diff --git a/ASSETS.md b/ASSETS.md index dbdd8b84d8..2c7a07478b 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -129,6 +129,7 @@ Generated-in-code art is original and has no file to list. This covers the defau | `assets/icons/dc-cap-square.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-center-hide.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-center-show.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-circle-points.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a circle with three dots on its edge) | MIT OR Apache-2.0 | | | `assets/icons/dc-clear.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-color-guide.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-contour.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a solid rounded square inside four corner arcs, its offset outline); not derived from any other application's icon | MIT OR Apache-2.0 | | diff --git a/Cargo.lock b/Cargo.lock index cec8e7aef7..cb0c72cc0c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6775,6 +6775,7 @@ dependencies = [ "craft-stream-codecs", "craft-xml", "crc32fast", + "encoding_rs", "flate2", "hayro-ccitt", "heic-rs", diff --git a/ROADMAP.md b/ROADMAP.md index 4358817b60..b3877be5c8 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -128,16 +128,20 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-14: Built-in Tech Circuit brush library: Circuit Trace (chamfered art with 45-degree elbows and terminal pads), Bus Lines (parallel conductor pattern) and Terminal Nodes (repeating solder pads, test points and leads), all original geometry generated in code. Ten built-in brush libraries; G5 remaining estimate 3–13 h (estimated), headline numbers unchanged. - 2026-11-05: Window › Toolbars › Keep Tools Beside the Canvas, off by default, docks the Tools panel between left-side panels and the canvas instead of at the window's left edge, and the canvas's left edge then also docks a floating Tools panel (`window.toolsBesideCanvas`, #5395). Workspaces keep the setting; workspaces saved without it keep Tools at the window's edge. An optional VectorCraft layout choice; headline numbers unchanged. +- 2026-11-17: The canvas's left edge docks a floating Tools panel whichever way Keep Tools Beside the Canvas is set: a drop there, right of panels docked on the left, turns the setting on, and a drop on the window's left edge turns it off (#7837). Headline numbers unchanged. - 2026-11-12: Stencil Bridges in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): strips of a set width are cut out of the selected art so that every island of a stencil cut from it (the inside of an O, a hole in a shape) stays attached to the sheet, by the shortest crossings first, vertical, horizontal or the shortest among 12 directions 15° apart, with up to 16 bridges per island; type is measured by its glyph outlines and stays type, and the original goes to a hidden layer or is replaced. One undo step (`addon.cutting.bridges`). A VectorCraft addition: headline numbers unchanged. - 2026-11-13: Banner Hems and Grommets in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): on the chosen sides of the selected art's bounds, or of each artboard, a hem line at a set depth inside the edge and grommet marks (a circle with a cross) at a set inset, one at each end of a side and the rest spread evenly at most a set spacing apart, stroked in a chosen swatch; a dialog with Preview, one undo step (`addon.cutting.banner`). A VectorCraft addition: headline numbers unchanged. - 2026-11-14: Nest Shapes in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): the selected objects move close together onto an artboard, a sheet of a set size or a roll of a set width, packed by their bounding boxes with a margin inside the edges and a spacing between them, optionally turning objects 90° to fit; objects that do not fit go in a column beside the sheet; a dialog with Preview, one undo step (`addon.cutting.nest`). A VectorCraft addition: headline numbers unchanged. - 2026-11-15: With Smart Guides and Snap to Tangent on, a circle drawn from its center with the Ellipse tool (Alt and Shift) snaps its radius so that the circle touches a nearby path (a straight segment, a curve, or another circle from outside or inside) when the radius comes within the snapping tolerance of that size, and the touch point shows the "tangent" label. A VectorCraft addition: headline numbers unchanged. - 2026-11-05: Release Type on a Path joins the Type Tools add-on (Object › Plug-ins › Type Tools): each selected type on a path splits into point type with the same text and attributes, on one straight line starting where its first character sat, and the plain path it was set on, with its exact shape and place in the stacking order and no paint; or keeps only the path or only the text, optionally leaving the original. A dialog with Preview, one undo step (`addon.type.releasePath`, #5532). A VectorCraft addition: headline numbers unchanged. +- 2026-11-14: Unit Converter add-on (Object › Plug-ins › Unit Converter): a panel with one field per unit (pt, picas, in, mm, cm, px, ft & in, m, yd, ft, Q, Ha) where a length typed in any field updates the others as it is typed; From Selection reads the selection's width or height, Apply sets it as one undo step, and each field copies its value with or without the unit (`addon.units.convert`, `addon.units.selectionSize`, #5528). A VectorCraft addition: headline numbers unchanged. - 2026-11-04: New Document: the units chosen in Preset Details now belong to the chosen document, as the pane's options are listed for the selected preset; the chosen card shows them, every other Recent and Saved card keeps the units its document or preset was made in, and the built-in tabs still follow the chosen units, so switching between inches and millimetres no longer restyles every recent template. Scores and estimates unchanged. - 2026-11-14: Packaging Tools add-on (Object › Plug-ins › Packaging Tools): fold line roles for dielines (Cut, Crease, Partial Cut, Perforation), each carried by the swatch on a path's top stroke through a per-document role table that native files keep; PDF prints a role line on its swatch's separation when that swatch is a spot color, as the default role swatches are, and SVG, DXF and HP-GL keep the stroke's color. Make Cut Line, Make Crease Line, Make Partial Cut Line and Make Perforation Line give the selected paths a role, overprinting by default, and make a missing role swatch; the Fold Lines panel counts each role in the selection or the document, and its Role Swatches… picks another swatch for a role (`addon.packaging.setRole`, `addon.packaging.roles`, `addon.packaging.setRoleSwatch`). A VectorCraft addition: headline numbers unchanged. - 2026-11-16: Check Fold Lines in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's Check button): the fold lines of the selection or the document are split into blanks, panels and hinges (cut lines bound the material, and creases, partial cuts and perforations divide it into panels), and 15 kinds of issue are listed, errors and warnings, each naming its lines: cut lines that enclose nothing or end loose, gaps closed within a tolerance, a cut on top of a crease, duplicate lines, creases that end inside a panel, divide nothing, lie outside the blank or are not straight, gaps too narrow to map, fold lines in a hole, panels joined by no crease, and fold lines on a non-printing layer. The panel lists the issues in the interface language; clicking one selects its lines (`addon.packaging.check`). A VectorCraft addition: headline numbers unchanged. +- 2026-11-16: Fold Preview in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's Fold Preview button): a window that folds the document's blank into its 3D shape about its largest panel, or the panel double-clicked, with the printed art on the outside of each panel (fold lines and non-printing layers left out, unless Show Fold Lines is on) and the board's inside color on the back. Creases and perforations fold 90° away from the print and partial cuts 90° toward it; a Fold slider goes from flat to folded, and the view turns by dragging and the arrow keys, zooms, moves and takes a perspective and seven view presets. The status line says when a joint does not close or two panels pass through each other (`addon.packaging.fold`, `ui.foldPreview`). A VectorCraft addition: headline numbers unchanged. - 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged. - 2026-11-15: Circle through three points: three Shift-clicks with the Ellipse tool, or `shape.circleThroughPoints` with three points or three selected anchor points, draw the circle whose edge passes through them, with the current paint, in one undo step; after two points the tool previews the circle through the pointer, and two points that are the same or three on one line are refused with a message. Scores and estimates unchanged. +- 2026-11-17: Circle tool (after the Ellipse tool in its group): two clicks or a drag draw the circle on that diameter, and a click followed by a drag from a second point to a third draws the circle through the three; Shift keeps the diameter at 45° steps, Alt rounds a two-point circle's diameter to the rulers' ticks at the current zoom, points snap to Smart Guides, and the tool shows the circle, its center, its radii and its diameter until the release, or "Circle too large" for points on one line or a circle past the canvas. `shape.circleThroughPoints` also takes two points or two selected anchor points as the ends of a diameter. One undo step per circle. A VectorCraft addition: headline numbers unchanged. - 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`). - 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged. - 2026-11-11: Pattern libraries: Patterns › Optical Effects, a third built-in pattern library, of VectorCraft's own designs, holds eight black wave, moiré and op-art tiles (Sine Bands, Ripple Lines, Interference Rings, Offset Rings, Warped Checks, Pinched Stripes, Chevron Pulse and Radiating Lenses) of 32 to 48 pt, each drawn the same way every time; each tile is one period of its design, and art that reaches past a tile edge continues on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged. @@ -151,6 +155,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-01: Divide into Dashes joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the selected paths, or only their direct-selected segments, are cut into separate open paths of a dash length measured along the curve, with an optional gap (left empty, or kept as pieces), each keeping the path's appearance; Fit to Corners and Ends stretches or squeezes the lengths so every run starts and ends on a dash. A dialog with Preview, one undo step, at most 100000 pieces. A VectorCraft addition: headline numbers unchanged. - 2026-11-15: Common Tangents in the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the straight lines that touch two selected convex closed paths (ellipses at any rotation and scale, or convex Bézier paths) without crossing either are added as open paths with the current stroke: external, internal or all, and the line joining the centers if asked; a path inside the other has none unless the two touch, and a message says why; a dialog with Preview, one undo step (`addon.pathtools.commonTangents`, #7845). A VectorCraft addition: headline numbers unchanged. - 2026-11-15: With Smart Guides and Snap to Tangent on, a Line Segment drag pressed on one convex curved path and dragged near another lands on a common tangent of the two: both ends move to where the line touches the paths, each labeled "tangent" (#7845). A VectorCraft addition: headline numbers unchanged. +- 2026-11-15: Smooth Bridge joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): two selected circles become one closed outline joined by two concave arcs that touch both circles, so every anchor is smooth; the arcs' radius is a percentage of the smaller circle's radius (1 to 1000%, 100% by default), and Keep Originals adds the outline above the circles instead of replacing them. A dialog with Preview, one undo step (`addon.pathtools.bridge`). A VectorCraft addition: headline numbers unchanged. - 2026-11-03: Text Tweaker, the first tool of the Type Tools add-on (Object › Plug-ins › Type Tools): one character attribute (size, baseline shift, rotation, horizontal or vertical scale, tracking, leading or stroke weight) goes letter by letter from a start value to an end value along a straight ramp, an ease, a bow, a spike or at random with a seed, set as the Character panel sets it, while the text stays live; a dialog with Preview, one undo step (`addon.type.textTweaker`, #4924). A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Group Overlapping Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects whose visual bounds overlap or touch, chains included, go into one group each, within their own layer or group, at the stacking place of their frontmost member; objects that overlap nothing stay as they are. One undo step, a sweep along x so thousands of loose pieces group quickly (at most 20000 objects). A VectorCraft addition: headline numbers unchanged. - 2026-10-31: Export for Screens works as the reference app's dialog: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File (the chosen artboards as one PDF's pages, `pdfs: "single"`) or Multiple Files, iOS and Android rows, format presets in a ☰ menu, and a count of the files the export writes (#4895). About 55 community PRs and fixes landed the same day: Find Font, Replace Font, Outline Stroke and Expand leave hidden and locked art alone (with a warning); DXF export writes LINE and ELLIPSE entities and outlines only the strokes a CAD line can't draw; Blob Brush Angle and Roundness; Shift-constrained Perspective Selection; Grid Repeat Options Preview; a gradient mesh from a file budgeted at about a million quads; width-profile strokes keep their shape zoomed out; `.ai`/EPS import fidelity (area type, envelopes, transparency in dictionaries, character styles); PDF import finds hyphenated and CMap-suffixed font names; Windows renders follow the process's core affinity; Enter or Escape in a floating panel's field no longer reaches the canvas (#4803); Properties shows Blend Options for any selected blend (#4817); Artwork Cleanup finds doubled type (#4835) and joins stacked lines into one object (Join Point Text, #4826). Headline numbers unchanged. diff --git a/apps/vectorcraft-cli/src/main.rs b/apps/vectorcraft-cli/src/main.rs index 4711232643..74f2095669 100644 --- a/apps/vectorcraft-cli/src/main.rs +++ b/apps/vectorcraft-cli/src/main.rs @@ -238,10 +238,12 @@ fn main() -> ExitCode { /// A headless session that remembers what the user keeps between runs: the PDF presets saved, the /// ICC profiles loaded, the plug-ins installed (#2168, #2174, #2541), the custom dictionary's words (#4936) and the Color Settings (#6335), in the folders /// and files next to the preferences that the desktop app uses too, and lists the scripts of the Scripts folder there -/// (`script.listInstalled`), keeps File Info's metadata templates there and starts new documents from the New Document profiles there. `VECTORCRAFT_NO_PREFS` and +/// (`script.listInstalled`), keeps each script's `Folder.userData` in the Script Data folder there, keeps File Info's +/// metadata templates there and starts new documents from the New Document profiles there. `VECTORCRAFT_NO_PREFS` and /// `VECTORCRAFT_CONFIG_DIR` apply as they do there. fn with_stores(mut h: Headless) -> Headless { prefs_dir::attach_scripts_dir(&mut h.session); + prefs_dir::attach_script_data(&mut h.session); prefs_dir::attach_metadata_templates_dir(&mut h.session); prefs_dir::attach_new_doc_profiles(&mut h.session); prefs_dir::attach_profile_store(&mut h.session); diff --git a/apps/vectorcraft-web/src/api.rs b/apps/vectorcraft-web/src/api.rs index eddd04f1b7..1be921baf3 100644 --- a/apps/vectorcraft-web/src/api.rs +++ b/apps/vectorcraft-web/src/api.rs @@ -142,7 +142,7 @@ fn send(method: &str, params: Value) -> Pin>> { }) } -async fn sleep(ms: i32) { +pub(crate) async fn sleep(ms: i32) { let promise = js_sys::Promise::new(&mut |resolve, _| { if let Some(window) = web_sys::window() { let _ = window.set_timeout_with_callback_and_timeout_and_arguments_0(&resolve, ms); diff --git a/apps/vectorcraft-web/src/demand.rs b/apps/vectorcraft-web/src/demand.rs new file mode 100644 index 0000000000..7583248701 --- /dev/null +++ b/apps/vectorcraft-web/src/demand.rs @@ -0,0 +1,139 @@ +//! Which `demand` web faces (`crates/text/web-fonts.txt`) to fetch: each face is fetched at most +//! once at a time and never again once it loaded. A face whose fetch failed is fetched again after +//! a wait that doubles with each failure, and not after [`MAX_TRIES`] failures. + +/// The wait after a face's first failed fetch before it is fetched again (ms). +const RETRY_MS: i32 = 30_000; +/// Failed fetches of a face after which it is not fetched again this session. +pub(crate) const MAX_TRIES: u32 = 5; + +#[derive(Clone, Copy, Debug, PartialEq)] +enum State { + Idle, + /// Being fetched, after `tries` failed fetches. + Loading { + tries: u32, + }, + Loaded, + /// `tries` fetches failed, the last at `failed_at` (ms); the next may start at `retry_at`, or + /// at once when the clock reads earlier than `failed_at`. + Failed { + tries: u32, + failed_at: f64, + retry_at: f64, + }, +} + +/// The fetch state of each face of a web font list, by index. +#[derive(Debug, Default)] +pub(crate) struct Demand { + states: Vec, +} + +impl Demand { + /// Of the faces `wanted` (indexes into the list), the ones to fetch at time `now` (ms): not + /// loaded, not being fetched, and not waiting to be fetched again. They are marked as being + /// fetched. + pub(crate) fn start(&mut self, wanted: &[usize], now: f64) -> Vec { + let mut out = Vec::new(); + for &i in wanted { + if self.states.len() <= i { + self.states.resize(i + 1, State::Idle); + } + let Some(state) = self.states.get_mut(i) else { continue }; + let tries = match *state { + State::Idle => Some(0), + State::Loading { .. } | State::Loaded => None, + State::Failed { tries, failed_at, retry_at } => (tries < MAX_TRIES && (now >= retry_at || now < failed_at)).then_some(tries), + }; + if let Some(tries) = tries { + *state = State::Loading { tries }; + out.push(i); + } + } + out + } + + /// The fetch of face `i` started by [`Demand::start`] ended at `now` (ms): loaded when `ok`. + /// Returns the wait (ms) after which a failed face may be fetched again, or `None` when it + /// loaded or has failed [`MAX_TRIES`] times. + pub(crate) fn finished(&mut self, i: usize, ok: bool, now: f64) -> Option { + let state = self.states.get_mut(i)?; + let State::Loading { tries } = *state else { return None }; + if ok { + *state = State::Loaded; + return None; + } + let tries = tries + 1; + let wait = RETRY_MS << (tries - 1).min(4); + *state = State::Failed { tries, failed_at: now, retry_at: now + f64::from(wait) }; + (tries < MAX_TRIES).then_some(wait) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_face_is_fetched_once_and_kept() { + let mut d = Demand::default(); + assert_eq!(d.start(&[2], 0.0), [2]); + assert!(d.start(&[2], 1.0).is_empty(), "already being fetched"); + assert_eq!(d.finished(2, true, 2.0), None, "loaded: no retry"); + assert!(d.start(&[2], 1e9).is_empty(), "loaded: never fetched again"); + assert_eq!(d.start(&[0, 2, 1], 3.0), [0, 1], "other faces start on their own"); + assert_eq!(d.finished(7, false, 4.0), None, "a face never started"); + } + + #[test] + fn a_failed_face_waits_longer_after_each_failure_and_then_stops() { + let mut d = Demand::default(); + let mut now = 0.0; + // The wait after the 1st, 2nd, ... failure: doubling, up to 16 times the first. + for wait in [1, 2, 4, 8].map(|k| k * RETRY_MS) { + assert_eq!(d.start(&[0], now), [0], "at {now}"); + assert_eq!(d.finished(0, false, now), Some(wait), "the wait after the failure at {now}"); + assert!(d.start(&[0], now + f64::from(wait) - 1.0).is_empty(), "waits {wait} ms after the failure at {now}"); + now += f64::from(wait); + } + // The fifth fetch, and after it fails, none. + assert_eq!(d.start(&[0], now), [0]); + assert_eq!(d.finished(0, false, now), None, "no retry after {MAX_TRIES} failures"); + assert!(d.start(&[0], now + 1e12).is_empty(), "no fetch after {MAX_TRIES} failures"); + // A later success after failures keeps the face. + let mut d = Demand::default(); + d.start(&[1], 0.0); + assert_eq!(d.finished(1, false, 0.0), Some(RETRY_MS)); + assert_eq!(d.start(&[1], f64::from(RETRY_MS)), [1]); + assert_eq!(d.finished(1, true, f64::from(RETRY_MS)), None); + assert!(d.start(&[1], 1e12).is_empty()); + } + + /// While a face is fetched again after a failure, neither the interface asking for its script + /// again nor the retry timer starts a second fetch of it. + #[test] + fn a_face_being_fetched_again_is_not_fetched_twice_at_once() { + let mut d = Demand::default(); + d.start(&[0], 0.0); + assert_eq!(d.finished(0, false, 0.0), Some(RETRY_MS)); + let retry = f64::from(RETRY_MS); + assert_eq!(d.start(&[0, 0], retry), [0], "one fetch for a face wanted twice"); + assert!(d.start(&[0], retry + 1.0).is_empty(), "the interface asking again"); + assert!(d.start(&[0], retry + 1_000.0).is_empty(), "the retry timer"); + assert_eq!(d.finished(0, true, retry + 2_000.0), None); + assert!(d.start(&[0], 1e12).is_empty(), "loaded"); + } + + /// A clock that reads earlier than the failure (one set back meanwhile) does not hold the + /// retry back: the timer that asks for it has waited already. + #[test] + fn a_clock_set_back_after_a_failure_does_not_stop_the_retry() { + let mut d = Demand::default(); + let failed_at = 1e12; + d.start(&[0], failed_at); + assert_eq!(d.finished(0, false, failed_at), Some(RETRY_MS)); + assert!(d.start(&[0], failed_at + 1.0).is_empty(), "still waiting"); + assert_eq!(d.start(&[0], failed_at - 3_600_000.0), [0], "the clock went back an hour"); + } +} diff --git a/apps/vectorcraft-web/src/fonts.rs b/apps/vectorcraft-web/src/fonts.rs index 2677c11edf..873474f6c3 100644 --- a/apps/vectorcraft-web/src/fonts.rs +++ b/apps/vectorcraft-web/src/fonts.rs @@ -1,17 +1,22 @@ //! Craft-fonts faces served beside the wasm (`fonts//…`, copied by //! `cargo xtask web-fonts`) instead of embedded: [`load_startup_fonts`] fetches the `startup` -//! ones before the app starts, [`spawn_background_fonts`] the rest once it runs. The browser checks -//! each file against its SHA-256 (Subresource Integrity). A face that fails is logged and skipped: -//! the app runs without it. With `WEB_FONTS` empty (built without craft-fonts) both do nothing. +//! ones before the app starts, [`spawn_background_fonts`] the `background` ones once it runs, and +//! [`want_chars`] a `demand` face (Korean, Devanagari) when the interface language or the +//! interface's own text needs its script. The browser checks each file against its SHA-256 +//! (Subresource Integrity). A face that fails is logged and skipped: the app runs without it. With +//! `WEB_FONTS` empty (built without craft-fonts) these do nothing. -use std::cell::Cell; +use std::cell::{Cell, RefCell}; use std::rc::Rc; +use vectorcraft_text::craft_fonts::demand_fonts; use vectorcraft_text::{FontDb, WEB_FONTS, WebFont}; use wasm_bindgen::JsCast as _; use wasm_bindgen::closure::Closure; use wasm_bindgen_futures::JsFuture; +use crate::demand::Demand; + /// Per startup face: the page shows its loading text meanwhile. const STARTUP_TIMEOUT_MS: i32 = 20_000; /// Per background face. @@ -22,12 +27,49 @@ const BACKGROUND_PARALLEL: usize = 4; thread_local! { /// The background fetch runs once per page, though a graphics restart creates the app again. static BACKGROUND_STARTED: Cell = const { Cell::new(false) }; + /// The `demand` faces' fetches. + static DEMAND: RefCell = RefCell::new(Demand::default()); + /// The running app's context, asked for a frame when a `demand` face arrives (none before the + /// app starts: its first frame looks through the faces loaded by then). + static REPAINT: RefCell> = const { RefCell::new(None) }; +} + +/// Fetch, in the background, the `demand` faces for the scripts of `chars` that are not loaded or +/// being fetched. Each one that arrives asks the app for a frame, and the interface draws those +/// characters with it from then on. Set as the interface's missing-glyph handler +/// (`vectorcraft_ui_egui::on_missing_glyphs`), and called with the interface language's name +/// before the app starts. +pub fn want_chars(chars: &[char]) { + let wanted = demand_fonts(WEB_FONTS, chars.iter().copied()); + if !wanted.is_empty() { + fetch_demand(&wanted); + } +} + +/// Fetch the `demand` faces `wanted` (indexes into `WEB_FONTS`) that [`Demand::start`] lets start. +/// A face whose fetch fails is fetched again after the wait [`Demand::finished`] gives. +fn fetch_demand(wanted: &[usize]) { + for i in DEMAND.with(|d| d.borrow_mut().start(wanted, vectorcraft_ui_egui::now_ms())) { + let Some(f) = WEB_FONTS.get(i) else { continue }; + wasm_bindgen_futures::spawn_local(async move { + let ok = load(f, BACKGROUND_TIMEOUT_MS).await; + let retry = DEMAND.with(|d| d.borrow_mut().finished(i, ok, vectorcraft_ui_egui::now_ms())); + if ok && let Some(ctx) = REPAINT.with(|r| r.borrow().clone()) { + ctx.request_repaint(); + } + if let Some(wait) = retry { + // A second longer, so a clock the browser coarsens still reads the wait as over. + crate::api::sleep(wait.saturating_add(1_000)).await; + fetch_demand(&[i]); + } + }); + } } /// Fetch and register the `startup` faces (one after the other). Returns how many loaded. pub async fn load_startup_fonts() -> usize { let mut loaded = 0; - for f in WEB_FONTS.iter().filter(|f| f.startup) { + for f in WEB_FONTS.iter().filter(|f| f.startup && !f.demand) { if load(f, STARTUP_TIMEOUT_MS).await { loaded += 1; } @@ -36,13 +78,14 @@ pub async fn load_startup_fonts() -> usize { } /// Fetch and register the `background` faces, [`BACKGROUND_PARALLEL`] at a time, asking `ctx` for -/// a frame after each so the font menus and the canvas pick it up. Only the first call does -/// anything. +/// a frame after each so the font menus and the canvas pick it up. Only the first call fetches +/// anything; each call makes `ctx` the context a `demand` face asks for a frame. pub fn spawn_background_fonts(ctx: egui::Context) { + REPAINT.with(|r| *r.borrow_mut() = Some(ctx.clone())); if BACKGROUND_STARTED.with(|s| s.replace(true)) { return; } - let queue: Rc> = Rc::new(WEB_FONTS.iter().filter(|f| !f.startup).collect()); + let queue: Rc> = Rc::new(WEB_FONTS.iter().filter(|f| !f.startup && !f.demand).collect()); let next = Rc::new(Cell::new(0usize)); for _ in 0..BACKGROUND_PARALLEL.min(queue.len()) { let (queue, next, ctx) = (queue.clone(), next.clone(), ctx.clone()); diff --git a/apps/vectorcraft-web/src/main.rs b/apps/vectorcraft-web/src/main.rs index 457d8d4640..b71b51b566 100644 --- a/apps/vectorcraft-web/src/main.rs +++ b/apps/vectorcraft-web/src/main.rs @@ -21,6 +21,8 @@ #[cfg(target_arch = "wasm32")] mod api; +#[cfg(any(target_arch = "wasm32", test))] +mod demand; #[cfg(target_arch = "wasm32")] mod fonts; #[cfg(any(target_arch = "wasm32", test))] diff --git a/apps/vectorcraft-web/src/web.rs b/apps/vectorcraft-web/src/web.rs index 2de7f3b481..6d9e0cadd5 100644 --- a/apps/vectorcraft-web/src/web.rs +++ b/apps/vectorcraft-web/src/web.rs @@ -81,6 +81,11 @@ pub fn start() { return; }; detect_language(); + // The face for a Korean or Hindi browser language (or `?lang=`) starts loading now, beside the + // startup fonts, without holding up the start. Text in those scripts painted later (a saved + // interface language, another one chosen, a layer or file name) has its face fetched then. + vectorcraft_ui_egui::on_missing_glyphs(crate::fonts::want_chars); + crate::fonts::want_chars(&i18n::system_lang().name().chars().collect::>()); wasm_bindgen_futures::spawn_local(async move { // Before the first frame, which looks for copies a crash left behind. let locks = WebLocks::start(RECOVERY_PREFIX).await; diff --git a/apps/vectorcraft/src/app.rs b/apps/vectorcraft/src/app.rs index dddaf0a91e..a40eb0c92f 100644 --- a/apps/vectorcraft/src/app.rs +++ b/apps/vectorcraft/src/app.rs @@ -43,6 +43,16 @@ impl eframe::App for App { /// Restore the borderless caption, apply platform menu and pen input, and hand the frame to the /// app's raw-input hook while the keyboard user is unconfined. fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) { + // Without vsync, a main-window frame starts no sooner than the minimum interval after the + // last one. eframe runs this hook once per frame, shown or not, before egui reads the input. + // The frame's time moves on by the wait, and the hang report's frame time starts after it. + if raw.viewport_id == egui::ViewportId::ROOT { + if let Some(wait) = super::presentation::frame_wait(self.min_frame, self.last_frame_began.map(|t| t.elapsed())) { + std::thread::sleep(wait); + raw.time = raw.time.map(|time| time + wait.as_secs_f64()); + } + self.last_frame_began = Some(std::time::Instant::now()); + } let _timed = BEACON.enter_timed(Stage::Input); self.frame_start = Some(std::time::Instant::now()); // winit gives the window its caption back when it changes the window's flags (maximize, diff --git a/apps/vectorcraft/src/display_profile.rs b/apps/vectorcraft/src/display_profile.rs index 2be6e27aa5..ee35a407a7 100644 --- a/apps/vectorcraft/src/display_profile.rs +++ b/apps/vectorcraft/src/display_profile.rs @@ -10,7 +10,7 @@ //! - macOS: the window's layer is tagged sRGB and macOS converts it (`mac_color_space`). //! //! While the preference is on, a background thread reads the display every [`EVERY`] seconds, -//! and at once when the window moves to another display. +//! and at once when the window moves to another display or Edit › Refresh Monitor Profile asks. use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; @@ -31,6 +31,8 @@ pub(crate) struct Reader { looked: Option, /// A reading is running. busy: Arc, + /// [`DisplayProfile::attach_reader`] was called. + attached: bool, } /// Clears [`Reader::busy`] when the reading thread ends, also by a panic. @@ -45,22 +47,22 @@ impl Drop for Done { impl Reader { /// Starts a reading when one is due and none is running. `now` is the frame's time in seconds. pub(crate) fn tick(&mut self, window: &winit::window::Window, now: f64, enabled: bool, profile: &DisplayProfile, ctx: &egui::Context) { - if !enabled || self.busy.load(Ordering::Acquire) || self.looked.is_some_and(|at| (at..at + LOOK_EVERY).contains(&now)) { - return; + if !self.attached { + profile.attach_reader(); + self.attached = true; } - self.looked = Some(now); - let display = window.current_monitor().and_then(|m| m.name()); - if !due(self.last.as_ref(), now, display.as_deref()) { + let Some(display) = self.start(now, enabled, profile, || window.current_monitor().and_then(|m| m.name())) else { return; - } - self.last = Some((now, display.clone())); + }; profile.pending(); self.busy.store(true, Ordering::Release); let done = Done(self.busy.clone()); let (profile, ctx) = (profile.clone(), ctx.clone()); let spawned = std::thread::Builder::new().name("display profile".into()).spawn(move || { - let _done = done; - if profile.report(read(display)) { + let changed = profile.report(read(display)); + drop(done); + // A request made while this reading ran starts on the next frame. + if changed || profile.read_requested() { ctx.request_repaint(); } }); @@ -68,6 +70,32 @@ impl Reader { log::warn!("couldn't start reading the display profile: {e}"); } } + + /// The display to read at `now` when a reading is to start, looked up with `display`. A + /// request from Refresh Monitor Profile ([`DisplayProfile::request_read`]) starts one at once, + /// past [`EVERY`] and [`LOOK_EVERY`]; while a reading runs it waits, and a frame that finds the + /// preference off drops it. A request made with the preference on is kept when the preference + /// goes off and on again between two frames. + fn start(&mut self, now: f64, enabled: bool, profile: &DisplayProfile, display: impl FnOnce() -> Option) -> Option> { + if !enabled { + profile.take_request(); + return None; + } + if self.busy.load(Ordering::Acquire) { + return None; + } + let asked = profile.take_request(); + if !asked && self.looked.is_some_and(|at| (at..at + LOOK_EVERY).contains(&now)) { + return None; + } + self.looked = Some(now); + let display = display(); + if !asked && !due(self.last.as_ref(), now, display.as_deref()) { + return None; + } + self.last = Some((now, display.clone())); + Some(display) + } } /// Whether a reading of `display` is due at `now`, after the last one (`last`): none yet, another @@ -570,6 +598,56 @@ mod tests { assert!(due(Some(&last), 50.0, Some("DP-1"))); } + fn attached() -> DisplayProfile { + let profile = DisplayProfile::default(); + profile.attach_reader(); + profile + } + + #[test] + fn a_requested_reading_starts_on_the_next_frame_past_both_intervals() { + let (mut r, profile) = (Reader::default(), attached()); + let dp1 = || Some("DP-1".to_string()); + assert_eq!(r.start(100.0, true, &profile, dp1), Some(Some("DP-1".into()))); + // Inside the display lookup interval and the reading interval: nothing starts. + assert_eq!(r.start(100.5, true, &profile, || panic!("not looked up")), None); + assert_eq!(r.start(102.0, true, &profile, dp1), None); + profile.request_read(true).unwrap(); + assert_eq!(r.start(102.1, true, &profile, dp1), Some(Some("DP-1".into()))); + assert!(!profile.read_requested(), "the request is taken"); + // The intervals run again from the requested reading. + assert_eq!(r.start(102.2, true, &profile, dp1), None); + assert_eq!(r.start(111.0, true, &profile, dp1), None); + assert_eq!(r.start(113.0, true, &profile, dp1), Some(Some("DP-1".into()))); + } + + #[test] + fn a_request_made_while_a_reading_runs_waits_for_it_to_end() { + let (mut r, profile) = (Reader::default(), attached()); + let dp1 = || Some("DP-1".to_string()); + assert!(r.start(0.0, true, &profile, dp1).is_some()); + r.busy.store(true, Ordering::Release); + profile.request_read(true).unwrap(); + assert_eq!(r.start(0.1, true, &profile, dp1), None); + assert_eq!(r.start(5.0, true, &profile, dp1), None); + assert!(profile.read_requested(), "kept while the reading runs"); + r.busy.store(false, Ordering::Release); + assert_eq!(r.start(5.1, true, &profile, dp1), Some(Some("DP-1".into()))); + assert!(!profile.read_requested()); + } + + #[test] + fn a_request_is_dropped_when_the_preference_goes_off() { + let (mut r, profile) = (Reader::default(), attached()); + let dp1 = || Some("DP-1".to_string()); + assert!(r.start(0.0, true, &profile, dp1).is_some()); + profile.request_read(true).unwrap(); + assert_eq!(r.start(0.1, false, &profile, dp1), None); + assert!(!profile.read_requested()); + assert_eq!(r.start(0.2, true, &profile, dp1), None, "no reading starts later for it"); + assert!(profile.request_read(false).is_err()); + } + #[test] fn wayland_sessions_are_told_apart_from_x11_by_the_environment() { let env = |pairs: &'static [(&'static str, &'static str)]| { diff --git a/apps/vectorcraft/src/host_services.rs b/apps/vectorcraft/src/host_services.rs index 2ed939245f..1ce124c1dd 100644 --- a/apps/vectorcraft/src/host_services.rs +++ b/apps/vectorcraft/src/host_services.rs @@ -73,7 +73,7 @@ fn open_extensions(exts: &[impl AsRef], any_case: bool) -> Vec { /// `d` set up for `request`: its title, file types, folder and suggested name. fn dialog_for(d: D, request: &PickRequest) -> D { let pick = match request { - PickRequest::Open(pick) | PickRequest::Save(pick) => pick, + PickRequest::Open(pick) | PickRequest::Save(pick) | PickRequest::OpenFiles(pick) => pick, PickRequest::OpenMany => { return fileio::place_filters().fold(d.title(vectorcraft_ui_egui::i18n::t("Place")), |d, (name, exts)| { d.filter( @@ -83,8 +83,9 @@ fn dialog_for(d: D, request: &PickRequest) -> D { }); } PickRequest::Folder => return d, + PickRequest::FolderAt(folder) => return d.folder(folder), }; - let any_case = CASE_SENSITIVE_FILTERS && matches!(request, PickRequest::Open(_)); + let any_case = CASE_SENSITIVE_FILTERS && matches!(request, PickRequest::Open(_) | PickRequest::OpenFiles(_)); let d = pick.filters.iter().fold(d, |d, (name, exts)| { d.filter( vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", name.as_str()), @@ -95,7 +96,55 @@ fn dialog_for(d: D, request: &PickRequest) -> D { Some(folder) => d.folder(folder), None => d, }; - if pick.name.is_empty() { d } else { d.file_name(&pick.name) } + if pick.name.is_empty() { + return d; + } + // Windows' save dialog changes the extension when a different file type is chosen only when + // the suggested name has no explicit extension. rfd supplies the first filter's extension to + // that dialog, so leave the suffix to Windows for saves that offer several formats (#5451). + // A remaining dot in the stem would look like another explicit extension to Windows. + #[cfg(windows)] + if matches!(request, PickRequest::Save(_)) + && pick.filters.len() > 1 + && let Some(ext) = std::path::Path::new(&pick.name).extension().and_then(|e| e.to_str()) + && pick.filters.iter().any(|(_, exts)| exts.iter().any(|e| e.eq_ignore_ascii_case(ext))) + && let Some(stem) = std::path::Path::new(&pick.name).file_stem().and_then(|s| s.to_str()) + && !stem.contains('.') + { + return d.file_name(stem); + } + d.file_name(&pick.name) +} + +#[cfg(test)] +#[test] +fn a_folder_picker_asked_for_a_folder_starts_there() { + /// The settings a dialog was given, by name. + #[derive(Default)] + struct Recorded(Vec); + impl DialogSettings for Recorded { + fn parent(self, _: &winit::window::Window) -> Self { + self + } + fn title(mut self, title: &str) -> Self { + self.0.push(format!("title {title}")); + self + } + fn filter(mut self, name: &str, _: &[impl ToString]) -> Self { + self.0.push(format!("filter {name}")); + self + } + fn folder(mut self, folder: &str) -> Self { + self.0.push(format!("folder {folder}")); + self + } + fn file_name(mut self, name: &str) -> Self { + self.0.push(format!("name {name}")); + self + } + } + assert_eq!(dialog_for(Recorded::default(), &PickRequest::FolderAt("/a/b".into())).0, ["folder /a/b"]); + assert!(dialog_for(Recorded::default(), &PickRequest::Folder).0.is_empty()); } /// A native file dialog for `request` over `parent` (on Linux the portal then shows it over the @@ -130,9 +179,9 @@ fn show_dialog(dialog: rfd::FileDialog, request: &PickRequest, parent: &Parent) } let paths = match request { PickRequest::Open(_) => dialog.pick_file().into_iter().collect(), - PickRequest::OpenMany => dialog.pick_files().unwrap_or_default(), + PickRequest::OpenMany | PickRequest::OpenFiles(_) => dialog.pick_files().unwrap_or_default(), PickRequest::Save(_) => dialog.save_file().into_iter().collect(), - PickRequest::Folder => dialog.pick_folder().into_iter().collect(), + PickRequest::Folder | PickRequest::FolderAt(_) => dialog.pick_folder().into_iter().collect(), }; paths.into_iter().map(|p| p.to_string_lossy().to_string()).collect() } @@ -315,7 +364,7 @@ fn start_pick(request: PickRequest, parent: &Parent, ui: &egui::Context) -> Opti let picked = dialog.pick_file(); Box::pin(async move { picked.await.iter().map(path).collect() }) } - PickRequest::OpenMany => { + PickRequest::OpenMany | PickRequest::OpenFiles(_) => { let picked = dialog.pick_files(); Box::pin(async move { picked.await.unwrap_or_default().iter().map(path).collect() }) } @@ -334,7 +383,7 @@ fn start_pick(request: PickRequest, parent: &Parent, ui: &egui::Context) -> Opti // on that nil; treat the pick as cancelled instead (#5980). Err(()) => Box::pin(async move { Vec::new() }), }, - PickRequest::Folder => { + PickRequest::Folder | PickRequest::FolderAt(_) => { let picked = dialog.pick_folder(); Box::pin(async move { picked.await.iter().map(path).collect() }) } @@ -355,7 +404,7 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services { .and_then(|w| w.window_handle().ok()) .is_some_and(|h| matches!(h.as_raw(), RawWindowHandle::Xlib(_) | RawWindowHandle::Xcb(_))); let (clip, clip_probe) = (parent.clone(), parent.clone()); - let (p1, p2, p3, p4, p5) = (parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent); + let (p1, p2, p3, p4, p5, p6, p7) = (parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent); #[cfg(any(target_os = "macos", target_os = "linux", windows))] let sampled_ui = ui.clone(); #[cfg(target_os = "linux")] @@ -363,6 +412,7 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services { Services { pick_open: Some(Box::new(move |pick: &FilePick| pick_now(PickRequest::Open(pick.clone()), &p1).into_iter().next())), pick_open_multi: Some(Box::new(move || pick_now(PickRequest::OpenMany, &p2))), + pick_open_files: Some(Box::new(move |pick: &FilePick| pick_now(PickRequest::OpenFiles(pick.clone()), &p6))), pick_save: Some(Box::new(move |pick: &FilePick| pick_now(PickRequest::Save(pick.clone()), &p3).into_iter().next())), // Linux shows dialogs on a thread of their own (#592), macOS as sheets (#867); Windows // dialogs run the window's events while they are open. @@ -410,6 +460,7 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services { // Edit Original of a raster image with Use System Defaults for Edit Original off (#5236). open_in_photocraft: Some(Box::new(open_in_photocraft)), pick_folder: Some(Box::new(move || pick_now(PickRequest::Folder, &p4).into_iter().next())), + pick_folder_at: Some(Box::new(move |start: &str| pick_now(PickRequest::FolderAt(start.to_string()), &p7).into_iter().next())), // Sample Color from Screen: the system's color sampler. #[cfg(target_os = "macos")] screen_color: Some(mac_screen_color::sampler(sampled_ui)), @@ -762,7 +813,7 @@ mod dialog_tests { /// The file types a dialog was given, by label. #[derive(Default)] - struct Filters(Vec<(String, Vec)>); + struct Filters(Vec<(String, Vec)>, Option); impl DialogSettings for Filters { fn parent(self, _window: &winit::window::Window) -> Self { @@ -778,7 +829,8 @@ mod dialog_tests { fn folder(self, _folder: &str) -> Self { self } - fn file_name(self, _name: &str) -> Self { + fn file_name(mut self, name: &str) -> Self { + self.1 = Some(name.to_string()); self } } @@ -835,4 +887,24 @@ mod dialog_tests { let first = fileio::place_filters().next().map(|(_, exts)| open_extensions(exts, CASE_SENSITIVE_FILTERS)); assert_eq!(placed.first().map(|(_, exts)| exts.clone()), first); } + + /// A format selected after the Windows Save As dialog opens can replace the suffix of the + /// suggested name. Single-format saves and open dialogs keep the supplied name verbatim. + #[cfg(windows)] + #[test] + fn save_dialog_with_several_formats_leaves_the_extension_to_windows() { + let filters = vec![FilePick::filter("VectorCraft", &["vectorcraft"]), FilePick::filter("PDF-compatible .ai", &["ai"])]; + let pick = FilePick { name: "Poster.vectorcraft".into(), filters: filters.clone(), ..Default::default() }; + assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick.clone())).1.as_deref(), Some("Poster")); + assert_eq!(dialog_for(Filters::default(), &PickRequest::Open(pick)).1.as_deref(), Some("Poster.vectorcraft")); + + let pick = FilePick { name: "Poster.AI".into(), filters: filters.clone(), ..Default::default() }; + assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick)).1.as_deref(), Some("Poster")); + let pick = FilePick { name: "Poster.design".into(), filters: filters.clone(), ..Default::default() }; + assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick)).1.as_deref(), Some("Poster.design")); + let pick = FilePick { name: "draft.v1.vectorcraft".into(), filters: filters.clone(), ..Default::default() }; + assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick)).1.as_deref(), Some("draft.v1.vectorcraft")); + let pick = FilePick { name: "Poster.vectorcraft".into(), filters: vec![filters[0].clone()], ..Default::default() }; + assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick)).1.as_deref(), Some("Poster.vectorcraft")); + } } diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index 4f8e326981..1778503201 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -142,6 +142,11 @@ struct App { display_profile: display_profile::Reader, /// When this frame's input hook started, for the hang report's frame times (`hang_watch`). frame_start: Option, + /// The shortest time between the starts of two frames, while the window presents without vsync + /// ([`presentation::min_frame_interval`]). + min_frame: Option, + /// When the last frame started, after its wait for [`Self::min_frame`]. + last_frame_began: Option, } /// `vectorcraft --help`. Headless work (convert, run, MCP) is `vectorcraft-cli`'s. @@ -365,6 +370,10 @@ fn main() -> std::process::ExitCode { let saved_window = saved.as_ref().and_then(|ui| ui.window); #[cfg(feature = "wgpu")] let gpu_pref = saved.as_ref().and_then(|ui| ui.engine_prefs.get("gpuPreference")).and_then(serde_json::Value::as_str); + // Preferences › Performance › Low-Latency Drawing; anything but `true` in the file is off. + #[cfg(feature = "wgpu")] + let low_latency_drawing = + saved.as_ref().and_then(|ui| ui.engine_prefs.get("lowLatencyDrawing")).and_then(serde_json::Value::as_bool).unwrap_or(false); #[cfg(feature = "wgpu")] let power_env = eframe::wgpu::PowerPreference::from_env(); #[cfg(feature = "wgpu")] @@ -458,10 +467,11 @@ fn main() -> std::process::ExitCode { let mut options = options; // One frame queued, not two: the canvas is rasterized on the CPU and the GPU only // composites it, so the window answers the pointer a frame sooner (#444). - // `--present-mode` and `--frame-latency` change it for a launch (`presentation`). - options.wgpu_options.surface = presentation.apply(eframe::egui_wgpu::SurfaceConfig::LOW_LATENCY); + // `--present-mode` and `--frame-latency` change it for a launch, and Low-Latency Drawing + // asks for no vsync when neither sets the mode (`presentation`). + options.wgpu_options.surface = presentation.apply(eframe::egui_wgpu::SurfaceConfig::LOW_LATENCY, low_latency_drawing); // What the app asks for: the driver picks novsync's mode and may clamp the latency. - log::info!("requested window surface: {}", presentation::describe(&options.wgpu_options.surface, &presentation)); + log::info!("requested window surface: {}", presentation::describe(&options.wgpu_options.surface, &presentation, low_latency_drawing)); // Only adapters that can show the window, in the order `gpu` gives (#306, #502). if let eframe::egui_wgpu::WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup { create.native_adapter_selector = Some(gpu::selector(power, displays, compositor, left_out.adapters.clone(), startup.clone())); @@ -508,6 +518,11 @@ fn main() -> std::process::ExitCode { // For the hang report (`hang_watch`). #[cfg(feature = "wgpu")] let requested_surface = options.wgpu_options.surface; + // Without vsync, frames start at most 240 times a second (`presentation`). + #[cfg(feature = "wgpu")] + let min_frame = presentation::min_frame_interval(&requested_surface); + #[cfg(not(feature = "wgpu"))] + let min_frame = None; // A panic that ends the window (egui-wgpu's own, #502) is caught here: never a crash. let run = |options: eframe::NativeOptions, app_creator: eframe::AppCreator<'_>| { #[cfg(target_os = "linux")] @@ -539,6 +554,7 @@ fn main() -> std::process::ExitCode { // File Info's metadata templates live in their own folder next to the preferences. prefs_dir::attach_metadata_templates_dir(&mut session); prefs_dir::attach_new_doc_profiles(&mut session); + prefs_dir::attach_script_data(&mut session); let mut app = VectorcraftApp::new(session, services(cc.winit_window().cloned(), cc.egui_ctx.clone())); app.set_startup_update_check(true); load_prefs(&mut app, saved); @@ -694,6 +710,8 @@ fn main() -> std::process::ExitCode { monitors_listed: None, display_profile: Default::default(), frame_start: None, + min_frame, + last_frame_began: None, })) }), ) diff --git a/apps/vectorcraft/src/prefs_dir.rs b/apps/vectorcraft/src/prefs_dir.rs index 1a33352ffc..d9defc5686 100644 --- a/apps/vectorcraft/src/prefs_dir.rs +++ b/apps/vectorcraft/src/prefs_dir.rs @@ -81,6 +81,15 @@ pub fn attach_new_doc_profiles(session: &mut vectorcraft_engine::Session) { } } +/// Keep each script's `Folder.userData` in the `Script Data` folder, and the file access people +/// allow scripts with Always in `Script Grants.json` beside it. Both are made when a script first +/// needs them. +pub fn attach_script_data(session: &mut vectorcraft_engine::Session) { + if let Some(dir) = store_dir("Script Data") { + session.attach_script_data(dir); + } +} + /// Take the saved PDF presets from the `PDF Presets` folder (#2168), and keep the ones saved from /// now on there. After the preferences were restored: the folder is the one place the presets live. pub fn attach_pdf_preset_store(session: &mut vectorcraft_engine::Session) { diff --git a/apps/vectorcraft/src/presentation.rs b/apps/vectorcraft/src/presentation.rs index 7c2f1dc48a..76438ab996 100644 --- a/apps/vectorcraft/src/presentation.rs +++ b/apps/vectorcraft/src/presentation.rs @@ -6,9 +6,17 @@ //! frames the swap chain may queue, 1 to 3. Unset, the app keeps its own surface settings. A flag //! overrides its variable; a value that isn't one of these stops the app with a message, as //! `--control` does. A launch that sets either one runs as its own app, as with `--new-instance`. -//! The surface the app asks for is logged at start-up. +//! Preferences › Performance › Low-Latency Drawing (`lowLatencyDrawing`, off by default, read at +//! start-up) asks for `novsync` when neither the flag nor the variable sets the mode. Whenever the +//! surface presents without vsync, frames start at most 240 times a second. The surface the app +//! asks for is logged at start-up, with where its present mode came from. use std::ffi::OsString; +use std::time::Duration; + +/// The most frames a second the window draws while it presents without vsync. +#[cfg(feature = "wgpu")] +pub const UNSYNCED_FRAME_CAP: u32 = 240; /// A present mode the command line or the environment can ask for. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -96,25 +104,44 @@ impl Overrides { Ok(Self { mode, latency }) } - /// `surface` with the overrides applied. + /// `surface` with the overrides applied. With Low-Latency Drawing on (`low_latency_drawing`) and + /// no present mode override, the mode is `novsync`. #[cfg(feature = "wgpu")] - pub fn apply(&self, surface: eframe::egui_wgpu::SurfaceConfig) -> eframe::egui_wgpu::SurfaceConfig { + pub fn apply(&self, surface: eframe::egui_wgpu::SurfaceConfig, low_latency_drawing: bool) -> eframe::egui_wgpu::SurfaceConfig { use eframe::wgpu::PresentMode; let present_mode = match self.mode { Some(Mode::Fifo) => PresentMode::Fifo, Some(Mode::AutoVsync) => PresentMode::AutoVsync, Some(Mode::NoVsync) => PresentMode::AutoNoVsync, + None if low_latency_drawing => PresentMode::AutoNoVsync, None => surface.present_mode, }; eframe::egui_wgpu::SurfaceConfig { present_mode, desired_maximum_frame_latency: self.latency.or(surface.desired_maximum_frame_latency) } } } -/// The present mode and frame latency `surface` asks for, for the start-up log: -/// "autovsync, frame latency 1", with "(override)" -/// after a value a flag or variable set. +/// The shortest time between the starts of two frames on `surface`: `None` with vsync, where the +/// display paces the frames, and 1/[`UNSYNCED_FRAME_CAP`] of a second without it. #[cfg(feature = "wgpu")] -pub fn describe(surface: &eframe::egui_wgpu::SurfaceConfig, overrides: &Overrides) -> String { +pub fn min_frame_interval(surface: &eframe::egui_wgpu::SurfaceConfig) -> Option { + use eframe::wgpu::PresentMode; + match surface.present_mode { + PresentMode::AutoNoVsync | PresentMode::Immediate | PresentMode::Mailbox => Some(Duration::from_secs(1) / UNSYNCED_FRAME_CAP), + PresentMode::AutoVsync | PresentMode::Fifo | PresentMode::FifoRelaxed => None, + } +} + +/// How long a frame waits before it starts, `since_last` after the previous frame started, so that +/// frames start at least `min` apart. `None`: no wait (no cap, the first frame, or `min` has passed). +pub fn frame_wait(min: Option, since_last: Option) -> Option { + min?.checked_sub(since_last?).filter(|wait| !wait.is_zero()) +} + +/// The present mode and frame latency `surface` asks for, for the start-up log: +/// "autovsync, frame latency 1", with "(override)" after a value a flag or variable set, and +/// "(preference)" after a present mode Low-Latency Drawing set. +#[cfg(feature = "wgpu")] +pub fn describe(surface: &eframe::egui_wgpu::SurfaceConfig, overrides: &Overrides, low_latency_drawing: bool) -> String { use eframe::wgpu::PresentMode; let mode = match surface.present_mode { PresentMode::AutoVsync => "autovsync", @@ -126,7 +153,8 @@ pub fn describe(surface: &eframe::egui_wgpu::SurfaceConfig, overrides: &Override }; let latency = surface.desired_maximum_frame_latency.map_or("default".to_string(), |n| n.to_string()); let tag = |set: bool| if set { " (override)" } else { "" }; - format!("{mode}{}, frame latency {latency}{}", tag(overrides.mode.is_some()), tag(overrides.latency.is_some())) + let mode_tag = if overrides.mode.is_none() && low_latency_drawing { " (preference)" } else { tag(overrides.mode.is_some()) }; + format!("{mode}{mode_tag}, frame latency {latency}{}", tag(overrides.latency.is_some())) } #[cfg(test)] @@ -224,20 +252,99 @@ mod tests { use eframe::wgpu::PresentMode; let app = SurfaceConfig::LOW_LATENCY; // No override: the surface the app asks for is unchanged. - assert_eq!(Overrides::default().apply(app), app); + assert_eq!(Overrides::default().apply(app, false), app); let latency = Overrides { mode: None, latency: Some(2) }; - let s = latency.apply(app); + let s = latency.apply(app, false); assert_eq!((s.present_mode, s.desired_maximum_frame_latency), (PresentMode::AutoVsync, Some(2))); - assert_eq!(describe(&s, &latency), "autovsync, frame latency 2 (override)"); + assert_eq!(describe(&s, &latency, false), "autovsync, frame latency 2 (override)"); let fifo = Overrides { mode: Some(Mode::Fifo), latency: None }; - let s = fifo.apply(app); + let s = fifo.apply(app, false); assert_eq!((s.present_mode, s.desired_maximum_frame_latency), (PresentMode::Fifo, app.desired_maximum_frame_latency)); // Never a mode the driver may lack: no vsync lets wgpu fall back by support. let novsync = Overrides { mode: Some(Mode::NoVsync), latency: Some(3) }; - let s = novsync.apply(app); + let s = novsync.apply(app, false); assert_eq!((s.present_mode, s.desired_maximum_frame_latency), (PresentMode::AutoNoVsync, Some(3))); - assert_eq!(describe(&s, &novsync), "novsync (override), frame latency 3 (override)"); + assert_eq!(describe(&s, &novsync, false), "novsync (override), frame latency 3 (override)"); let unset = SurfaceConfig { present_mode: PresentMode::Fifo, desired_maximum_frame_latency: None }; - assert_eq!(describe(&unset, &Overrides::default()), "fifo, frame latency default"); + assert_eq!(describe(&unset, &Overrides::default(), false), "fifo, frame latency default"); + } + + /// Low-Latency Drawing alone asks for no vsync, through wgpu's fallback by support and never an + /// explicit Immediate or Mailbox; off, the app's surface is exactly its own. + #[cfg(feature = "wgpu")] + #[test] + fn low_latency_drawing_alone_presents_without_vsync_and_off_keeps_the_app_surface() { + use eframe::egui_wgpu::SurfaceConfig; + use eframe::wgpu::PresentMode; + let app = SurfaceConfig::LOW_LATENCY; + let none = Overrides::default(); + assert_eq!(none.apply(app, false), app); + let s = none.apply(app, true); + assert_eq!(s.present_mode, PresentMode::AutoNoVsync); + assert_eq!(s.desired_maximum_frame_latency, app.desired_maximum_frame_latency); + let frames = app.desired_maximum_frame_latency.map_or("default".to_string(), |n| n.to_string()); + assert_eq!(describe(&s, &none, true), format!("novsync (preference), frame latency {frames}")); + // A latency override still applies with the preference's mode. + let latency = Overrides { mode: None, latency: Some(2) }; + let s = latency.apply(app, true); + assert_eq!((s.present_mode, s.desired_maximum_frame_latency), (PresentMode::AutoNoVsync, Some(2))); + assert_eq!(describe(&s, &latency, true), "novsync (preference), frame latency 2 (override)"); + } + + /// The flag and the variable each set the present mode over Low-Latency Drawing. + #[cfg(feature = "wgpu")] + #[test] + fn the_flag_and_the_variable_win_over_low_latency_drawing() { + use eframe::egui_wgpu::SurfaceConfig; + use eframe::wgpu::PresentMode; + let app = SurfaceConfig::LOW_LATENCY; + let flag = parse(&["--present-mode", "fifo"]).unwrap(); + let s = flag.apply(app, true); + assert_eq!(s.present_mode, PresentMode::Fifo); + assert!(describe(&s, &flag, true).starts_with("fifo (override),"), "{}", describe(&s, &flag, true)); + let var = Overrides::default().with_env(Some("autovsync".into()), None).unwrap(); + let s = var.apply(app, true); + assert_eq!(s.present_mode, PresentMode::AutoVsync); + assert!(describe(&s, &var, true).starts_with("autovsync (override),"), "{}", describe(&s, &var, true)); + // The flag wins over the variable, and both over the preference. + let both = parse(&["--present-mode=fifo"]).unwrap().with_env(Some("novsync".into()), None).unwrap(); + assert_eq!(both.apply(app, true).present_mode, PresentMode::Fifo); + } + + /// Frames start at most 240 times a second without vsync, from the preference or an override, + /// and the display paces them with vsync. + #[cfg(feature = "wgpu")] + #[test] + fn the_frame_cap_applies_only_without_vsync_at_240_frames_a_second() { + use eframe::egui_wgpu::SurfaceConfig; + use eframe::wgpu::PresentMode; + let app = SurfaceConfig::LOW_LATENCY; + let cap = Duration::from_secs(1) / 240; + assert_eq!(cap.as_nanos(), 4_166_666); + assert_eq!(min_frame_interval(&Overrides::default().apply(app, true)), Some(cap)); + assert_eq!(min_frame_interval(&Overrides { mode: Some(Mode::NoVsync), latency: None }.apply(app, false)), Some(cap)); + assert_eq!(min_frame_interval(&Overrides::default().apply(app, false)), None); + assert_eq!(min_frame_interval(&Overrides { mode: Some(Mode::Fifo), latency: None }.apply(app, true)), None); + for (mode, capped) in [ + (PresentMode::Immediate, true), + (PresentMode::Mailbox, true), + (PresentMode::AutoNoVsync, true), + (PresentMode::Fifo, false), + (PresentMode::FifoRelaxed, false), + (PresentMode::AutoVsync, false), + ] { + let s = SurfaceConfig { present_mode: mode, desired_maximum_frame_latency: Some(1) }; + assert_eq!(min_frame_interval(&s).is_some(), capped, "{mode:?}"); + } + } + + #[test] + fn a_frame_waits_out_the_rest_of_the_minimum_interval() { + let min = Some(Duration::from_millis(4)); + assert_eq!(frame_wait(min, Some(Duration::from_millis(1))), Some(Duration::from_millis(3))); + assert_eq!(frame_wait(min, Some(Duration::from_millis(4))), None); + assert_eq!(frame_wait(min, Some(Duration::from_millis(9))), None); + assert_eq!(frame_wait(min, None), None, "the first frame starts at once"); + assert_eq!(frame_wait(None, Some(Duration::ZERO)), None, "no cap with vsync"); } } diff --git a/assets/icons/dc-circle-points.svg b/assets/icons/dc-circle-points.svg new file mode 100644 index 0000000000..46da3a3401 --- /dev/null +++ b/assets/icons/dc-circle-points.svg @@ -0,0 +1 @@ + diff --git a/crates/brush/src/calli.rs b/crates/brush/src/calli.rs index 888294356c..69a8463c92 100644 --- a/crates/brush/src/calli.rs +++ b/crates/brush/src/calli.rs @@ -9,7 +9,6 @@ //! the stroke with what the pen recorded on it (`StrokeLayer::pressure`, `tilt`, `bearing` and //! `rotation`): the sweep is sampled densely and each sample takes the nib for the pen there. -use vectorcraft_color::Paint; use vectorcraft_doc::{Node, StrokeLayer}; use vectorcraft_geom::{BezPath, PathData, Point, SubPath, Vec2}; @@ -198,7 +197,70 @@ fn offset_track(t: &Track, d: f64, trim0: f64, trim1: f64) -> Option { Some(bp) } -pub(crate) fn bristle(b: &Bristle, bp: &BezPath, weight: f64, paint: &Paint, name: &str) -> Vec { +/// A strand that follows the recorded pen pose. Pressure and tilt change its spread; bearing and +/// barrel rotation turn that spread in the path's local frame. Original path corners are included +/// in the samples so a turn is not rounded away by the pose sampling interval. +fn posed_bristle_track( + t: &Track, + d: f64, + trim0: f64, + trim1: f64, + size: f64, + stroke: &StrokeLayer, + varies: bool, +) -> Option<(BezPath, Vec<(f64, f64)>)> { + let l = t.len(); + let (s0, s1) = (trim0.clamp(0.0, l), (l - trim1).clamp(0.0, l)); + if s1 - s0 < 1e-6 { + return None; + } + let steps = if varies { ((s1 - s0) / (size * 0.2).max(0.25)).ceil().clamp(1.0, MAX_STEPS) as usize } else { 1 }; + let mut positions: Vec = (0..=steps).map(|i| s0 + (s1 - s0) * i as f64 / steps as f64).collect(); + positions.extend(t.cum.iter().copied().filter(|&s| s > s0 && s < s1)); + positions.sort_by(f64::total_cmp); + positions.dedup_by(|a, b| (*a - *b).abs() < 1e-6); + let mut path = BezPath::new(); + // Distance along the posed strand -> fraction along the original, untrimmed path. + let mut source = Vec::with_capacity(positions.len()); + let mut previous: Option = None; + let mut distance = 0.0; + for (i, s) in positions.into_iter().enumerate() { + let pen = PenAt::of(stroke, s / l); + let pressure = pen.control(Variation::Pressure).unwrap_or(0.5); + let tilt = pen.control(Variation::Tilt).unwrap_or(0.5); + let bearing = pen.control(Variation::Bearing).unwrap_or(0.5); + let rotation = pen.control(Variation::Rotation).unwrap_or(0.5); + let spread = d * (0.5 + pressure) * (1.25 - 0.5 * tilt); + let angle = std::f64::consts::TAU * (bearing + rotation - 1.0); + let p = t.map(s + spread * angle.sin(), spread * angle.cos()); + if i == 0 { + path.move_to(p) + } else { + path.line_to(p) + } + if let Some(previous) = previous { + distance += previous.distance(p); + } + source.push((distance, s / l)); + previous = Some(p); + } + Some((path, source)) +} + +fn source_fraction(source: &[(f64, f64)], distance: f64) -> f64 { + let next = source.partition_point(|(d, _)| *d < distance); + if next == 0 { + return source.first().map_or(0.0, |(_, f)| *f); + } + if next >= source.len() { + return source.last().map_or(1.0, |(_, f)| *f); + } + let (d0, f0) = source[next - 1]; + let (d1, f1) = source[next]; + if d1 - d0 < 1e-9 { f1 } else { f0 + (f1 - f0) * ((distance - d0) / (d1 - d0)) } +} + +pub(crate) fn bristle(b: &Bristle, bp: &BezPath, weight: f64, stroke: &StrokeLayer, name: &str) -> Vec { let mut rng = Rng::new(seed_of(bp, name)); let size = b.size.max(0.1) * weight; let strands = (3.0 + b.density.clamp(1.0, 100.0) / 100.0 * 13.0).round() as usize; @@ -210,6 +272,13 @@ pub(crate) fn bristle(b: &Bristle, bp: &BezPath, weight: f64, paint: &Paint, nam let wobble = (100.0 - b.stiffness.clamp(1.0, 100.0)) / 100.0; let ragged = b.length.clamp(25.0, 300.0) / 100.0; let opacity = (b.opacity.clamp(1.0, 100.0) / 100.0) as f32; + let posed = stroke.pressure.is_some() || stroke.tilt.is_some() || stroke.bearing.is_some() || stroke.rotation.is_some(); + let varies = |points: &[(f64, f64)]| points.first().is_some_and(|(_, first)| points.iter().any(|(_, value)| (value - first).abs() > 1e-6)); + let pressure_varies = stroke.pressure.as_ref().is_some_and(|p| varies(&p.points)); + let pose_varies = pressure_varies + || stroke.tilt.as_ref().is_some_and(|p| varies(&p.points)) + || stroke.bearing.as_ref().is_some_and(|p| varies(&p.points)) + || stroke.rotation.as_ref().is_some_and(|p| varies(&p.points)); let mut out = vec![]; for t in tracks(bp, tolerance(size)) { let l = t.len(); @@ -220,14 +289,37 @@ pub(crate) fn bristle(b: &Bristle, bp: &BezPath, weight: f64, paint: &Paint, nam let edge = 1.0 - lane.abs(); let trim = |r: &mut Rng| r.unit() * ragged * size * (1.2 - edge) * 0.8; let (t0, t1) = (trim(&mut rng), trim(&mut rng)); - let Some(sp) = offset_track(&t, off, t0.min(l * 0.3), t1.min(l * 0.3)) else { continue }; + let (t0, t1) = (t0.min(l * 0.3), t1.min(l * 0.3)); + let sp = if posed { + posed_bristle_track(&t, off, t0, t1, size, stroke, pose_varies) + } else { + offset_track(&t, off, t0, t1).map(|path| (path, Vec::new())) + }; + let Some((sp, source)) = sp else { continue }; let w = thick * (0.6 + 0.4 * edge) * rng.range(0.8, 1.2); - let nib = Nib::new(0.0, 1.0, w); - let subs: Vec = tracks(&sp, tolerance(w)).iter().flat_map(|tt| sweep(tt, &|_| nib, None)).collect(); + let subs: Vec = tracks(&sp, tolerance(w)) + .iter() + .flat_map(|tt| { + if posed { + sweep( + tt, + &|f| { + let original_fraction = source_fraction(&source, f * tt.len()); + let pressure = PenAt::of(stroke, original_fraction).control(Variation::Pressure).unwrap_or(0.5); + Nib::new(0.0, 1.0, w * (0.5 + pressure)) + }, + pressure_varies.then_some((tt.len() / MAX_STEPS).max(0.25)), + ) + } else { + let nib = Nib::new(0.0, 1.0, w); + sweep(tt, &|_| nib, None) + } + }) + .collect(); if subs.is_empty() { continue; } - let mut n = filled(PathData::new(subs), paint); + let mut n = filled(PathData::new(subs), &stroke.paint); n.opacity = (opacity * rng.range(0.7, 1.0) as f32).clamp(0.0, 1.0); out.push(n); } diff --git a/crates/brush/src/colorize.rs b/crates/brush/src/colorize.rs index 00edeb3113..10dc66b587 100644 --- a/crates/brush/src/colorize.rs +++ b/crates/brush/src/colorize.rs @@ -97,6 +97,75 @@ pub fn colorize(n: &mut Node, mode: Colorization, stroke: &Paint) { walk(n, mode, key); } +/// Mixed into a stroke's seed for its hue jitter, so the amounts come from a sequence of their own +/// and a copy's size, spacing, scatter and rotation stay as they were without hue jitter. +const HUE_JITTER_SALT: u64 = 0x6875_655f_6a69_7474; + +/// Turn the hue of each of `copies` (a scatter brush's copies, in order along the path) by its +/// own amount between −`amount` and `amount` degrees, drawn from `seed` (the stroke's +/// [`crate::track::seed_of`]). +pub(crate) fn jitter_hues(copies: &mut [Node], amount: f64, seed: u64) { + let mut rng = crate::track::Rng::new(seed ^ HUE_JITTER_SALT); + for n in copies { + let turn = rng.range(-amount, amount) as f32; + turn_hues(n, turn); + } +} + +/// `c` with its hue turned by `degrees`, worked out on its own components so nothing else about it +/// changes: RGB in HSB of its values, CMYK over C, M and Y with K kept (as +/// [`Color::complement_keep_model`] does), Lab by turning a and b. `None` for a color without a hue: +/// white, black and grays, in their own model (Gray, CMYK with no C, M or Y ink). +fn turned(c: &Color, degrees: f32) -> Option { + if !degrees.is_finite() || vectorcraft_color::recolor::Neutral::of(c).is_some() { + return None; + } + let turn = |v: [f32; 3]| { + let [h, s, b] = vectorcraft_color::rgb_to_hsb(v); + (s > 0.0).then(|| vectorcraft_color::hsb_to_rgb([(h + degrees).rem_euclid(360.0), s, b])) + }; + match *c { + Color::Rgb { r, g, b } => turn([r, g, b]).map(|[r, g, b]| Color::rgb(r, g, b)), + Color::Cmyk { c, m, y, k } => turn([1.0 - c, 1.0 - m, 1.0 - y]).map(|[r, g, b]| Color::cmyk(1.0 - r, 1.0 - g, 1.0 - b, k)), + Color::Gray { .. } => None, + Color::Lab { l, a, b } => { + let (sin, cos) = f64::from(degrees).to_radians().sin_cos(); + let (a, b) = (f64::from(a), f64::from(b)); + Some(Color::lab(l, (a * cos - b * sin) as f32, (a * sin + b * cos) as f32)) + } + } +} + +fn turn_paint(p: &mut Paint, degrees: f32) { + if let Paint::Solid { color, .. } = p + && let Some(c) = turned(color, degrees) + { + *p = Paint::solid(c); + } +} + +/// Turn the hue of the solid fills and strokes under `n`, its type's characters included. A +/// mask's colors are its values, so they stay. +fn turn_hues(n: &mut Node, degrees: f32) { + for it in &mut n.appearance.items { + match it { + AppearanceItem::Fill(f) => turn_paint(&mut f.paint, degrees), + AppearanceItem::Stroke(s) => turn_paint(&mut s.paint, degrees), + } + } + if let NodeKind::Text(t) = &mut n.kind { + for r in &mut t.runs { + turn_paint(&mut r.style.fill, degrees); + turn_paint(&mut r.style.stroke, degrees); + } + } + if let Some(ch) = n.children_mut() { + for c in ch.iter_mut() { + turn_hues(Arc::make_mut(c), degrees); + } + } +} + /// Strip the brushes from every stroke under `n`, its masks' art included. fn strip_brushes(n: &mut Node) { for it in &mut n.appearance.items { diff --git a/crates/brush/src/defaults.rs b/crates/brush/src/defaults.rs index 8cf7467397..b99f36ecec 100644 --- a/crates/brush/src/defaults.rs +++ b/crates/brush/src/defaults.rs @@ -172,6 +172,7 @@ pub fn defaults() -> &'static [Brush] { rotation: (-180.0, 180.0), rotation_relative_to_path: false, colorization: Colorization::Tints, + hue_jitter: 0.0, modes: None, }), }, @@ -185,6 +186,7 @@ pub fn defaults() -> &'static [Brush] { rotation: (-35.0, 35.0), rotation_relative_to_path: true, colorization: Colorization::None, + hue_jitter: 0.0, modes: None, }), }, diff --git a/crates/brush/src/lib.rs b/crates/brush/src/lib.rs index 0b48f586cd..c5354d75cd 100644 --- a/crates/brush/src/lib.rs +++ b/crates/brush/src/lib.rs @@ -298,6 +298,12 @@ pub struct Scatter { /// Rotation relative to the path direction (else to the page). pub rotation_relative_to_path: bool, pub colorization: Colorization, + /// Hue jitter in degrees, 0 to 180: each copy turns the hue of the solid colors it draws, after + /// the colorization, by its own amount between −`hue_jitter` and `hue_jitter`. The stroke's + /// path and the brush name fix the amounts, so a stroke draws the same colors every time. + /// 0 (brushes saved before there was hue jitter) leaves the colors as they are. + #[serde(skip_serializing_if = "is_zero")] + pub hue_jitter: f64, /// How size, spacing, scatter and rotation vary between their two values: Fixed takes the /// first, Random any value between them, Pressure the first at the lightest pen pressure and /// the second at the heaviest, Tilt the first with the pen lying flat and the second upright, @@ -318,6 +324,7 @@ impl Default for Scatter { rotation: (0.0, 0.0), rotation_relative_to_path: false, colorization: Colorization::None, + hue_jitter: 0.0, modes: None, } } @@ -326,6 +333,8 @@ impl Default for Scatter { impl Scatter { /// The ranges of size (%), spacing (%), scatter (%) and rotation (°). pub const RANGES: [(f64, f64); 4] = [(1.0, 10000.0), (1.0, 10000.0), (-1000.0, 1000.0), (-180.0, 180.0)]; + /// The range of [`Scatter::hue_jitter`] (°). + pub const HUE_JITTER_RANGE: (f64, f64) = (0.0, 180.0); /// Size, spacing, scatter and rotation, each as its (first, second) values. pub fn values(&self) -> [(f64, f64); 4] { @@ -624,6 +633,10 @@ fn within_pair((a, b): (f64, f64), range: (f64, f64), fallback: f64) -> (f64, f6 (within(a, range, fallback), within(b, range, fallback)) } +fn is_zero(v: &f64) -> bool { + *v == 0.0 +} + fn valid_tile_frame(frame: Rect) -> bool { [frame.x0, frame.y0, frame.x1, frame.y1].into_iter().all(f64::is_finite) && frame.width().is_finite() @@ -714,6 +727,7 @@ impl Brush { s.spacing = within_pair(s.spacing, spacing, d.spacing.0); s.scatter = within_pair(s.scatter, scatter, 0.0); s.rotation = within_pair(s.rotation, rotation, 0.0); + s.hue_jitter = within(s.hue_jitter, Scatter::HUE_JITTER_RANGE, 0.0); s.colorization.sanitize(); } BrushKind::Art(a) => { @@ -753,6 +767,229 @@ impl Brush { } } +// ---------- stroke options ---------- + +/// The Scatter brush fields a stroke can set for itself ([`BrushKind::stroke_option_keys`]). +#[derive(Serialize, Deserialize)] +struct ScatterOptions { + size: (f64, f64), + spacing: (f64, f64), + scatter: (f64, f64), + rotation: (f64, f64), + modes: Option<[Variation; 4]>, + rotation_relative_to_path: bool, + colorization: Colorization, +} + +/// The Art brush fields a stroke can set for itself. +#[derive(Serialize, Deserialize)] +struct ArtOptions { + width: f64, + width_mode: Option, + width_max: Option, + flip_along: bool, + flip_across: bool, + overlap: bool, + colorization: Colorization, +} + +/// The Pattern brush fields a stroke can set for itself. +#[derive(Serialize, Deserialize)] +struct PatternOptions { + scale: f64, + spacing: f64, + fit: PatternFit, + flip_along: bool, + flip_across: bool, + colorization: Colorization, +} + +impl BrushKind { + /// The definition fields, by their `brush.options` names, that one stroke can set for itself + /// (the Brushes panel's Options of Selected Object, [`StrokeLayer::brush_options`]). A Bristle + /// brush has none. + pub fn stroke_option_keys(&self) -> &'static [&'static str] { + match self { + BrushKind::Calligraphic(_) => &["angle", "roundness", "size", "variation", "modes"], + BrushKind::Scatter(_) => &["size", "spacing", "scatter", "rotation", "modes", "rotation_relative_to_path", "colorization"], + BrushKind::Art(_) => &["width", "width_mode", "width_max", "flip_along", "flip_across", "overlap", "colorization"], + BrushKind::Pattern(_) => &["scale", "spacing", "fit", "flip_along", "flip_across", "colorization"], + BrushKind::Bristle(_) => &[], + } + } + + /// The values of [`Self::stroke_option_keys`], as a JSON object. Calligraphic modes left to the + /// values are a `null` `modes`, so a stroke that sets them so keeps that setting. + fn option_values(&self) -> serde_json::Value { + let v = match self { + BrushKind::Calligraphic(c) => serde_json::to_value(c).map(|mut v| { + if let Some(o) = v.as_object_mut() { + o.entry("modes").or_insert(serde_json::Value::Null); + } + v + }), + BrushKind::Scatter(s) => serde_json::to_value(ScatterOptions { + size: s.size, + spacing: s.spacing, + scatter: s.scatter, + rotation: s.rotation, + modes: s.modes, + rotation_relative_to_path: s.rotation_relative_to_path, + colorization: s.colorization, + }), + BrushKind::Art(a) => serde_json::to_value(ArtOptions { + width: a.width, + width_mode: a.width_mode, + width_max: a.width_max, + flip_along: a.flip_along, + flip_across: a.flip_across, + overlap: a.overlap, + colorization: a.colorization, + }), + BrushKind::Pattern(p) => serde_json::to_value(PatternOptions { + scale: p.scale, + spacing: p.spacing, + fit: p.fit, + flip_along: p.flip_along, + flip_across: p.flip_across, + colorization: p.colorization, + }), + BrushKind::Bristle(_) => Ok(serde_json::Value::Object(serde_json::Map::new())), + }; + v.unwrap_or_default() + } + + /// Set the values of [`Self::stroke_option_keys`] from `v` (as [`Self::option_values`] gives + /// them). An error when a value is of the wrong kind. + fn set_option_values(&mut self, v: serde_json::Value) -> Result<(), serde_json::Error> { + match self { + BrushKind::Calligraphic(c) => *c = serde_json::from_value(v)?, + BrushKind::Scatter(s) => { + let o: ScatterOptions = serde_json::from_value(v)?; + (s.size, s.spacing, s.scatter, s.rotation, s.modes) = (o.size, o.spacing, o.scatter, o.rotation, o.modes); + (s.rotation_relative_to_path, s.colorization) = (o.rotation_relative_to_path, o.colorization); + } + BrushKind::Art(a) => { + let o: ArtOptions = serde_json::from_value(v)?; + (a.width, a.width_mode, a.width_max, a.flip_along, a.flip_across) = (o.width, o.width_mode, o.width_max, o.flip_along, o.flip_across); + (a.overlap, a.colorization) = (o.overlap, o.colorization); + } + BrushKind::Pattern(p) => { + let o: PatternOptions = serde_json::from_value(v)?; + (p.scale, p.spacing, p.fit, p.flip_along, p.flip_across, p.colorization) = + (o.scale, o.spacing, o.fit, o.flip_along, o.flip_across, o.colorization); + } + BrushKind::Bristle(_) => {} + } + Ok(()) + } +} + +/// Stroke option value `new` with each `null` item of an array taken from the same place in +/// `current`, an array of the same length: a stroke option that changes some items of a range or a +/// list of modes and keeps the others ([`Brush::with_stroke_options`]). Any other `new` is given as +/// it is. +pub fn keep_items(new: &serde_json::Value, current: &serde_json::Value) -> serde_json::Value { + match (new, current) { + (serde_json::Value::Array(n), serde_json::Value::Array(c)) if n.len() == c.len() => { + serde_json::Value::Array(n.iter().zip(c).map(|(n, c)| if n.is_null() { c.clone() } else { n.clone() }).collect()) + } + _ => new.clone(), + } +} + +impl Brush { + /// The brush as a stroke whose own settings are `options` draws it: each field of + /// [`BrushKind::stroke_option_keys`] in `options` replaces the brush's value (a `colorization` + /// object changes only the fields it gives), and the values are kept within their ranges + /// ([`Brush::sanitize`]). A `null` item of an array keeps the brush's item there + /// ([`keep_items`]). Fields the type does not take are passed over. An error when a value is of + /// the wrong kind. + pub fn with_stroke_options(&self, options: &serde_json::Map) -> Result { + let keys = self.kind.stroke_option_keys(); + let mut values = self.kind.option_values(); + let Some(o) = values.as_object_mut() else { return Ok(self.clone()) }; + for (k, v) in options { + if !keys.contains(&k.as_str()) { + continue; + } + match (o.get_mut(k).and_then(serde_json::Value::as_object_mut), v.as_object()) { + (Some(inner), Some(fields)) if k == "colorization" => { + for (f, fv) in fields { + inner.insert(f.clone(), fv.clone()); + } + } + // Set below, once the values the modes may follow are in. + _ if k == "modes" => {} + _ => { + let current = o.get(k).cloned().unwrap_or_default(); + o.insert(k.clone(), keep_items(v, ¤t)); + } + } + } + // A Hue Shift without a key takes the art's main color, as `Brush::from_json` gives it. + if let Some(c) = o.get_mut("colorization").and_then(serde_json::Value::as_object_mut) + && c.get("method").and_then(serde_json::Value::as_str) == Some("hueShift") + && c.get("key").is_none_or(serde_json::Value::is_null) + { + let key = art_colors(self.art()).first().copied().unwrap_or(vectorcraft_color::Color::BLACK); + c.insert("key".into(), serde_json::to_value(key).map_err(|e| e.to_string())?); + } + let mut b = self.clone(); + b.kind.set_option_values(values.clone()).map_err(|e| e.to_string())?; + if let Some(m) = options.get("modes") + && keys.contains(&"modes") + { + // A null item keeps the mode the brush with the other settings has: modes it leaves to + // its values follow the stroke's values, as they are kept within their ranges. Modes + // equal to those are left as the brush has them, so they keep following the values. + b.sanitize(); + let current = match &b.kind { + BrushKind::Calligraphic(c) => serde_json::to_value(c.modes()).unwrap_or_default(), + BrushKind::Scatter(s) => serde_json::to_value(s.modes()).unwrap_or_default(), + _ => serde_json::Value::Null, + }; + let modes = keep_items(m, ¤t); + if modes != current { + if let Some(o) = values.as_object_mut() { + o.insert("modes".into(), modes); + } + b = self.clone(); + b.kind.set_option_values(values).map_err(|e| e.to_string())?; + } + } + b.sanitize(); + Ok(b) + } + + /// The stroke options of `options` that make the brush draw differently: each field of + /// [`BrushKind::stroke_option_keys`] whose value, after [`Self::with_stroke_options`], differs + /// from the brush's own, with that value (kept within its range). An error for a field the + /// type does not take and for a value of the wrong kind. + pub fn stroke_options_that_differ( + &self, + options: &serde_json::Map, + ) -> Result, String> { + let keys = self.kind.stroke_option_keys(); + if let Some(k) = options.keys().find(|k| !keys.contains(&k.as_str())) { + return Err(if keys.is_empty() { + format!("a {} brush has no options of its own on a stroke", self.kind.label().to_lowercase()) + } else { + format!("a {} brush's stroke options do not include `{k}` (they are {})", self.kind.label().to_lowercase(), keys.join(", ")) + }); + } + let edited = self.with_stroke_options(options)?.kind.option_values(); + let own = self.kind.option_values(); + Ok(keys + .iter() + .filter_map(|k| { + let v = edited.get(*k)?; + (own.get(*k) != Some(v)).then(|| ((*k).to_string(), v.clone())) + }) + .collect()) + } +} + // ---------- library ---------- /// The brush library of `doc`: its stored brushes, or the defaults when it has none. @@ -842,12 +1079,26 @@ fn tolerance(scale: f64) -> f64 { /// Filled art for one brushed stroke along `bp`, in `doc`. Pieces are in document space with id /// 0, and never draw a brushed stroke (so they never recurse): their own strokes carry no brush, /// and what they draw by name that would draw one is left out ([`leave_out_brushed`]). -/// Stroke-level opacity/blend are the caller's job (`StrokeLayer::opacity`). +/// Stroke-level opacity/blend are the caller's job (`StrokeLayer::opacity`). The stroke's own +/// brush settings ([`StrokeLayer::brush_options`]) replace the brush's values +/// ([`Brush::with_stroke_options`]); settings that do not read draw the brush as it is. pub fn stroke_pieces(doc: &Document, brush: &Brush, bp: &BezPath, stroke: &StrokeLayer) -> Vec { + let edited; + let brush = if stroke.brush_options.is_empty() { + brush + } else { + match brush.with_stroke_options(&stroke.brush_options) { + Ok(b) => { + edited = b; + &edited + } + Err(_) => brush, + } + }; let w = if stroke.width > 0.0 { stroke.width } else { 1.0 }; let mut out = match &brush.kind { BrushKind::Calligraphic(c) => calli::calligraphic(c, bp, w, stroke, &brush.name), - BrushKind::Bristle(b) => calli::bristle(b, bp, w, &stroke.paint, &brush.name), + BrushKind::Bristle(b) => calli::bristle(b, bp, w, stroke, &brush.name), BrushKind::Art(a) => warp::art(a, bp, w, stroke), BrushKind::Scatter(s) => warp::scatter(s, bp, w, stroke, &brush.name), BrushKind::Pattern(p) => warp::pattern(p, bp, w), @@ -856,6 +1107,12 @@ pub fn stroke_pieces(doc: &Document, brush: &Brush, bp: &BezPath, stroke: &Strok for n in &mut out { colorize(n, colorization, &stroke.paint); } + // One piece per copy, in the order the copies run along the path. + if let BrushKind::Scatter(s) = &brush.kind + && s.hue_jitter > 0.0 + { + colorize::jitter_hues(&mut out, s.hue_jitter, track::seed_of(bp, &brush.name)); + } leave_out_brushed(doc, &mut out, &mut Known::new()); out } @@ -1008,6 +1265,14 @@ 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)) } +/// Does `stroke` draw with a brush of `lib` (the document's [`library`])? [`stroke_pieces`] sizes +/// brush art from the brush and the stroke weight and does not read the stroke's width profile, so +/// the profile does not change what such a stroke draws. A stroke without a brush, or one that +/// names a brush `lib` lacks, draws a plain stroke, which follows the profile. +pub fn keeps_brush_size(lib: &[Brush], stroke: &StrokeLayer) -> bool { + stroke.brush.as_deref().is_some_and(|name| lib.iter().any(|b| b.name == name)) +} + /// 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 diff --git a/crates/brush/src/tests.rs b/crates/brush/src/tests.rs index de178c76ac..f4f2d1ae20 100644 --- a/crates/brush/src/tests.rs +++ b/crates/brush/src/tests.rs @@ -1,3 +1,4 @@ +use serde_json::json; use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, StrokeLayer}; use vectorcraft_geom::{Affine, BezPath, Point, Rect, Vec2, shapes}; @@ -826,6 +827,86 @@ fn bristle_makes_translucent_strands() { assert!(bb.height() <= 6.0 * 1.3 && bb.height() >= 3.0, "{bb:?}"); } +#[test] +fn bristle_pen_pressure_changes_its_footprint() { + let b = Brush { name: "b".into(), kind: BrushKind::Bristle(Bristle::default()) }; + let render = |pressure| { + let s = StrokeLayer { pressure: Some(vectorcraft_doc::PressureProfile { points: vec![(0.0, pressure), (1.0, pressure)] }), ..stroke(1.0) }; + stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 200.0, 0.0), &s) + }; + let light = render(0.0); + let heavy = render(1.0); + assert_eq!(light.len(), heavy.len()); + assert!(bounds(&heavy).height() > bounds(&light).height() * 1.8); +} + +#[test] +fn bristle_pen_pressure_is_sampled_along_the_stroke() { + let b = Brush { name: "b".into(), kind: BrushKind::Bristle(Bristle::default()) }; + let s = StrokeLayer { pressure: Some(vectorcraft_doc::PressureProfile { points: vec![(0.0, 0.0), (1.0, 1.0)] }), ..stroke(1.0) }; + let out = stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 200.0, 0.0), &s); + let mut points = Vec::new(); + for n in &out { + all_points(n, &mut points); + } + let early = points.iter().filter(|p| p.x > 20.0 && p.x < 60.0).map(|p| p.y.abs()).fold(0.0_f64, f64::max); + let late = points.iter().filter(|p| p.x > 140.0 && p.x < 180.0).map(|p| p.y.abs()).fold(0.0_f64, f64::max); + assert!(late > early * 1.4, "spread along stroke: {early} -> {late}"); +} + +#[test] +fn trimmed_bristle_strands_read_pressure_where_they_begin() { + let b = Brush { name: "b".into(), kind: BrushKind::Bristle(Bristle { size: 20.0, length: 300.0, ..Default::default() }) }; + let render = |points| { + let s = StrokeLayer { pressure: Some(vectorcraft_doc::PressureProfile { points }), ..stroke(1.0) }; + stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 80.0, 0.0), &s) + }; + let ramp = render(vec![(0.0, 0.0), (1.0, 1.0)]); + let neutral = render(vec![(0.0, 0.5), (1.0, 0.5)]); + assert_eq!(ramp.len(), neutral.len()); + let start = |n: &Node| { + let anchors = &n.path_data().unwrap().subpaths[0].anchors; + let first = anchors[0].p; + let opposite = anchors[anchors.len() - 16].p; + (first.x, (first.y - opposite.y).abs()) + }; + let mut checked = false; + for (ramp, neutral) in ramp.iter().zip(&neutral) { + let (x, width) = start(ramp); + if x < 12.0 { + continue; + } + let (_, neutral_width) = start(neutral); + let expected = 0.5 + x / 80.0; + assert!(width / neutral_width > expected - 0.08, "strand at {x}: {width} vs {neutral_width}, expected ratio {expected}"); + checked = true; + } + assert!(checked, "at least one strand begins past the pressure ramp's first eighth"); +} + +#[test] +fn bristle_pen_orientation_changes_its_footprint() { + let b = Brush { name: "b".into(), kind: BrushKind::Bristle(Bristle::default()) }; + let render = |tilt, bearing, rotation| { + let flat = |x| vec![(0.0, x), (1.0, x)]; + let s = StrokeLayer { + tilt: Some(vectorcraft_doc::PressureProfile { points: flat(tilt) }), + bearing: Some(vectorcraft_doc::AngleProfile { points: flat(bearing) }), + rotation: Some(vectorcraft_doc::AngleProfile { points: flat(rotation) }), + ..stroke(1.0) + }; + stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 200.0, 0.0), &s) + }; + let neutral = bounds(&render(0.5, 0.0, 0.0)).height(); + let flat = bounds(&render(1.0, 0.0, 0.0)).height(); + let upright = bounds(&render(0.0, 0.0, 0.0)).height(); + let bearing = bounds(&render(0.5, 90.0, 0.0)).height(); + let rotation = bounds(&render(0.5, 0.0, 90.0)).height(); + assert!(flat > neutral && neutral > upright, "tilt: {flat} > {neutral} > {upright}"); + assert!(bearing < neutral * 0.7, "bearing: {bearing} vs {neutral}"); + assert!(rotation < neutral * 0.7, "rotation: {rotation} vs {neutral}"); +} + #[test] fn tints_colorization_uses_stroke_colour() { let b = art_brush(rect_art(10.0, 4.0), ArtScale::Stretch); @@ -952,6 +1033,165 @@ fn stain_mixes_type_strokes_too() { assert_eq!(run_paints(&[art]), [(Paint::solid(blue), Paint::solid(blue))]); } +/// A scatter brush of rectangles filled `fill`, with `colorization` and `hue_jitter`. +fn jittered(fill: Color, colorization: Colorization, hue_jitter: f64) -> Brush { + let mut art = rect_art(10.0, 4.0); + art.appearance.set_fill(Paint::solid(fill)); + Brush { name: "s".into(), kind: BrushKind::Scatter(Scatter { art, colorization, hue_jitter, ..Default::default() }) } +} + +/// The fill color of each copy. +fn fill_colors(out: &[Node]) -> Vec { + out.iter().map(|n| n.appearance.fill_paint().color().unwrap()).collect() +} + +/// How far hue `h` is from `from`, in degrees, either way round. +fn hue_gap(h: f32, from: f32) -> f32 { + let d = (h - from).rem_euclid(360.0); + d.min(360.0 - d) +} + +#[test] +fn hue_jitter_turns_each_copy_the_same_every_time() { + let doc = Document::new(1.0, 1.0); + let path = line(0.0, 0.0, 200.0, 0.0); + let b = jittered(Color::rgb(1.0, 0.0, 0.0), Colorization::None, 90.0); + let out = stroke_pieces(&doc, &b, &path, &stroke(1.0)); + assert_eq!(out.len(), 20); + assert_eq!(stroke_pieces(&doc, &b, &path, &stroke(1.0)), out, "the same stroke draws the same colors"); + let colors = fill_colors(&out); + let hues: Vec = colors.iter().map(|c| c.to_hsb()[0]).collect(); + assert!(hues.iter().all(|h| hue_gap(*h, 0.0) <= 90.01), "{hues:?}"); + assert!(hues.iter().any(|h| hue_gap(*h, 0.0) > 10.0), "the copies turn: {hues:?}"); + let distinct: std::collections::HashSet = colors.iter().map(Color::to_hex).collect(); + assert!(distinct.len() > 10, "each copy turns by its own amount: {distinct:?}"); + // Saturation and brightness stay; the copies stay where they were, at their size and angle. + assert!(colors.iter().all(|c| near(f64::from(c.to_hsb()[1]), 1.0, 1e-3) && near(f64::from(c.to_hsb()[2]), 1.0, 1e-3)), "{colors:?}"); + let plain = stroke_pieces(&doc, &jittered(Color::rgb(1.0, 0.0, 0.0), Colorization::None, 0.0), &path, &stroke(1.0)); + let boxes = |o: &[Node]| o.iter().map(|n| n.geometric_bounds().unwrap()).collect::>(); + assert_eq!(boxes(&out), boxes(&plain)); + // Another path draws other amounts. + let other = fill_colors(&stroke_pieces(&doc, &b, &line(0.0, 10.0, 200.0, 10.0), &stroke(1.0))); + assert_ne!(other, colors); +} + +#[test] +fn hue_jitter_of_zero_changes_nothing() { + let red = Color::rgb(1.0, 0.0, 0.0); + let out = stroke_pieces(&Document::new(1.0, 1.0), &jittered(red, Colorization::None, 0.0), &line(0.0, 0.0, 200.0, 0.0), &stroke(1.0)); + assert!(!out.is_empty() && fill_colors(&out).iter().all(|c| *c == red)); + // A brush without hue jitter is saved as before, and one saved before reads as 0. + let v = serde_json::to_value(jittered(red, Colorization::None, 0.0)).unwrap(); + assert!(v.get("hue_jitter").is_none(), "{v}"); + let mut old = serde_json::to_value(jittered(red, Colorization::None, 45.0)).unwrap(); + assert_eq!(old.as_object_mut().unwrap().remove("hue_jitter"), Some(serde_json::json!(45.0))); + let BrushKind::Scatter(s) = Brush::from_json(old).unwrap().kind else { panic!("not a scatter brush") }; + assert_eq!(s.hue_jitter, 0.0, "a brush saved without the key reads as 0"); + let mut with = v.clone(); + with["hue_jitter"] = serde_json::json!(45.0); + let BrushKind::Scatter(s) = Brush::from_json(with).unwrap().kind else { panic!("not a scatter brush") }; + assert_eq!(s.hue_jitter, 45.0); + // Values outside 0..180 are clamped. + for (given, kept) in [(500.0, 180.0), (-20.0, 0.0)] { + let mut v = v.clone(); + v["hue_jitter"] = serde_json::json!(given); + let BrushKind::Scatter(s) = Brush::from_json(v).unwrap().kind else { panic!("not a scatter brush") }; + assert_eq!(s.hue_jitter, kept, "{given}"); + } +} + +#[test] +fn hue_jitter_turns_after_the_colorization() { + let doc = Document::new(1.0, 1.0); + let path = line(0.0, 0.0, 200.0, 0.0); + // Tints: black art takes the blue stroke color, which then turns. + let blue = StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 1.0); + let hues: Vec = + fill_colors(&stroke_pieces(&doc, &jittered(Color::BLACK, Colorization::Tints, 30.0), &path, &blue)).iter().map(|c| c.to_hsb()[0]).collect(); + assert!(!hues.is_empty() && hues.iter().all(|h| hue_gap(*h, 240.0) <= 30.01), "{hues:?}"); + assert!(hues.iter().any(|h| hue_gap(*h, 240.0) > 3.0), "{hues:?}"); + // A gray stroke color has no hue: its tints stay as they are. + let gray = StrokeLayer::new(Paint::solid(Color::rgb(0.5, 0.5, 0.5)), 1.0); + let turned = stroke_pieces(&doc, &jittered(Color::BLACK, Colorization::Tints, 180.0), &path, &gray); + let still = stroke_pieces(&doc, &jittered(Color::BLACK, Colorization::Tints, 0.0), &path, &gray); + assert_eq!(fill_colors(&turned), fill_colors(&still)); + // Nor does black ink alone, nor a gray, as a process stroke color. + for key in [Color::cmyk(0.0, 0.0, 0.0, 1.0), Color::cmyk(0.0, 0.0, 0.0, 0.5), Color::gray(0.4)] { + let key = StrokeLayer::new(Paint::solid(key), 1.0); + let turned = stroke_pieces(&doc, &jittered(Color::BLACK, Colorization::Tints, 180.0), &path, &key); + let still = stroke_pieces(&doc, &jittered(Color::BLACK, Colorization::Tints, 0.0), &path, &key); + assert_eq!(fill_colors(&turned), fill_colors(&still), "{key:?}"); + } + // A turned process color stays a process color, turned over its C, M and Y with its K kept. + let cmyk = fill_colors(&stroke_pieces(&doc, &jittered(Color::cmyk(0.0, 1.0, 1.0, 0.25), Colorization::None, 60.0), &path, &stroke(1.0))); + assert!(cmyk.iter().any(|c| *c != Color::cmyk(0.0, 1.0, 1.0, 0.25)), "{cmyk:?}"); + for c in &cmyk { + let Color::Cmyk { c, m, y, k } = *c else { panic!("not CMYK: {c:?}") }; + assert_eq!(k, 0.25); + // Full ink in one channel and none in another, as the color before it. + assert!(near(f64::from(c.max(m).max(y)), 1.0, 1e-4) && near(f64::from(c.min(m).min(y)), 0.0, 1e-4), "{c} {m} {y}"); + } + // An RGB color keeps its saturation and brightness in its own values. + let rgb = fill_colors(&stroke_pieces(&doc, &jittered(Color::rgb(0.8, 0.2, 0.4), Colorization::None, 90.0), &path, &stroke(1.0))); + for c in &rgb { + let Color::Rgb { r, g, b } = *c else { panic!("not RGB: {c:?}") }; + assert!(near(f64::from(r.max(g).max(b)), 0.8, 1e-4) && near(f64::from(r.min(g).min(b)), 0.2, 1e-4), "{c:?}"); + } + // A Lab color keeps its lightness and chroma. + let lab = fill_colors(&stroke_pieces(&doc, &jittered(Color::lab(50.0, 40.0, 30.0), Colorization::None, 90.0), &path, &stroke(1.0))); + assert!(lab.iter().any(|c| *c != Color::lab(50.0, 40.0, 30.0)), "{lab:?}"); + for c in &lab { + let Color::Lab { l, a, b } = *c else { panic!("not Lab: {c:?}") }; + assert!(l == 50.0 && near(f64::from(a.hypot(b)), 50.0, 1e-3), "{c:?}"); + } +} + +/// Hue jitter turns type's characters, the colors Tints and Shades and Hue Shift give, and a color +/// linked to a swatch (which loses the link); a pattern paint stays. +#[test] +fn hue_jitter_turns_type_every_colorization_and_linked_colors() { + let doc = Document::new(1.0, 1.0); + let path = line(0.0, 0.0, 200.0, 0.0); + let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0)); + let typed = |hue_jitter| Brush { + name: "s".into(), + kind: BrushKind::Scatter(Scatter { art: type_art(red.clone(), red.clone()), hue_jitter, ..Default::default() }), + }; + let still = run_paints(&stroke_pieces(&doc, &typed(0.0), &path, &stroke(1.0))); + let turned = run_paints(&stroke_pieces(&doc, &typed(90.0), &path, &stroke(1.0))); + assert!(!still.is_empty() && still.iter().all(|p| *p == (red.clone(), red.clone())), "{still:?}"); + assert_eq!(turned.len(), still.len()); + assert!(turned.iter().any(|p| *p != (red.clone(), red.clone())), "the characters turn: {turned:?}"); + assert!(turned.iter().all(|(f, s)| f == s), "a copy's character fill and stroke turn by the same amount: {turned:?}"); + // Tints and Shades and Hue Shift: the colors they give turn. + let blue = StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 1.0); + for colorization in [Colorization::TintsAndShades, Colorization::HueShift { key: Color::rgb(1.0, 0.0, 0.0) }] { + let art = Color::rgb(1.0, 0.0, 0.0); + let still = fill_colors(&stroke_pieces(&doc, &jittered(art, colorization, 0.0), &path, &blue)); + let turned = fill_colors(&stroke_pieces(&doc, &jittered(art, colorization, 45.0), &path, &blue)); + assert_eq!(turned.len(), still.len()); + assert_ne!(turned, still, "{colorization:?}"); + for (t, s) in turned.iter().zip(&still) { + assert!(hue_gap(t.to_hsb()[0], s.to_hsb()[0]) <= 45.01, "{colorization:?}: {t:?} from {s:?}"); + } + } + // A color linked to a swatch turns and loses the link; a pattern paint stays. + let linked = Paint::Solid { color: Color::rgb(1.0, 0.0, 0.0), swatch: Some("Red".into()), tint: 1.0 }; + let pattern = Paint::Pattern { pattern: "Dots".into(), xf: Affine::IDENTITY }; + let mut art = rect_art(10.0, 4.0); + art.appearance.set_fill(linked.clone()); + art.appearance.set_stroke(pattern.clone()); + let b = |hue_jitter| Brush { name: "s".into(), kind: BrushKind::Scatter(Scatter { art: art.clone(), hue_jitter, ..Default::default() }) }; + let still = stroke_pieces(&doc, &b(0.0), &path, &stroke(1.0)); + let turned = stroke_pieces(&doc, &b(90.0), &path, &stroke(1.0)); + assert!(!still.is_empty() && still.iter().all(|n| n.appearance.fill_paint() == linked)); + assert_eq!(turned.len(), still.len()); + for n in &turned { + assert!(matches!(n.appearance.fill_paint(), Paint::Solid { swatch: None, .. }), "{:?}", n.appearance.fill_paint()); + assert_eq!(n.appearance.stroke().map(|s| &s.paint), Some(&pattern)); + } +} + /// An instance whose fill has an opacity of 0 does not stain its symbol's art, so the art keeps its /// swatch links. #[test] @@ -2037,3 +2277,100 @@ fn a_straight_run_keeps_the_same_node_kinds_as_a_bend() { } } } + +/// `options` as a stroke's own brush settings. +fn with_options(options: serde_json::Value) -> StrokeLayer { + StrokeLayer { brush_options: options.as_object().cloned().unwrap_or_default(), ..stroke(1.0) } +} + +#[test] +fn a_strokes_own_options_change_its_art_and_leave_the_brush() { + let doc = Document::new(1.0, 1.0); + let brush = art_brush(rect_art(10.0, 4.0), ArtScale::Stretch); + let path = line(20.0, 50.0, 220.0, 50.0); + let half = stroke_pieces(&doc, &brush, &path, &with_options(json!({"width": 50.0}))); + assert!(near(bounds(&half).height(), 2.0, 1e-6), "width 50% halves the art across the stroke: {:?}", bounds(&half)); + assert!(near(bounds(&stroke_pieces(&doc, &brush, &path, &stroke(1.0))).height(), 4.0, 1e-6), "a stroke without options draws the brush"); + let BrushKind::Art(a) = &brush.kind else { panic!("art brush") }; + assert_eq!(a.width, 100.0, "the brush keeps its width"); + // A calligraphic stroke's own size and angle. + let nib = stroke_pieces(&doc, &calli(0.0, 20.0, 10.0), &line(0.0, 0.0, 100.0, 0.0), &with_options(json!({"angle": 90.0}))); + assert!(near(bounds(&nib).height(), 10.0, 0.05), "{:?}", bounds(&nib)); + // A pattern stroke's own scale doubles the tiles across it. + let pattern = pattern_brush(PatternFit::Stretch, false); + let plain = bounds(&stroke_pieces(&doc, &pattern, &path, &stroke(1.0))).height(); + let doubled = bounds(&stroke_pieces(&doc, &pattern, &path, &with_options(json!({"scale": 200.0})))).height(); + assert!(near(doubled, plain * 2.0, 1e-6), "{plain} → {doubled}"); +} + +#[test] +fn stroke_options_are_checked_and_kept_within_their_ranges() { + let brush = art_brush(rect_art(10.0, 4.0), ArtScale::Stretch); + let map = |v: serde_json::Value| v.as_object().cloned().unwrap_or_default(); + // Out of range: clamped; equal to the brush's own value: left out. + let got = brush.stroke_options_that_differ(&map(json!({"width": 5000.0, "flip_along": false}))).unwrap(); + assert_eq!(serde_json::Value::Object(got), json!({"width": 1000.0})); + // A field the type does not take, and a value of the wrong kind, are errors. + assert!(brush.stroke_options_that_differ(&map(json!({"angle": 10.0}))).unwrap_err().contains("angle")); + assert!(brush.stroke_options_that_differ(&map(json!({"width": "wide"}))).is_err()); + let bristle = Brush { name: "b".into(), kind: BrushKind::Bristle(Bristle::default()) }; + assert!(bristle.stroke_options_that_differ(&map(json!({"size": 2.0}))).is_err()); + assert!(bristle.stroke_options_that_differ(&map(json!({}))).unwrap().is_empty()); + // A colorization object changes only the fields it gives: Hue Shift keeps the key it has. + let key = Color::rgb(0.0, 0.0, 1.0); + let hue = Brush { + name: "h".into(), + kind: BrushKind::Art(ArtBrush { art: rect_art(10.0, 4.0), colorization: Colorization::HueShift { key }, ..Default::default() }), + }; + let tints = hue.with_stroke_options(&map(json!({"colorization": {"method": "tints"}}))).unwrap(); + assert_eq!(tints.kind.colorization(), Colorization::Tints); + let back = hue.stroke_options_that_differ(&map(json!({"colorization": {"method": "hueShift"}}))).unwrap(); + assert!(back.is_empty(), "the brush's own colorization: {back:?}"); + // Hue Shift without a key takes the art's main color, as brush.options gives it. + let keyless = tints.stroke_options_that_differ(&map(json!({"colorization": {"method": "hueShift"}}))).unwrap(); + let want = art_colors(tints.art()).first().copied().unwrap_or(Color::BLACK); + assert_eq!(keyless["colorization"]["method"], json!("hueShift")); + assert_eq!(keyless["colorization"]["key"], serde_json::to_value(want).unwrap()); + // Settings that do not read draw the brush as it is. + let doc = Document::new(1.0, 1.0); + let path = line(20.0, 50.0, 220.0, 50.0); + let odd = stroke_pieces(&doc, &brush, &path, &with_options(json!({"width": [1, 2]}))); + assert!(near(bounds(&odd).height(), 4.0, 1e-6)); +} + +#[test] +fn null_stroke_option_items_keep_the_items_the_stroke_has() { + let map = |v: serde_json::Value| v.as_object().cloned().unwrap_or_default(); + // A scatter brush at fixed sizes, with no modes of its own: they follow its values. + let b = Brush { name: "s".into(), kind: BrushKind::Scatter(Scatter { size: (100.0, 100.0), ..Default::default() }) }; + let BrushKind::Scatter(s) = b.with_stroke_options(&map(json!({"size": [null, 150]}))).unwrap().kind else { panic!("scatter") }; + assert_eq!(s.size, (100.0, 150.0), "the smallest size stays the brush's"); + // A stroke whose sizes vary keeps that random size mode when it sets only the spacing mode. + let e = b.with_stroke_options(&map(json!({"size": [50, 80], "modes": [null, "pressure", null, null]}))).unwrap(); + let BrushKind::Scatter(s) = e.kind else { panic!("scatter") }; + assert_eq!(s.modes(), [Variation::Random, Variation::Pressure, Variation::Fixed, Variation::Fixed]); + // The kept modes follow the values as they are kept within their ranges. + let c = calli(0.0, 100.0, 3.0).with_stroke_options(&map(json!({"variation": [-2, 0, 0], "modes": [null, "pressure", null]}))).unwrap(); + let BrushKind::Calligraphic(c) = c.kind else { panic!("calligraphic") }; + assert_eq!(c.modes(), [Variation::Fixed, Variation::Pressure, Variation::Fixed]); + // Modes that change nothing are no setting of the stroke's: they keep following its values. + let same = b.stroke_options_that_differ(&map(json!({"modes": [null, null, null, null]}))).unwrap(); + assert!(same.is_empty(), "{same:?}"); +} + +#[test] +fn a_null_calligraphic_modes_setting_stays_when_another_value_changes() { + let map = |v: serde_json::Value| v.as_object().cloned().unwrap_or_default(); + // A brush whose modes are its own, and a stroke whose modes follow its values instead. + let mut b = calli(0.0, 100.0, 3.0); + if let BrushKind::Calligraphic(c) = &mut b.kind { + c.modes = Some([Variation::Pressure; 3]); + } + let got = b.stroke_options_that_differ(&map(json!({"modes": null, "angle": 30.0}))).unwrap(); + assert_eq!(serde_json::Value::Object(got), json!({"modes": null, "angle": 30.0})); + let BrushKind::Calligraphic(c) = b.with_stroke_options(&map(json!({"modes": null, "angle": 30.0}))).unwrap().kind else { panic!("calligraphic") }; + assert_eq!(c.modes(), [Variation::Fixed; 3], "the stroke draws with the modes its values give"); + // A brush whose modes follow its values: a null `modes` is the brush's own and is left out. + let plain = calli(0.0, 100.0, 3.0).stroke_options_that_differ(&map(json!({"modes": null}))).unwrap(); + assert!(plain.is_empty(), "{plain:?}"); +} diff --git a/crates/cad/src/lib.rs b/crates/cad/src/lib.rs index eafb4616f1..8aefe61a0d 100644 --- a/crates/cad/src/lib.rs +++ b/crates/cad/src/lib.rs @@ -7,6 +7,8 @@ //! hatches, type text entities or glyph outlines, and placed images image entities linked to PNG //! or JPEG files the caller writes next to the drawing. Coordinates are y-up, in drawing units: `scale` units per //! `unit` of the art, with the origin at the bottom-left corner of [`DxfOptions::region`]. +//! [`export_drawings`] writes one such drawing for each of several regions, applying the live +//! effects once for all of them. //! //! What DXF can't hold (blending modes, opacity masks, raster effects, gradients, patterns, //! clipping) is approximated or left out, and each such loss comes back as a warning. @@ -436,18 +438,43 @@ pub const SCALE_RANGE: std::ops::RangeInclusive = 1e-6..=1e6; /// Write `doc` as a DXF drawing with `opts`. Live geometry effects are applied first; template /// layers, guides and hidden objects are left out. pub fn export(doc: &Document, opts: &DxfOptions) -> Result { + Ok(export_drawings(doc, opts, &[(opts.region, opts.crop)])?.pop().unwrap_or_default()) +} + +/// Write `doc` as one DXF drawing for each `(region, crop)` of `drawings`, in order, each as +/// [`export`] writes it with `opts` and that region and crop. Live geometry effects are applied +/// once for all the drawings. +pub fn export_drawings(doc: &Document, opts: &DxfOptions, drawings: &[(Rect, bool)]) -> Result, String> { + export_drawings_with(doc, opts, drawings, bake_for_drawings) +} + +/// `doc` with its live geometry effects applied and its symbols' art placed, or `None` when +/// nothing changes. +fn bake_for_drawings(doc: &Document) -> Option { + // Symbols' art is placed without clipping, as the scene places it. + let layers = vectorcraft_effects::WrittenLayers { hidden: true, non_printing: true, hidden_objects: false }; + vectorcraft_effects::bake_document_placing_symbols(doc, false, layers) +} + +/// [`export_drawings`] with `bake` applying the live effects. +fn export_drawings_with( + doc: &Document, + opts: &DxfOptions, + drawings: &[(Rect, bool)], + bake: impl Fn(&Document) -> Option, +) -> Result, String> { if !(opts.scale.is_finite() && SCALE_RANGE.contains(&opts.scale)) { return Err(format!("scale must be a number from {} to {}, not {}", SCALE_RANGE.start(), SCALE_RANGE.end(), opts.scale)); } - let r = opts.region; - if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) { + if drawings.iter().any(|(r, _)| ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite())) { return Err("the export region is not finite".into()); } - // Symbols' art is placed without clipping, as the scene places it. - let layers = vectorcraft_effects::WrittenLayers { hidden: true, non_printing: true, hidden_objects: false }; - let baked = vectorcraft_effects::bake_document_placing_symbols(doc, false, layers); + if drawings.is_empty() { + return Ok(vec![]); + } + let baked = bake(doc); let doc = baked.as_ref().unwrap_or(doc); - Ok(scene::Scene::new(doc, opts).run()) + Ok(drawings.iter().map(|&(region, crop)| scene::Scene::new(doc, &DxfOptions { region, crop, ..opts.clone() }).run()).collect()) } #[cfg(test)] diff --git a/crates/cad/src/tests.rs b/crates/cad/src/tests.rs index dda09a0696..797223b688 100644 --- a/crates/cad/src/tests.rs +++ b/crates/cad/src/tests.rs @@ -1493,3 +1493,201 @@ fn export_bytes_match_shared_writer_goldens() { assert_eq!(got, expected, "DXF bytes changed versus {}", path.display()); } } + +/// One drawing written by applying the live effects for it alone and walking the result, as each +/// drawing of a multi-drawing export was written before [`export_drawings`]. +fn export_baking_alone(doc: &Document, opts: &DxfOptions) -> DxfOutput { + let baked = crate::bake_for_drawings(doc); + crate::scene::Scene::new(baked.as_ref().unwrap_or(doc), opts).run() +} + +/// A written drawing's bytes, linked images (name and bytes), warnings and setting notes. +type Written = (Vec, Vec<(String, Vec)>, Vec, Vec); + +/// Every field of a written drawing, for comparing two. +fn written(out: &DxfOutput) -> Written { + let images = out.images.iter().map(|i| (i.name.clone(), i.bytes.clone())).collect(); + (out.bytes.clone(), images, out.warnings.clone(), out.setting_notes.clone()) +} + +/// A Transform effect that moves its object `x` pt right. +fn moved_by(mut n: Node, x: f64) -> Node { + n.appearance.effects.push(vectorcraft_doc::Effect { id: "distort.transform".into(), params: serde_json::json!({"moveH": x}), visible: true }); + n +} + +/// A line moved by a Transform effect, an instance of a symbol whose art carries the same effect +/// stained by its fill, a semi-transparent line in a blending mode, and a placed PNG image. +fn drawings_doc() -> Document { + let png = craft_image_codecs::encode( + &craft_image_codecs::Image::from_raw( + 2, + 2, + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + [0u8, 128, 255, 255].repeat(4), + ) + .unwrap(), + craft_image_codecs::Format::Png, + &craft_image_codecs::EncodeOptions::default(), + ) + .unwrap(); + let mut d = doc_with(|d| { + let line = path(d, shapes::line((10.0, 10.0).into(), (20.0, 10.0).into()), Paint::None, Paint::solid(Color::BLACK), 1.0); + let mut instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Moved".into(), xf: Affine::IDENTITY }); + instance.appearance = Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), Paint::None, 0.0).into(); + let mut faint = path(d, shapes::line((10.0, 90.0).into(), (190.0, 90.0).into()), Paint::None, Paint::solid(Color::BLACK), 1.0); + faint.opacity = 0.5; + faint.blend = vectorcraft_color::BlendMode::Multiply; + let im = ImageObject { + key: "raster-1".into(), + width: 2, + height: 2, + xf: Affine::translate((150.0, 20.0)) * Affine::scale(10.0), + link: None, + placement: Default::default(), + pixels: None, + }; + vec![moved_by(line, 100.0), instance, faint, Node::new(d.alloc_id(), NodeKind::Image(Box::new(im)))] + }); + let art = path(&mut d, shapes::rectangle(Rect::new(10.0, 40.0, 30.0, 60.0)), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Moved".into(), art: Arc::new(moved_by(art, 20.0)) }); + d.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None }); + d +} + +#[test] +fn drawings_apply_the_live_effects_once_and_match_drawings_written_alone() { + let d = drawings_doc(); + assert!(crate::bake_for_drawings(&d).is_some(), "the document has live effects to apply"); + // The left and right halves cropped, the whole page uncropped, and a region off the page. + let drawings = [ + (Rect::new(0.0, 0.0, 100.0, 100.0), true), + (Rect::new(100.0, 0.0, 200.0, 100.0), true), + (Rect::new(0.0, 0.0, 200.0, 100.0), false), + (Rect::new(300.0, 0.0, 400.0, 100.0), true), + ]; + // With every option, and with images and hatches left out (which adds setting notes). + let all_in = opts(&d); + for o in [all_in.clone(), DxfOptions { include_images: false, include_hatches: false, ..all_in }] { + let bakes = std::cell::Cell::new(0); + let outs = crate::export_drawings_with(&d, &o, &drawings, |doc| { + bakes.set(bakes.get() + 1); + crate::bake_for_drawings(doc) + }) + .unwrap(); + assert_eq!(bakes.get(), 1, "the live effects are applied once for every drawing"); + assert_eq!(outs.len(), drawings.len()); + for ((region, crop), out) in drawings.iter().zip(&outs) { + let alone = export_baking_alone(&d, &DxfOptions { region: *region, crop: *crop, ..o.clone() }); + assert_eq!(written(out), written(&alone), "the drawing over {region:?}, crop {crop}"); + let one = export(&d, &DxfOptions { region: *region, crop: *crop, ..o.clone() }).unwrap(); + assert_eq!(written(&one), written(&alone), "export over {region:?}, crop {crop}"); + } + let public: Vec<_> = export_drawings(&d, &o, &drawings).unwrap().iter().map(written).collect(); + assert_eq!(public, outs.iter().map(written).collect::>()); + // The halves hold different art, the left half a line with losses, and the region off the + // page nothing. + assert!(!entities(&outs[0]).is_empty() && !entities(&outs[1]).is_empty() && !outs[0].warnings.is_empty()); + assert_ne!(outs[0].bytes, outs[1].bytes); + assert!(entities(&outs[3]).is_empty() && outs[3].images.is_empty()); + if o.include_images { + assert_eq!(outs[2].images.len(), 1); + } else { + assert!(!outs[2].setting_notes.is_empty() && outs[2].images.is_empty()); + } + } +} + +#[test] +fn drawings_are_checked_before_the_live_effects_are_applied() { + let d = drawings_doc(); + let o = opts(&d); + let bakes = std::cell::Cell::new(0); + let count = |doc: &Document| { + bakes.set(bakes.get() + 1); + crate::bake_for_drawings(doc) + }; + let page = (d.artboards[0].rect, false); + let off = (Rect::new(0.0, 0.0, f64::NAN, 100.0), false); + assert_eq!(crate::export_drawings_with(&d, &o, &[page, off], count).unwrap_err(), "the export region is not finite"); + let e = crate::export_drawings_with(&d, &DxfOptions { scale: 0.0, ..o.clone() }, &[page], count).unwrap_err(); + assert!(e.starts_with("scale must be a number"), "{e}"); + assert!(crate::export_drawings_with(&d, &o, &[], count).unwrap().is_empty()); + assert_eq!(bakes.get(), 0, "nothing is applied for drawings that are refused or for none"); +} + +/// The thread's time on the CPU in nanoseconds where Linux reports it, otherwise `None`. +fn thread_cpu_ns() -> Option { + std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok() +} + +/// Time a Use Artboards export of eight artboards whose art has live effects, written drawing by +/// drawing with the effects applied for each (as before [`export_drawings`]) and with +/// [`export_drawings`], alternating, seven times each, and check that both write the same +/// drawings. Prints the median of each in milliseconds of the thread's CPU time (on Linux) and of +/// wall-clock time. +/// Run with `cargo test --release -p vectorcraft-cad --lib dxf_artboards_bake_perf -- --ignored --nocapture`. +#[test] +#[ignore = "manual timing probe; wall-clock performance depends on machine load"] +fn dxf_artboards_bake_perf() { + const BOARDS: usize = 8; + let mut d = Document::new(200.0 * BOARDS as f64, 200.0); + let layer = d.layers[0].id; + let effect = |id: &str, params: serde_json::Value| vectorcraft_doc::Effect { id: id.into(), params, visible: true }; + let mut art = vec![]; + for i in 0..50 { + let (x, y) = (f64::from(i % 10) * 5.0, f64::from(i / 10) * 5.0); + art.push(Arc::new(path(&mut d, shapes::rectangle(Rect::new(x, y, x + 4.0, y + 4.0)), Paint::None, Paint::solid(Color::BLACK), 0.5))); + } + let mut cell = Node::group(d.alloc_id(), art); + cell.appearance.effects.push(effect("distort.zigZag", serde_json::json!({"size": 1.0, "relative": false, "ridges": 4, "points": "smooth"}))); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Cell".into(), art: Arc::new(cell) }); + for b in 0..BOARDS { + let x0 = 200.0 * b as f64; + for i in 0..250 { + let (x, y) = (x0 + f64::from(i % 25) * 8.0, f64::from(i / 25) * 8.0); + let mut n = path(&mut d, shapes::ellipse(Rect::new(x, y, x + 6.0, y + 6.0)), Paint::None, Paint::solid(Color::BLACK), 0.5); + let params = serde_json::json!({"size": 1.0, "relative": false, "detail": 10.0, "points": "smooth", "seed": i}); + n.appearance.effects.push(effect("distort.roughen", params)); + d.insert(Some(layer), usize::MAX, n).unwrap(); + } + for i in 0..20 { + let xf = Affine::translate((x0 + f64::from(i % 5) * 40.0, 100.0 + f64::from(i / 5) * 25.0)); + let instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Cell".into(), xf }); + d.insert(Some(layer), usize::MAX, instance).unwrap(); + } + } + let o = DxfOptions { unit: Unit::Points, ..DxfOptions::default() }; + let drawings: Vec<(Rect, bool)> = (0..BOARDS).map(|b| (Rect::new(200.0 * b as f64, 0.0, 200.0 * (b + 1) as f64, 200.0), true)).collect(); + let before = || drawings.iter().map(|&(region, crop)| export_baking_alone(&d, &DxfOptions { region, crop, ..o.clone() })).collect::>(); + let after = || export_drawings(&d, &o, &drawings).unwrap(); + let time = |f: &dyn Fn() -> Vec| { + let (cpu, wall) = (thread_cpu_ns(), std::time::Instant::now()); + let outs = f(); + let wall = wall.elapsed().as_secs_f64() * 1000.0; + let cpu = cpu.zip(thread_cpu_ns()).map(|(a, b)| (b - a) as f64 / 1e6); + (outs, cpu, wall) + }; + let (mut runs_before, mut runs_after) = (vec![], vec![]); + for _ in 0..7 { + let (a, cpu_a, wall_a) = time(&before); + let (b, cpu_b, wall_b) = time(&after); + assert_eq!(a.len(), BOARDS); + assert_eq!(a.iter().map(written).collect::>(), b.iter().map(written).collect::>(), "both write the same drawings"); + runs_before.push((cpu_a, wall_a)); + runs_after.push((cpu_b, wall_b)); + } + let median = |runs: &[(Option, f64)], cpu: bool| { + let mut v: Vec = runs.iter().filter_map(|r| if cpu { r.0 } else { Some(r.1) }).collect(); + v.sort_by(f64::total_cmp); + v.get(v.len() / 2).copied() + }; + for (name, runs) in [("drawing by drawing", &runs_before), ("export_drawings", &runs_after)] { + println!( + "{name}: {BOARDS} artboards, median CPU {:?} ms, median wall {:?} ms; runs (CPU ms, wall ms) {runs:?}", + median(runs, true), + median(runs, false) + ); + } +} diff --git a/crates/color/src/cms.rs b/crates/color/src/cms.rs index 3ad4820ce1..96640b5508 100644 --- a/crates/color/src/cms.rs +++ b/crates/color/src/cms.rs @@ -347,7 +347,9 @@ pub fn profiles_generation() -> u64 { /// Profile `name` as an ICC file to embed in an export: any RGB or CMYK profile of [`profiles`] /// (by its current or legacy name), or [`GRAY`]. Built-in profiles are written in code from the /// CMS: the RGB spaces from their primaries, the CMYK spaces as lookup tables sampled from their -/// model (both directions, perceptual and relative colorimetric, Lab PCS); a profile the user +/// model (both directions, perceptual and relative colorimetric, Lab PCS, with the model's paper +/// as the media white point; the colorimetric Lab → CMYK table without black-point +/// compensation, the perceptual and saturation ones with it); a profile the user /// loaded is the file it came from. Cached. pub fn icc_bytes(name: &str) -> Result, CmsError> { static CACHE: Mutex)>> = Mutex::new(Vec::new()); @@ -361,8 +363,17 @@ pub fn icc_bytes(name: &str) -> Result, CmsError> { let bytes: Arc<[u8]> = if name == GRAY { icc::encode(&icc::gray_profile(name))? } else if BUILTIN_CMYK.contains(&name) { - let cms = Cms::new(&ColorSettings { cmyk: name.into(), ..ColorSettings::default() })?; - icc::encode(&icc::cmyk_profile(name, |c| cms.cmyk_to_lab(c), |l| cms.lab_to_cmyk(l, Intent::RelativeColorimetric)))? + // The perceptual and saturation tables map the shadows with black-point compensation; the + // colorimetric table is the inverse of the CMYK → Lab table, without it. + let mapped = Cms::new(&ColorSettings { cmyk: name.into(), bpc: true, ..ColorSettings::default() })?; + let cms = Cms::new(&ColorSettings { cmyk: name.into(), bpc: false, ..ColorSettings::default() })?; + let paper = match &cms.cmyk { + CmykSpace::Generic(g) => g.paper_xyz(), + CmykSpace::Device | CmykSpace::Icc(_) => lab::D50, + }; + let to_lab = |c| cms.cmyk_to_lab(c); + let shadows = |l| mapped.lab_to_cmyk(l, Intent::RelativeColorimetric); + icc::encode(&icc::cmyk_profile(name, paper, to_lab, shadows, |l| cms.lab_to_cmyk(l, Intent::RelativeColorimetric)))? } else { icc::builtin_rgb_bytes(name)? } diff --git a/crates/color/src/cms/generic.rs b/crates/color/src/cms/generic.rs index 3d532ac02a..16f251054b 100644 --- a/crates/color/src/cms/generic.rs +++ b/crates/color/src/cms/generic.rs @@ -133,6 +133,11 @@ pub struct GenericCmyk { } impl GenericCmyk { + /// Absolute XYZ (D50) of the paper. + pub fn paper_xyz(&self) -> [f32; 3] { + self.paper_xyz + } + pub fn new(params: GenericCmykParams) -> Self { let paper_xyz = lab_to_xyz(params.paper); let mut prim = [D50; 16]; diff --git a/crates/color/src/cms/icc.rs b/crates/color/src/cms/icc.rs index ffddd6c955..8fc287ae23 100644 --- a/crates/color/src/cms/icc.rs +++ b/crates/color/src/cms/icc.rs @@ -446,11 +446,20 @@ const B2A_GRID: usize = 17; const GAMUT_GRID: usize = 9; /// A CMYK output profile sampled from a conversion: `to_lab` (CMYK → media-relative Lab) in a -/// 9⁴ table, `from_lab` (Lab → CMYK, gamut-mapped) in a 17³ table, Lab PCS (ICC v4 encoding). +/// 9⁴ table, and Lab → CMYK in 17³ tables, Lab PCS (ICC v4 encoding): `mapped` (gamut-mapped, +/// with black-point compensation) for the perceptual and saturation intents, `colorimetric` (the +/// colorimetric inverse of `to_lab`) for the colorimetric intents and the gamut tag. /// It carries every tag ICC.1 requires of an output profile: the tables for all three intents /// and the gamut tag (Windows rejects a CMYK profile without them, so Photos couldn't show a CMYK -/// TIFF that embedded one, #2707). -pub(super) fn cmyk_profile(name: &str, to_lab: impl Fn([f32; 4]) -> lab::Lab, from_lab: impl Fn(lab::Lab) -> [f32; 4]) -> ColorProfile { +/// TIFF that embedded one, #2707). The media white point is `paper` (absolute XYZ, D50), which +/// the ICC-absolute colorimetric intent reproduces. +pub(super) fn cmyk_profile( + name: &str, + paper: [f32; 3], + to_lab: impl Fn([f32; 4]) -> lab::Lab, + mapped: impl Fn(lab::Lab) -> [f32; 4], + colorimetric: impl Fn(lab::Lab) -> [f32; 4], +) -> ColorProfile { let unit = |i: usize, n: usize| i as f32 / (n - 1) as f32; let q = |v: f32| (v.clamp(0.0, 1.0) * 65535.0).round() as u16; let mut a2b = Vec::with_capacity(A2B_GRID.pow(4) * 3); @@ -459,17 +468,21 @@ pub(super) fn cmyk_profile(name: &str, to_lab: impl Fn([f32; 4]) -> lab::Lab, fr let l = to_lab(cmyk); a2b.extend([l.l / 100.0, (l.a + 128.0) / 255.0, (l.b + 128.0) / 255.0].map(q)); } - let mut b2a = Vec::with_capacity(B2A_GRID.pow(3) * 4); - for i in 0..B2A_GRID.pow(3) { - let [l, a, b] = [2, 1, 0].map(|d| unit(i / B2A_GRID.pow(d) % B2A_GRID, B2A_GRID)); - b2a.extend(from_lab(lab::Lab::new(l * 100.0, a * 255.0 - 128.0, b * 255.0 - 128.0)).map(q)); - } + let b2a_of = |from_lab: &dyn Fn(lab::Lab) -> [f32; 4]| { + let mut b2a = Vec::with_capacity(B2A_GRID.pow(3) * 4); + for i in 0..B2A_GRID.pow(3) { + let [l, a, b] = [2, 1, 0].map(|d| unit(i / B2A_GRID.pow(d) % B2A_GRID, B2A_GRID)); + b2a.extend(from_lab(lab::Lab::new(l * 100.0, a * 255.0 - 128.0, b * 255.0 - 128.0)).map(q)); + } + b2a + }; + let (b2a_mapped, b2a) = (b2a_of(&mapped), b2a_of(&colorimetric)); // Gamut: 0 where a colour separates and comes back within a ΔE of 3, else out of gamut. let mut gamut = Vec::with_capacity(GAMUT_GRID.pow(3)); for i in 0..GAMUT_GRID.pow(3) { let [l, a, b] = [2, 1, 0].map(|d| unit(i / GAMUT_GRID.pow(d) % GAMUT_GRID, GAMUT_GRID)); let want = lab::Lab::new(l * 100.0, a * 255.0 - 128.0, b * 255.0 - 128.0); - gamut.push(if lab::delta_e2000(want, to_lab(from_lab(want))) <= 3.0 { 0 } else { u16::MAX }); + gamut.push(if lab::delta_e2000(want, to_lab(colorimetric(want))) <= 3.0 { 0 } else { u16::MAX }); } let identity = |n: usize| vec![ToneReprCurve::Parametric(vec![1.0]); n]; let table = |inputs: usize, outputs: usize, grid: usize, clut: Vec| { @@ -490,6 +503,7 @@ pub(super) fn cmyk_profile(name: &str, to_lab: impl Fn([f32; 4]) -> lab::Lab, fr }) }; let a2b = table(4, 3, A2B_GRID, a2b); + let b2a_mapped = table(3, 4, B2A_GRID, b2a_mapped); let b2a = table(3, 4, B2A_GRID, b2a); let gamut = table(3, 1, GAMUT_GRID, gamut); let mut p = ColorProfile::default(); @@ -498,12 +512,12 @@ pub(super) fn cmyk_profile(name: &str, to_lab: impl Fn([f32; 4]) -> lab::Lab, fr p.pcs = DataColorSpace::Lab; p.rendering_intent = RenderingIntent::RelativeColorimetric; p.white_point = moxcms::WHITE_POINT_D50.to_xyzd(); - p.media_white_point = Some(p.white_point); + p.media_white_point = Some(moxcms::Xyzd::new(f64::from(paper[0]), f64::from(paper[1]), f64::from(paper[2]))); p.lut_a_to_b_perceptual = Some(a2b.clone()); p.lut_a_to_b_saturation = Some(a2b.clone()); p.lut_a_to_b_colorimetric = Some(a2b); - p.lut_b_to_a_perceptual = Some(b2a.clone()); - p.lut_b_to_a_saturation = Some(b2a.clone()); + p.lut_b_to_a_perceptual = Some(b2a_mapped.clone()); + p.lut_b_to_a_saturation = Some(b2a_mapped); p.lut_b_to_a_colorimetric = Some(b2a); p.gamut = Some(gamut); labelled(p, name) diff --git a/crates/color/src/cms/tests_icc.rs b/crates/color/src/cms/tests_icc.rs index bee0f0f9fa..2c1d96638b 100644 --- a/crates/color/src/cms/tests_icc.rs +++ b/crates/color/src/cms/tests_icc.rs @@ -30,11 +30,62 @@ fn cmyk_profiles_convert_like_the_cms() { let de = delta_e2000(lab::srgb_to_lab(want), lab::srgb_to_lab(got)); assert!(de < 2.5, "{name} {cmyk:?}: {want:?} vs {got:?} (ΔE {de})"); } - // And back: an in-gamut colour separates to about the same inks. - let srgb = cms.cmyk_to_srgb([0.1, 0.6, 0.8, 0.0], false); - let back = p.from_srgb(srgb, Intent::RelativeColorimetric).unwrap(); - let again = cms.cmyk_to_srgb([back[0], back[1], back[2], back[3]], false); - assert!(delta_e2000(lab::srgb_to_lab(srgb), lab::srgb_to_lab(again)) < 3.0, "{back:?}"); + // And back: in-gamut colours separate to inks that print them. The Lab → CMYK table is + // the colorimetric inverse of the CMYK → Lab table, with no black-point compensation. + for inks in [ + [0.1, 0.6, 0.8, 0.0], + [0.5, 0.1, 0.3, 0.1], + [0.3, 0.3, 0.3, 0.2], + [0.05, 0.05, 0.4, 0.0], + [0.4, 0.3, 0.3, 0.6], + [0.6, 0.5, 0.5, 0.4], + [0.2, 0.2, 0.2, 0.8], + [0.0, 0.0, 0.0, 0.5], + ] { + let srgb = cms.cmyk_to_srgb(inks, false); + let back = p.from_srgb(srgb, Intent::RelativeColorimetric).unwrap(); + let again = cms.cmyk_to_srgb([back[0], back[1], back[2], back[3]], false); + let de = delta_e2000(lab::srgb_to_lab(srgb), lab::srgb_to_lab(again)); + assert!(de < 1.5, "{name} {inks:?}: {srgb:?} -> {back:?} -> {again:?} (ΔE {de})"); + } + // The perceptual table keeps black-point compensation: source black separates to inks + // that print the press's black point, as the CMS separates it with compensation. + let compensated = Cms::new(&ColorSettings { cmyk: name.into(), bpc: true, ..Default::default() }).unwrap(); + let want = compensated.srgb_to_cmyk([0.0; 3], Intent::RelativeColorimetric); + let got = p.from_srgb([0.0; 3], Intent::Perceptual).unwrap(); + let printed = |inks: &[f32]| cms.cmyk_to_lab([inks[0], inks[1], inks[2], inks[3]]); + let de = delta_e2000(printed(&want), printed(&got)); + assert!(de < 1.5, "{name}: perceptual black {got:?} prints {:?}, want {want:?} ({:?})", printed(&got), printed(&want)); + } +} + +#[test] +fn cmyk_profiles_separate_saturated_inks_back_without_clipping_to_srgb() { + // CMYK → PCS → CMYK through the profile's own colorimetric tables, by way of linear ProPhoto + // RGB, which holds every color these profiles print, so no display gamut clips the inks. + // Inks that print outside sRGB come back to inks that print the same color. + for name in BUILTIN_CMYK { + let p = IccProfile::from_bytes(None, &icc_bytes(name).unwrap()).unwrap(); + let cms = Cms::new(&ColorSettings { cmyk: name.into(), bpc: false, ..Default::default() }).unwrap(); + for inks in + [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [1.0, 1.0, 0.0, 0.0], [0.0, 1.0, 1.0, 0.0], [1.0, 0.0, 1.0, 0.0]] + { + let back = p.to_same_model_of(&p, &inks, Intent::RelativeColorimetric, false).unwrap(); + let de = delta_e2000(cms.cmyk_to_lab(inks), cms.cmyk_to_lab([back[0], back[1], back[2], back[3]])); + // Within the ΔE of 3 that the gamut tag counts as reproduced. + assert!(de <= 3.0, "{name} {inks:?} -> {back:?} (ΔE {de})"); + } + } +} + +#[test] +fn cmyk_profiles_carry_their_paper_as_the_media_white() { + let generic = generic::swop_like(); + let p = parse(&icc_bytes(GENERIC_CMYK).unwrap()); + let white = p.media_white_point.unwrap(); + let paper = lab::lab_to_xyz(generic.paper); + for (got, want) in [white.x, white.y, white.z].iter().zip(paper) { + assert!((*got - f64::from(want)).abs() < 2e-3, "{white:?} vs {paper:?}"); } } @@ -116,9 +167,10 @@ fn black_point_compensation_maps_the_darkest_ink_to_rgb_black() { let rich = [0.75, 0.68, 0.67, 0.9]; let (on, off) = (icc_cmyk(true).cmyk_to_rgb(rich, Intent::RelativeColorimetric), icc_cmyk(false).cmyk_to_rgb(rich, Intent::RelativeColorimetric)); // Without compensation the profile's black is a dark grey; with it, rich black goes most of - // the way to RGB black (not all: it isn't quite the darkest ink the profile prints). + // the way to RGB black (not all: it isn't quite the darkest ink the profile prints, and the + // profile's Lab → CMYK table carries no compensation of its own). assert!(off.iter().all(|v| *v > 0.1), "without: {off:?}"); - assert!(on.iter().zip(off).all(|(a, b)| *a < 0.08 && *a < b * 0.5), "with: {on:?}, without: {off:?}"); + assert!(on.iter().zip(off).all(|(a, b)| *a < 0.09 && *a < b * 0.55), "with: {on:?}, without: {off:?}"); // The screen shows what an sRGB conversion writes, compensated alike. let srgb = |bpc| { let c = icc_cmyk(bpc); diff --git a/crates/doc/src/appearance.rs b/crates/doc/src/appearance.rs index 3bfba32f6a..737e10eb58 100644 --- a/crates/doc/src/appearance.rs +++ b/crates/doc/src/appearance.rs @@ -143,6 +143,11 @@ impl Appearance { pub fn fill_paint(&self) -> Paint { self.fill().map(|f| f.paint.clone()).unwrap_or(Paint::None) } + /// Whether any visible fill has non-None paint. Unlike [`Self::fill`], this + /// includes lower fills in the stack; zero opacity still counts for selecting its geometry. + pub fn has_visible_fill(&self) -> bool { + self.items.iter().any(|item| matches!(item, AppearanceItem::Fill(fill) if fill.visible && !fill.paint.is_none())) + } pub fn stroke_paint(&self) -> Paint { self.stroke().map(|s| s.paint.clone()).unwrap_or(Paint::None) } diff --git a/crates/doc/src/appearance/layers.rs b/crates/doc/src/appearance/layers.rs index f8a58758d8..5e07dc6cde 100644 --- a/crates/doc/src/appearance/layers.rs +++ b/crates/doc/src/appearance/layers.rs @@ -71,6 +71,11 @@ pub struct StrokeLayer { /// Brush applied to the stroke (by brush name). #[serde(default, skip_serializing_if = "Option::is_none")] pub brush: Option, + /// This stroke's own brush settings (the Brushes panel's Options of Selected Object): brush + /// definition fields, by their `brush.options` names, that replace the brush's values on this + /// stroke only. Empty: the stroke draws the brush as it is. `vectorcraft-brush` reads them. + #[serde(default, skip_serializing_if = "serde_json::Map::is_empty")] + pub brush_options: serde_json::Map, #[serde(default = "one", skip_serializing_if = "crate::skip::is_one")] pub opacity: f32, #[serde(default, skip_serializing_if = "crate::skip::is_default")] @@ -170,6 +175,7 @@ impl StrokeLayer { arrow_scale: (100.0, 100.0), profile: None, brush: None, + brush_options: serde_json::Map::new(), opacity: 1.0, blend: BlendMode::Normal, visible: true, diff --git a/crates/doc/src/dimension.rs b/crates/doc/src/dimension.rs index e803d867fc..9e78d17d4d 100644 --- a/crates/doc/src/dimension.rs +++ b/crates/doc/src/dimension.rs @@ -112,6 +112,18 @@ pub enum ArrowStyle { None, } +impl ArrowStyle { + /// The stroke arrowhead drawn at each end of the dimension line, or None for no head. + pub fn arrowhead(self) -> Option { + match self { + Self::Filled => Some(crate::Arrowhead::Triangle), + Self::Open => Some(crate::Arrowhead::TriangleOpen), + Self::Tick => Some(crate::Arrowhead::Slash), + Self::None => None, + } + } +} + /// Where the label sits across the dimension line. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index f4a307cd5c..4365f7788a 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -339,6 +339,7 @@ impl Document { /// Index path from the top-level layer list to `id` (e.g. `[0, 3, 1]`): the first place in /// tree order where `id` appears. pub fn index_path(&self, id: NodeId) -> Option> { + crate::id_index::note_path_lookup(); // The cached path, while the node there still has the id ([`id_index`]). let cached = self.index.get(); match cached.as_ref().and_then(|m| m.get(&id)) { @@ -423,6 +424,44 @@ impl Document { out } + /// Every node whose id is in `ids`, in tree order (the order of [`Document::walk`]): unlike + /// [`Document::index_paths`], an id that appears more than once (a damaged file) gives every + /// node that has it. When the cache ([`id_index`]) holds each id once, at a path that still + /// checks out, the nodes are found along those paths; otherwise one walk of the tree finds + /// them. As for every cached lookup, a second node given an existing id after the cache was + /// built is not found while the first one's cached path checks out (see [`id_index`]). + pub fn nodes_in_order(&self, ids: impl IntoIterator) -> Vec<&Node> { + let want: std::collections::HashSet> = ids.into_iter().collect(); + // As in `index_paths`, one walk is quicker than checking the cached paths of a good share + // of the document. + if let Some(cache) = self.index.get().filter(|c| want.len().saturating_mul(8) < c.len()) { + let mut paths = Vec::with_capacity(want.len()); + let cached = want.iter().all(|id| match cache.get(id) { + Some(Some(p)) if self.node_at(&p).is_some_and(|n| n.id == *id) => { + paths.push(p); + true + } + _ => false, + }); + if cached { + // A node's path sorts after the paths of the nodes before it in tree order, its + // ancestors included. + paths.sort_unstable(); + return paths.iter().filter_map(|p| self.node_at(p)).collect(); + } + } + let mut out = Vec::new(); + if !want.is_empty() { + crate::id_index::note_tree_walk(); + self.walk(|n| { + if want.contains(&n.id) { + out.push(n); + } + }); + } + out + } + /// The node at index path `path` (as [`Document::index_path`] gives it). pub fn node_at(&self, path: &[usize]) -> Option<&Node> { let (first, rest) = path.split_first()?; diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index 3b415ef1ed..93baa85ed8 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -82,8 +82,9 @@ impl Default for HitOptions { } } -/// The shapes that an image's own fills and strokes paint, each with its fill rule and the fill or -/// stroke that paints it (none for fills and strokes that paint nothing). Effects are evaluated +/// The shapes that an image's own fills and strokes paint, or the fills and strokes of the art of a +/// symbol instance whose own fill or stroke has a geometry effect, each with its fill rule and the +/// fill or stroke that paints it (none for fills and strokes that paint nothing). Effects are evaluated /// above this crate, so the engine registers one with [`set_image_paint`]. It looks up swatches and /// patterns in the document it is given. pub type ImagePaint = fn(Option<&Document>, &Node) -> Vec<(BezPath, FillRule, AppearanceItem)>; @@ -97,10 +98,58 @@ pub fn set_image_paint(f: ImagePaint) { let _ = IMAGE_PAINT.set(f); } -/// The shapes that the image `n`'s own fills and strokes paint ([`set_image_paint`]), none while -/// nothing is registered. -pub(crate) fn image_paint(doc: Option<&Document>, n: &Node) -> Vec<(BezPath, FillRule, AppearanceItem)> { - IMAGE_PAINT.get().map_or_else(Vec::new, |f| f(doc, n)) +/// The shapes that [`ImagePaint`] gives for one object. +type Painted = Vec<(BezPath, FillRule, AppearanceItem)>; + +/// The shapes that the image or symbol instance `n` paints with its geometry effects +/// ([`set_image_paint`]), none while nothing is registered. The shapes of a symbol instance of +/// `doc` with an effect on a fill or stroke are kept on this thread ([`PAINT_KEPT`]) and measured +/// again when `n`, a symbol of `doc` or its 9-slice guides or natural size, a pattern of `doc`, +/// its swatches or color groups, or the +/// [`LiveInputs`] have changed since, and on every call while `n` or the document's symbols or +/// patterns hold a placed document or the symbols hold an image ([`symbols_hold_images`]). +pub(crate) fn image_paint(doc: Option<&Document>, n: &Node) -> Rc { + let Some(f) = IMAGE_PAINT.get() else { return Rc::default() }; + let row_effects = || n.appearance.items.iter().any(|i| !i.effects().is_empty()); + let Some(d) = doc.filter(|_| matches!(n.kind, NodeKind::SymbolInstance { .. }) && row_effects()) else { + return Rc::new(f(doc, n)); + }; + let inputs = live_inputs(); + if let Some(painted) = kept(&PAINTED, d, n, inputs) { + return painted; + } + #[cfg(test)] + PAINT_EVALUATED.with(|c| c.set(c.get() + 1)); + let painted = Rc::new(f(doc, n)); + if !symbols_hold_images(d) { + let size = painted.iter().fold(0usize, |s, (bp, _, _)| s.saturating_add(1 + bp.elements().len())); + keep(&PAINTED, d, n, inputs, &painted, size, PAINT_KEPT); + } + painted +} + +/// Does the art of a symbol of `doc` hold an image? The shapes its fills and strokes paint can +/// follow its pixels, which change when its file is read again, so [`image_paint`] does not keep +/// the shapes of an instance then. +fn symbols_hold_images(doc: &Document) -> bool { + let mut image = false; + doc.symbols.iter().for_each(|s| s.art.walk(&mut |c| image |= matches!(c.kind, NodeKind::Image(_)))); + image +} + +/// How many symbol instances' shapes [`image_paint`] keeps on each thread: every click and every +/// hover measures each instance whose fill or stroke has a geometry effect. +const PAINT_KEPT: usize = 64; + +thread_local! { + /// The shapes [`image_paint`] keeps, the latest first. + static PAINTED: RefCell>> = const { RefCell::new(Vec::new()) }; +} + +#[cfg(test)] +thread_local! { + /// How many symbol instances [`image_paint`] measured on this thread. + static PAINT_EVALUATED: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// One level of evaluation of a live object in a document, as the canvas draws it: type in an @@ -127,21 +176,72 @@ fn live_inputs() -> u64 { LIVE_ART.get().map_or(0, |(_, inputs)| inputs()) } -/// A live object evaluated by [`live_art`] on this thread: the object, its document's symbols (by -/// name and art), patterns, swatches and color groups and the [`LiveInputs`] as they were, the art -/// and its [`art_size`]. -struct EvaluatedLive { +/// An object evaluated by [`live_art`] or [`image_paint`] on this thread: the object, its +/// document's symbols (by name and art), patterns, swatches and color groups, the document data +/// that symbols' 9-slice guides and natural sizes are kept in, and the [`LiveInputs`] as they +/// were, the result and its size. +struct Evaluated { node: Node, symbols: Vec<(String, Arc)>, patterns: Vec, swatches: crate::Shared>, swatch_groups: crate::Shared>, + unknown: crate::Shared>, inputs: u64, - art: Rc>, + art: Rc, size: usize, } -impl EvaluatedLive { +/// The evaluations kept on this thread in one store, the latest first. +type Store = std::thread::LocalKey>>>; + +/// The evaluation of `n` in `doc` with inputs `inputs` that `store` keeps, moved to the front. +fn kept(store: &'static Store, doc: &Document, n: &Node, inputs: u64) -> Option> { + store.with_borrow_mut(|kept| { + let i = kept.iter().position(|e| e.is_of(doc, n, inputs))?; + let e = kept.remove(i); + let art = e.art.clone(); + kept.insert(0, e); + Some(art) + }) +} + +/// Keep `art`, of size `size`, the evaluation of `n` in `doc` with inputs `inputs`, at the front +/// of `store`, which keeps `most` evaluations whose sizes add up to [`LIVE_KEPT_SIZE`] at most. +/// Nothing is kept when `art` alone is larger, or when `n` or the document's symbols or patterns +/// hold a placed document ([`holds_placed`]). +fn keep(store: &'static Store, doc: &Document, n: &Node, inputs: u64, art: &Rc, size: usize, most: usize) { + if size > LIVE_KEPT_SIZE || holds_placed(doc, n) { + return; + } + let e = Evaluated::new(doc, n, inputs, art, size); + store.with_borrow_mut(|kept| { + kept.insert(0, e); + kept.truncate(most); + let mut total = 0usize; + kept.retain(|e| { + total = total.saturating_add(e.size); + total <= LIVE_KEPT_SIZE + }); + }); +} + +impl Evaluated { + /// `art`, of size `size`, the evaluation of `n` in `doc` with inputs `inputs`, as they are now. + fn new(doc: &Document, n: &Node, inputs: u64, art: &Rc, size: usize) -> Self { + Self { + node: n.clone(), + symbols: doc.symbols.iter().map(|s| (s.name.clone(), s.art.clone())).collect(), + patterns: doc.patterns.clone(), + swatches: doc.swatches.clone(), + swatch_groups: doc.swatch_groups.clone(), + unknown: doc.unknown.clone(), + inputs, + art: art.clone(), + size, + } + } + /// Is this the evaluation of `n` in `doc`, with inputs `inputs`, as they are now? fn is_of(&self, doc: &Document, n: &Node, inputs: u64) -> bool { self.inputs == inputs @@ -151,6 +251,7 @@ impl EvaluatedLive { && self.patterns == doc.patterns && self.swatches == doc.swatches && self.swatch_groups == doc.swatch_groups + && self.unknown == doc.unknown } } @@ -158,8 +259,9 @@ impl EvaluatedLive { /// envelope's stroke band hits it again and again, and an envelope can hold a blend. const LIVE_KEPT: usize = 4; -/// Most [`art_size`] the evaluations [`live_art`] keeps on one thread add up to. Art larger than -/// this is not kept. +/// Most size the evaluations [`live_art`] keeps on one thread add up to ([`art_size`]), and the +/// shapes [`image_paint`] keeps (each shape and its path elements). Art larger than this is not +/// kept. const LIVE_KEPT_SIZE: usize = 250_000; /// The size of `art` for [`LIVE_KEPT_SIZE`]: its objects and the anchors of their paths. @@ -184,52 +286,23 @@ fn holds_placed(doc: &Document, n: &Node) -> bool { thread_local! { /// The evaluations [`live_art`] keeps, the latest first. - static EVALUATED: RefCell> = const { RefCell::new(Vec::new()) }; + static EVALUATED: RefCell>>> = const { RefCell::new(Vec::new()) }; } /// The art live object `n` of `doc` draws ([`set_live_art`]); [`crate::live::expand_live`] while -/// nothing is registered. The art is evaluated again when `n`, a symbol of `doc`, a pattern of -/// `doc`, its swatches or color groups, or the [`LiveInputs`] have changed since, and on every +/// nothing is registered. The art is evaluated again when `n`, a symbol of `doc` or its 9-slice +/// guides or natural size, a pattern of `doc`, its swatches or color groups, or the +/// [`LiveInputs`] have changed since, and on every /// click while it or the document's symbols or patterns hold a placed document ([`holds_placed`]). fn live_art(doc: &Document, n: &Node) -> Rc> { let inputs = live_inputs(); - let kept = EVALUATED.with_borrow_mut(|kept| { - let i = kept.iter().position(|e| e.is_of(doc, n, inputs))?; - let e = kept.remove(i); - let art = e.art.clone(); - kept.insert(0, e); - Some(art) - }); - if let Some(art) = kept { + if let Some(art) = kept(&EVALUATED, doc, n, inputs) { return art; } #[cfg(test)] LIVE_EVALUATED.with(|c| c.set(c.get() + 1)); let art = Rc::new(LIVE_ART.get().map_or_else(|| crate::live::expand_live(n), |(f, _)| f(Some(doc), n))); - let size = art_size(&art); - if size > LIVE_KEPT_SIZE || holds_placed(doc, n) { - return art; - } - let symbols = doc.symbols.iter().map(|s| (s.name.clone(), s.art.clone())).collect(); - let e = EvaluatedLive { - node: n.clone(), - symbols, - patterns: doc.patterns.clone(), - swatches: doc.swatches.clone(), - swatch_groups: doc.swatch_groups.clone(), - inputs, - art: art.clone(), - size, - }; - EVALUATED.with_borrow_mut(|kept| { - kept.insert(0, e); - kept.truncate(LIVE_KEPT); - let mut total = 0usize; - kept.retain(|e| { - total = total.saturating_add(e.size); - total <= LIVE_KEPT_SIZE - }); - }); + keep(&EVALUATED, doc, n, inputs, &art, art_size(&art), LIVE_KEPT); art } @@ -257,7 +330,7 @@ pub fn set_drawn_art(f: DrawnArt) { /// The art of an object found by [`drawn`] (none, or one object), with what it was found from, and /// the box round everything that art can paint. struct EvaluatedDrawn { - of: EvaluatedLive, + of: Evaluated>, reach: Option, } @@ -310,7 +383,8 @@ fn plain(mask: bool, f: impl FnOnce() -> T) -> T { /// nothing is registered, while a [`DrawnOff`] guard lives, for objects whose art is not evaluated /// ([`evaluates`]), and when nothing in `n`, nor the art of a symbol an instance in it shows, has a /// visible effect ([`draws_effects`]). The art is evaluated again when `n`, a symbol of the -/// document, its patterns, swatches or color groups, or the [`LiveInputs`] have changed since, and +/// document or its 9-slice guides or natural size, its patterns, swatches or color groups, or the +/// [`LiveInputs`] have changed since, and /// on every call while it holds a placed document ([`holds_placed`]). When the art kept is full, new /// art replaces as much other art as it needs room for, and art larger than [`LIVE_KEPT_SIZE`] is /// kept alone. @@ -332,16 +406,7 @@ fn drawn(symbols: &SymbolBoxes, n: &Node) -> Option<(Rc>, Option let art = Rc::new(art.into_iter().collect::>()); let size = art_size(&art).saturating_add(art_size(std::slice::from_ref(n))); if !holds_placed(doc, n) { - let of = EvaluatedLive { - node: n.clone(), - symbols: doc.symbols.iter().map(|s| (s.name.clone(), s.art.clone())).collect(), - patterns: doc.patterns.clone(), - swatches: doc.swatches.clone(), - swatch_groups: doc.swatch_groups.clone(), - inputs, - art: art.clone(), - size, - }; + let of = Evaluated::new(doc, n, inputs, &art, size); DRAWN.with_borrow_mut(|(kept, total)| { if let Some(old) = kept.remove(&n.id) { *total = total.saturating_sub(old.of.size); @@ -607,9 +672,11 @@ fn objects_at_repeated(doc: &Document, p: Point, opt: HitOptions, scope: Option< /// [`objects_at_repeated`] after `tops`, the topmost objects under `p` already found. fn objects_at_repeated_after(doc: &Document, p: Point, opt: HitOptions, scope: Option, mut tops: Vec) -> Vec { - // Each round leaves out the objects found so far (and everything inside them). - while let Some(top) = hit_test_skipping(doc, p, opt, &|id| tops.contains(&id), true).map(|h| h.top_object(scope)) { - if tops.contains(&top) { + // Each round leaves out the objects found so far (and everything inside them). `found` holds + // the same ids as `tops`, which keeps their order. + let mut found: HashSet = tops.iter().copied().collect(); + while let Some(top) = hit_test_skipping(doc, p, opt, &|id| found.contains(&id), true).map(|h| h.top_object(scope)) { + if !found.insert(top) { break; } tops.push(top); @@ -1290,8 +1357,9 @@ fn hit_stroke(n: &Node, bp: &vectorcraft_geom::BezPath, rule: vectorcraft_geom:: stroke_contains(bp, 0.0, opt.tol, p).then_some(HitKind::Outline) } -/// Check the body without assembling a `BezPath`. A miss near a joint or cap may still hit a -/// miter or square cap, so the caller falls back to the full stroke check there. +/// Check the body without assembling a `BezPath`. Near an end or joint, the caller uses the +/// full stroke check for non-round caps or joins: Butt and Bevel can reject a radial body hit, +/// while Miter and Square can extend beyond it. fn near_path_body(path: &PathData, p: Point, radius: f64, decoration_reach: f64) -> Option<(bool, bool)> { if !radius.is_finite() || radius < 0.0 || !decoration_reach.is_finite() || decoration_reach < 0.0 { return None; @@ -1349,6 +1417,7 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio } match &n.kind { NodeKind::Path { path, rule, .. } => { + let has_fill = n.appearance.has_visible_fill(); if opt.outline && let Some((hit, needs_full_check)) = near_path_body(path, p, opt.tol, 0.0) { @@ -1361,7 +1430,7 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio } let mut strokes = n.appearance.painted_strokes(); if !opt.outline - && n.appearance.fill().is_none_or(|f| f.paint.is_none()) + && !has_fill && let Some(s) = strokes.next() && strokes.next().is_none() && s.align == StrokeAlign::Center @@ -1376,10 +1445,10 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio path, p, s.width / 2.0 + opt.tol, - if s.join == crate::LineJoin::Miter || s.cap == crate::LineCap::Square { s.reach() + opt.tol } else { 0.0 }, + if s.join != crate::LineJoin::Round || s.cap != crate::LineCap::Round { s.reach() + opt.tol } else { 0.0 }, ) { - if hit { + if hit && !near_decoration { return Some(HitKind::Stroke); } if !near_decoration { @@ -1390,8 +1459,7 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio if let Some(k) = hit_stroke(n, &bp, *rule, p, opt) { return Some(k); } - let filled = !n.appearance.fill_paint().is_none(); - if !opt.outline && !opt.path_only && filled && fill_contains(&bp, *rule, p) { + if !opt.outline && !opt.path_only && has_fill && fill_contains(&bp, *rule, p) { return Some(HitKind::Fill); } None @@ -1412,7 +1480,7 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio if vectorcraft_geom::hit::distance_to_outline(&near, p) <= opt.tol { return Some(HitKind::Outline); } - (!opt.outline && !opt.path_only && fill_contains(&near, *rule, p)).then_some(HitKind::Fill) + (!opt.outline && !opt.path_only && n.appearance.has_visible_fill() && fill_contains(&near, *rule, p)).then_some(HitKind::Fill) } // The type path lies within the bounds: they rule out the rest before it is measured. NodeKind::Text(t) if opt.type_path_only => { @@ -1436,22 +1504,21 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio if opt.outline { return None; } - image_paint(Some(symbols.document()), n).iter().rev().find_map(|(bp, rule, item)| match item { - AppearanceItem::Stroke(s) => s.hits(bp, *rule, p, opt.tol).then_some(HitKind::Stroke), - AppearanceItem::Fill(_) => (!opt.path_only && fill_contains(bp, *rule, p)).then_some(HitKind::Fill), - }) + hit_painted(n, p, opt, symbols) } NodeKind::Text(_) | NodeKind::PlacedDocument(_) => { n.geometric_bounds_with(symbols).filter(|b| b.inflate(opt.tol, opt.tol).contains(p)).map(|_| HitKind::Bounds) } // A symbol instance is hit within its bounds, and outside them where its art paints - // ([`instance_art_hit`]). In the art of another instance walked outside that instance's - // bounds, it is hit only where its own art paints ([`ArtOnly`]). + // ([`instance_art_hit`]) or where the geometry effects of its active fill or stroke reshape + // the art it draws ([`image_paint`]) except in outline mode. In the art of another instance + // walked outside that instance's bounds, it is hit only where its own art paints + // ([`ArtOnly`]). NodeKind::SymbolInstance { .. } => { if !ArtOnly::on() && n.geometric_bounds_with(symbols).is_some_and(|b| b.inflate(opt.tol, opt.tol).contains(p)) { return Some(HitKind::Bounds); } - instance_art_hit(n, p, opt, symbols) + instance_art_hit(n, p, opt, symbols).or_else(|| if opt.outline { None } else { hit_painted(n, p, opt, symbols) }) } // A blend or an envelope is hit within its bounds, and outside them where its evaluated // art paints: a blend's keys and steps on a spine can reach past the keys and the spine, @@ -1478,6 +1545,16 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio } } +/// What a click at `p` hits among the shapes that the fills and strokes of `n` (an image or a +/// symbol instance) paint with their geometry effects ([`image_paint`]), the frontmost first: a +/// stroke along its shape, a fill inside it except with Selection by Path Only. +fn hit_painted(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option { + image_paint(Some(symbols.document()), n).iter().rev().find_map(|(bp, rule, item)| match item { + AppearanceItem::Stroke(s) => s.hits(bp, *rule, p, opt.tol).then_some(HitKind::Stroke), + AppearanceItem::Fill(_) => (!opt.path_only && fill_contains(bp, *rule, p)).then_some(HitKind::Fill), + }) +} + /// Is `p` within `tol` of the type path of `t` (in `n`), what "Type Object Selection by Path /// Only" picks type by: its baselines ([`crate::TextObject::baselines`]), area type's frame and /// type on a path's path, drawn through `n`'s perspective projection if it has one. @@ -2019,7 +2096,9 @@ pub fn compound_part_at(n: &Node, p: Point, tol: f64) -> Option { /// Objects (children of layers, or of `scope` in isolation mode) touched by a marquee rect, leaving /// out those on a locked artboard ([`crate::LockedArtboards::holds_id`]). Symbol instances are measured /// by their art ([`Node::geometric_bounds_with`]), and outside that box, except in outline, they are -/// touched where the live geometry effects of a clipping path in their art show it. The art of a clip group or of a layer with a +/// touched where the live geometry effects of a clipping path in their art show it, or where the +/// geometry effects of their active fill or stroke reshape the art. Images are also touched, except +/// in outline, where their own fills and strokes paint outside their box. The art of a clip group or of a layer with a /// clipping mask counts only when the marquee meets the region its clipping path clips to, and then /// only within that region's bounds. In isolation mode the clipping mask of the isolated container, /// or of the parent of the single object isolated, does not limit the marquee, as it does not limit @@ -2188,8 +2267,10 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh /// 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. A clipping path is touched by - /// its own geometry ([`mask_marquee`]) and on the edge of its region ([`clip_edge_touches`]). + /// compound paths, layers and groups are touched by their box, and an image or a symbol + /// instance also where its fills and strokes paint outside it ([`painted_touches`]). 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 { // A path or compound path whose geometry effects reshape it, or a group or layer whose own // geometry effects reshape its members, is touched where that art is drawn ([`drawn_art`]). @@ -2219,12 +2300,27 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh 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 symbol instance is touched by its box, and outside it where the live geometry - // effects of a clipping path in its art show the art. In the art of another instance - // walked outside that instance's box, it is touched only by its own art ([`ArtOnly`]). - NodeKind::SymbolInstance { .. } => !ArtOnly::on() && box_touches(n, s, r) || !outline && instance_art_touches(n, s, r, whole_compounds), + // effects of a clipping path in its art show the art, or where the geometry effects of + // its active fill or stroke reshape the art ([`painted_touches`]). In the art of another + // instance walked outside that instance's box, it is touched only by its own art + // ([`ArtOnly`]) and those shapes. + NodeKind::SymbolInstance { .. } => { + !ArtOnly::on() && box_touches(n, s, r) || !outline && (instance_art_touches(n, s, r, whole_compounds) || painted_touches(n, s, r)) + } + // An image is touched by its box, and outside it where its own fills and strokes paint. + NodeKind::Image(_) => box_touches(n, s, r) || !outline && painted_touches(n, s, r), _ => box_touches(n, s, r), } } + /// Does the marquee `r` touch the shapes that the fills and strokes of image or symbol + /// instance `n` paint ([`image_paint`]), where clicks hit them ([`hit_painted`])? Each shape is + /// touched by its path, as a path is ([`vectorcraft_geom::hit::intersects_rect`]). Only when + /// `r` meets the reach of `n` ([`Node::reach_bounds_with`]). + fn painted_touches(n: &Node, s: &SymbolBoxes, r: Rect) -> bool { + let meets = |b: Rect| b.x0 <= r.x1 && r.x0 <= b.x1 && b.y0 <= r.y1 && r.y0 <= b.y1; + n.reach_bounds_with(s).is_some_and(meets) + && image_paint(Some(s.document()), n).iter().any(|(bp, _, _)| vectorcraft_geom::hit::intersects_rect(&PathData::from_bezpath(bp), r)) + } /// Does the marquee `r` touch the box of `n`? 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. fn box_touches(n: &Node, s: &SymbolBoxes, r: Rect) -> bool { diff --git a/crates/doc/src/hit/tests.rs b/crates/doc/src/hit/tests.rs index 39efd78795..9d0133ec60 100644 --- a/crates/doc/src/hit/tests.rs +++ b/crates/doc/src/hit/tests.rs @@ -1262,6 +1262,60 @@ fn evaluated_art_is_not_kept_while_a_placed_document_may_show_in_it() { assert_eq!(evaluated(), before + 2); } +/// For instances of the symbol "Painted", a fill that paints the square from (300, 0) to +/// (320, 20); nothing for anything else. +fn painted_far_away(_: Option<&Document>, n: &Node) -> Vec<(BezPath, FillRule, AppearanceItem)> { + match &n.kind { + NodeKind::SymbolInstance { symbol, .. } if symbol == "Painted" => { + let square = shapes::rectangle(Rect::new(300.0, 0.0, 320.0, 20.0)).to_bezpath(); + vec![(square, FillRule::NonZero, AppearanceItem::Fill(crate::FillLayer::new(Paint::solid(Color::rgb(1.0, 0.0, 0.0)))))] + } + _ => vec![], + } +} + +/// Clicks and hovers measure the shapes a symbol instance's fill and stroke effects paint once, +/// and again only after the instance or the symbols change. +#[test] +fn clicks_measure_a_symbol_instances_painted_shapes_once_until_it_changes() { + set_image_paint(painted_far_away); + let mut d = Document::new(1000.0, 1000.0); + let l = d.layers[0].id; + let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::default_art()); + d.symbols.push(crate::Symbol { dynamic: false, name: "Painted".into(), art: Arc::new(art) }); + let inst = d.alloc_id(); + let mut n = Node::new(inst, NodeKind::SymbolInstance { symbol: "Painted".into(), xf: vectorcraft_geom::Affine::IDENTITY }); + n.appearance = Appearance::default_art().into(); + let offset = crate::Effect { id: "path.offsetPath".into(), params: serde_json::json!({"offset": 10}), visible: true }; + n.appearance.items[0].effects_mut().push(offset); + d.insert(Some(l), 0, n).unwrap(); + let measured = || PAINT_EVALUATED.with(std::cell::Cell::get); + let before = measured(); + let at = |d: &Document, x: f64| hit_test(d, Point::new(x, 10.0), HitOptions::default()).map(|h| h.leaf); + assert_eq!(at(&d, 310.0), Some(inst), "a click where the instance's fill paints"); + assert_eq!(at(&d, 500.0), None); + assert_eq!(at(&d, 10.0), Some(inst)); + assert_eq!(measured(), before + 1); + d.node_mut(inst).unwrap().appearance.items[0].effects_mut()[0].params = serde_json::json!({"offset": 12}); + assert_eq!(at(&d, 310.0), Some(inst)); + assert_eq!(measured(), before + 2, "a changed instance is measured again"); + let other = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art()); + d.symbols.push(crate::Symbol { dynamic: false, name: "Other".into(), art: Arc::new(other) }); + assert_eq!(at(&d, 310.0), Some(inst)); + assert_eq!(measured(), before + 3, "changed symbols measure it again"); + assert_eq!(at(&d, 310.0), Some(inst)); + assert_eq!(measured(), before + 3); + // An image's pixels change when its file is read again, so with one in a symbol's art every + // click measures the instance. + let xf = vectorcraft_geom::Affine::IDENTITY; + let im = crate::ImageObject { key: "k".into(), width: 10, height: 10, xf, link: None, placement: Default::default(), pixels: None }; + let image = Node::new(d.alloc_id(), NodeKind::Image(Box::new(im))); + d.symbols.push(crate::Symbol { dynamic: false, name: "Photo".into(), art: Arc::new(image) }); + assert_eq!(at(&d, 310.0), Some(inst)); + assert_eq!(at(&d, 310.0), Some(inst)); + assert!(measured() >= before + 5, "each click measures it: {}", measured() - before); +} + /// A kept evaluation is the evaluation of the object only while the fonts and plug-ins /// ([`LiveInputs`]) are as they were. #[test] @@ -1274,19 +1328,32 @@ fn a_kept_evaluation_is_stale_after_the_live_inputs_change() { } /// An evaluation of `n` in `d`, with inputs 7, holding no symbols, patterns or art. -fn kept_evaluation(d: &Document, n: &Node) -> EvaluatedLive { - EvaluatedLive { +fn kept_evaluation(d: &Document, n: &Node) -> Evaluated> { + Evaluated { node: n.clone(), symbols: vec![], patterns: vec![], swatches: d.swatches.clone(), swatch_groups: d.swatch_groups.clone(), + unknown: d.unknown.clone(), inputs: 7, art: std::rc::Rc::new(vec![]), size: 0, } } +/// A kept evaluation is stale once a symbol's 9-slice guides or natural size change: they place +/// the symbol's art, and the document keeps them apart from the symbols. +#[test] +fn a_kept_evaluation_is_stale_after_a_symbols_placement_changes() { + let mut d = Document::new(100.0, 100.0); + let n = Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art()); + let e = kept_evaluation(&d, &n); + assert!(e.is_of(&d, &n, 7)); + d.unknown.insert(crate::SYMBOL_SIZES.into(), serde_json::json!({"Logo": [40.0, 20.0]})); + assert!(!e.is_of(&d, &n, 7)); +} + /// A kept evaluation is stale once a swatch changes, in a color group too: a painted live effect's /// pieces name swatches. #[test] @@ -1823,6 +1890,216 @@ fn objects_at_matches_repeated_hits_on_random_documents() { } } +/// [`objects_at_repeated_after`] with each found object looked up in the ordered list itself: the +/// reference the tests below hold the set lookup to, and the base that `select_behind_isolation_timing` times. +fn objects_at_repeated_after_by_list(doc: &Document, p: Point, opt: HitOptions, scope: Option, mut tops: Vec) -> Vec { + while let Some(top) = hit_test_skipping(doc, p, opt, &|id| tops.contains(&id), true).map(|h| h.top_object(scope)) { + if tops.contains(&top) { + break; + } + tops.push(top); + } + tops +} + +/// A layer holding a group of `count` overlapping 50 × 50 squares, member `i` at x = 5 × (`i` mod +/// 10), with a square at x = 0 below the group and above it, and one at x = 100 above it: the +/// document, the group and its members, topmost first. +fn isolated_stack(count: u32) -> (Document, NodeId, Vec) { + let mut d = Document::new(200.0, 200.0); + let l = d.layers[0].id; + let square = |d: &mut Document, x: f64| Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, 0.0, x + 50.0, 50.0)), Appearance::default_art()); + let below = square(&mut d, 0.0); + d.insert(Some(l), usize::MAX, below).unwrap(); + let members: Vec = (0..count).map(|i| square(&mut d, f64::from(i % 10) * 5.0)).collect(); + let mut ids: Vec = members.iter().map(|n| n.id).collect(); + let g = d.alloc_id(); + d.insert(Some(l), usize::MAX, Node::group(g, members.into_iter().map(Arc::new).collect())).unwrap(); + for x in [0.0, 100.0] { + let above = square(&mut d, x); + d.insert(Some(l), usize::MAX, above).unwrap(); + } + ids.reverse(); + (d, g, ids) +} + +/// Select Behind in an isolated group of 40 overlapping squares, with art around the group above +/// and below them: each member once, front to back, over 41 rounds of hit tests, and nothing where +/// only the art around the group lies. +#[test] +fn select_behind_in_isolation_lists_a_large_stack_once() { + let (d, g, ids) = isolated_stack(40); + let at = |x: f64, scope| objects_at(&d, Point::new(x, 25.0), HitOptions::default(), scope); + assert_eq!(at(47.5, Some(g)), ids); + assert_eq!(at(47.5, Some(g)).iter().collect::>().len(), 40, "no object twice"); + assert_eq!(at(47.5, None).len(), 3, "not isolated: the square above, the group and the square below"); + // At x = 17.5 only the members at x = 0 to 20 are hit (the one at 20 on its stroke, within + // the tolerance): `ids[k]` is member 39 - k. + let left: Vec = ids.iter().enumerate().filter(|(k, _)| (39 - k) % 10 <= 4).map(|(_, id)| *id).collect(); + assert_eq!(left.len(), 20); + assert_eq!(at(17.5, Some(g)), left); + assert!(at(125.0, Some(g)).is_empty(), "only the square around the group"); + assert_eq!(at(125.0, None).len(), 1); + let isolated = HitOptions { scope: Some(g), ..HitOptions::default() }; + let p = Point::new(47.5, 25.0); + assert_eq!(objects_at_repeated_after(&d, p, isolated, Some(g), ids[..15].to_vec()), ids, "the objects passed in stay first"); + let (d, g, clip, art) = masked_square(false); + let isolated = HitOptions { scope: Some(g), ..SELECTING }; + for p in [Point::new(140.0, 90.0), Point::new(170.0, 90.0), Point::new(100.0, 90.0)] { + let want = objects_at_repeated_after_by_list(&d, p, isolated, Some(g), vec![]); + assert_eq!(objects_at(&d, p, SELECTING, Some(g)), want, "clip group isolated, {p:?}"); + } + assert_eq!(objects_at(&d, Point::new(170.0, 90.0), SELECTING, Some(g)), vec![art], "the art its mask hides"); + assert!(objects_at(&d, Point::new(140.0, 90.0), SELECTING, Some(g)).contains(&clip), "the mask on its outline"); +} + +/// Documents built at random (nested groups, clipping groups, envelopes in Edit Contents, hidden +/// and locked objects), each object in turn isolated, and each list started with some of the +/// objects already found: the set lookup returns what the ordered-list lookup returns, field for +/// field. +#[test] +fn select_behind_in_isolation_matches_the_list_lookup_on_random_documents() { + let mut seed = 0x2545_f491_u32; + let mut next = move |n: u32| { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + seed % n + }; + fn fill(d: &mut Document, parent: NodeId, depth: u32, next: &mut impl FnMut(u32) -> u32) { + for _ in 0..2 + next(5) { + let id = d.alloc_id(); + let rect = |next: &mut dyn FnMut(u32) -> u32| { + let (x, y) = (f64::from(next(60)), f64::from(next(60))); + Rect::new(x, y, x + 10.0 + f64::from(next(50)), y + 10.0 + f64::from(next(50))) + }; + let mut n = match next(if depth < 3 { 9 } else { 4 }) { + 4 | 5 => Node::group(id, Vec::new()), + 6 => { + let mut g = Node::group(id, Vec::new()); + g.set_clips(true); + g + } + 7 => { + let content = + (0..2).map(|_| Arc::new(Node::path(d.alloc_id(), shapes::rectangle(rect(next)), Appearance::default_art()))).collect(); + Node::new( + id, + NodeKind::Envelope { + content, + kind: Box::new(crate::live::EnvelopeKind::Warp { + style: "arc".to_string(), + bend: 0.0, + h: 0.0, + v: 0.0, + horizontal: true, + version: 0, + }), + fidelity: 100.0, + editing: next(2) == 0, + options: Default::default(), + frame: Box::new(vectorcraft_geom::Affine::IDENTITY), + }, + ) + } + _ => Node::path(id, shapes::rectangle(rect(next)), if next(4) == 0 { Appearance::default() } else { Appearance::default_art() }), + }; + n.visible = next(8) != 0; + n.locked = next(8) == 0; + let group = matches!(n.kind, NodeKind::Group { .. }); + d.insert(Some(parent), usize::MAX, n).unwrap(); + if group { + fill(d, id, depth + 1, next); + } + } + } + let mut compared = 0; + for round in 0..60 { + let mut d = Document::new(120.0, 120.0); + let layer = d.layers[0].id; + fill(&mut d, layer, 0, &mut next); + let mut scopes = vec![None]; + d.walk(|n| { + if n.id != layer { + scopes.push(Some(n.id)); + } + }); + for _ in 0..6 { + let p = Point::new(f64::from(next(120)), f64::from(next(120))); + let opt = HitOptions { outline: next(5) == 0, path_only: next(5) == 0, clip_outlines: next(2) == 0, ..Default::default() }; + for &scope in &scopes { + let opt = HitOptions { scope, ..opt }; + let want = objects_at_repeated_after_by_list(&d, p, opt, scope, vec![]); + let context = format!("round {round}, {p:?}, {opt:?}"); + assert_eq!(objects_at_repeated_after(&d, p, opt, scope, vec![]), want, "{context}"); + if scope.is_some() { + assert_eq!(objects_at(&d, p, opt, scope), want, "{context}"); + } + for found in 1..want.len() { + let start = want[..found].to_vec(); + assert_eq!(objects_at_repeated_after(&d, p, opt, scope, start.clone()), want, "{context}, {found} found"); + assert_eq!(objects_at_repeated_after_by_list(&d, p, opt, scope, start), want, "{context}, {found} found"); + } + compared += usize::from(!want.is_empty()); + } + } + } + assert!(compared > 500, "only {compared} non-empty lists compared"); +} + +/// Times Select Behind in an isolated group of 200 and of 1,000 overlapping squares, the set lookup +/// against the ordered-list lookup, alternating the two in one process: +/// `cargo test --release -p vectorcraft-doc --lib -- --ignored --nocapture select_behind_isolation_timing`. +#[test] +#[ignore = "a timing, not a check"] +fn select_behind_isolation_timing() { + /// This thread's CPU time in nanoseconds on Linux; the elapsed time since `start` elsewhere. + fn clock(start: std::time::Instant) -> u128 { + let cpu = std::fs::read_to_string("/proc/thread-self/schedstat").ok(); + cpu.and_then(|s| s.split_whitespace().next()?.parse().ok()).unwrap_or_else(|| start.elapsed().as_nanos()) + } + type Lookup = fn(&Document, Point, HitOptions, Option, Vec) -> Vec; + let start = std::time::Instant::now(); + println!("clock: {}", if std::fs::metadata("/proc/thread-self/schedstat").is_ok() { "thread CPU time" } else { "wall clock" }); + let p = Point::new(47.5, 25.0); + for count in [200, 1_000] { + let (d, g, ids) = isolated_stack(count); + let opt = HitOptions { scope: Some(g), ..HitOptions::default() }; + assert_eq!(objects_at_repeated_after(&d, p, opt, Some(g), vec![]), ids); + assert_eq!(objects_at_repeated_after_by_list(&d, p, opt, Some(g), vec![]), ids); + // The time per call of `f`: batches of calls double until one takes at least 100 ms. + let per_call = |f: Lookup| { + let mut calls = 1u32; + loop { + let t = clock(start); + for _ in 0..calls { + std::hint::black_box(f(&d, std::hint::black_box(p), opt, Some(g), vec![])); + } + let spent = clock(start) - t; + if spent >= 100_000_000 || calls >= 1 << 20 { + return (spent as f64 / f64::from(calls), calls); + } + calls *= 2; + } + }; + let (mut old, mut new) = (vec![], vec![]); + for _ in 0..7 { + old.push(per_call(objects_at_repeated_after_by_list)); + new.push(per_call(objects_at_repeated_after)); + } + old.sort_by(|a, b| a.0.total_cmp(&b.0)); + new.sort_by(|a, b| a.0.total_cmp(&b.0)); + let (o, n) = (old[3], new[3]); + println!( + "{count} objects: list lookup {:.2} ms per call ({} calls), set lookup {:.2} ms per call ({} calls), median of 7 runs", + o.0 / 1e6, + o.1, + n.0 / 1e6, + n.1 + ); + } +} + /// Select Behind finds a symbol instance by its symbol's art, as a click does: art from /// (100, 60) to (140, 80), outside the 20 × 20 square around the origin, drawn where it lies by /// one instance and 100 pt lower by an instance in a group. diff --git a/crates/doc/src/id_index.rs b/crates/doc/src/id_index.rs index ed89f6ead4..149a8e488b 100644 --- a/crates/doc/src/id_index.rs +++ b/crates/doc/src/id_index.rs @@ -82,6 +82,16 @@ impl Paths { pub(crate) fn len(&self) -> usize { self.ids.len() } + /// The entry of `id` in the table: `Some(None)` when the id appears more than once, `None` + /// when it isn't in the table. + pub(crate) fn entry(&self, id: &NodeId) -> Option> { + self.ids.get(id).copied() + } + /// Entry `e`'s parent entry (`u32::MAX` for a top-level layer) and its index among its + /// siblings. + pub(crate) fn place(&self, e: u32) -> Option<(u32, u32)> { + self.at.get(e as usize).copied() + } } /// Lookups that had to walk (the cache didn't have the id, or its path no longer checks out) @@ -108,6 +118,22 @@ pub(crate) fn note_tree_walk() { TREE_WALKS.set(TREE_WALKS.get().saturating_add(1)); } +thread_local! { + /// [`path_lookups`] of this thread. + static PATH_LOOKUPS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// How many times [`crate::Document::index_path`] has run on this thread, the lookups that +/// [`crate::Document::node`] and [`crate::Document::ancestry`] make through it included. +pub fn path_lookups() -> u64 { + PATH_LOOKUPS.get() +} + +/// Adds one to [`path_lookups`]. +pub(crate) fn note_path_lookup() { + PATH_LOOKUPS.set(PATH_LOOKUPS.get().saturating_add(1)); +} + /// The cache, shared by clones of a document (each checks every path it uses against its own tree). #[derive(Default)] pub struct IdIndex(RwLock>>, std::sync::atomic::AtomicU32); diff --git a/crates/doc/src/inline.rs b/crates/doc/src/inline.rs index 86c26e14f4..b22f6cbfc7 100644 --- a/crates/doc/src/inline.rs +++ b/crates/doc/src/inline.rs @@ -117,6 +117,29 @@ impl Document { /// symbol that shows itself inline ([`Self::inline_art_bounds`]) is shown as an empty slot. /// Returns the ids of the texts in the layers that changed. pub fn resolve_inline_art_with(&mut self, layout: &mut dyn FnMut(&mut TextObject)) -> Vec { + self.resolve_inline_art_since(None, layout).changed + } + + /// [`Self::resolve_inline_art_with`], given `last`: a document an earlier pass left resolved, + /// with the bounds that pass measured ([`InlinePass::measured`]). When this document has the + /// same symbols, graph designs, pattern tiles and foreign data (`unknown`, which holds the + /// symbols' natural sizes and 9-slice guides) as `last`, and each symbol name measured then + /// still measures the same, the type in the layer trees that are the same nodes as `last`'s + /// already has these bounds: only the other layer trees are checked, in the same order, and + /// the document and the ids returned are those of the full pass. Otherwise, or without `last`, + /// the full pass runs. + pub fn resolve_inline_art_since(&mut self, last: Option<(&Document, &InlineMeasured)>, layout: &mut dyn FnMut(&mut TextObject)) -> InlinePass { + if let Some((last, kept)) = last + && self.same_inline_inputs(last, kept) + { + let measured = Measured(RefCell::new(kept.0.clone())); + let mut changed = vec![]; + let layers = resolve_kids(Some(&last.layers), &self.layers, &|n| measured.get(n, || self.inline_art_bounds(n)), layout, &mut changed); + for (i, layer) in layers { + self.layers[i] = layer; + } + return InlinePass { changed, measured: InlineMeasured(measured.0.into_inner()), partial: true }; + } let mut out = vec![]; let mut unused = vec![]; let graph = InlineGraph::of(self); @@ -147,10 +170,44 @@ impl Document { } } } - out + InlinePass { changed: out, measured: InlineMeasured(measured.0.into_inner()), partial: false } + } + + /// Whether the type in this document's layer trees that are the same nodes as `last`'s already + /// has the bounds a full pass would give it (see [`Self::resolve_inline_art_since`]). + fn same_inline_inputs(&self, last: &Document, kept: &InlineMeasured) -> bool { + self.symbols.len() == last.symbols.len() + && self.symbols.iter().zip(&last.symbols).all(|(a, b)| a.name == b.name && Arc::ptr_eq(&a.art, &b.art)) + && self.graph_designs.len() == last.graph_designs.len() + && self.graph_designs.iter().zip(&last.graph_designs).all(|(a, b)| a.name == b.name && Arc::ptr_eq(&a.art, &b.art)) + && self.patterns.len() == last.patterns.len() + && self + .patterns + .iter() + .zip(&last.patterns) + .all(|(a, b)| a.name == b.name && a.art.len() == b.art.len() && a.art.iter().zip(&b.art).all(|(x, y)| Arc::ptr_eq(x, y))) + && crate::Shared::ptr_eq(&self.unknown, &last.unknown) + && kept.0.iter().all(|(name, b)| self.inline_art_bounds(name) == *b) } } +/// What a pass of [`Document::resolve_inline_art_since`] did. +#[derive(Debug)] +pub struct InlinePass { + /// The ids of the texts in the layers that changed, in the order the full pass finds them. + pub changed: Vec, + /// The bounds the pass gave the inline graphics of each symbol name, for the next pass. + pub measured: InlineMeasured, + /// Whether only the layer trees that differ from the last resolved document's were checked. + pub partial: bool, +} + +/// The art bounds a pass of [`Document::resolve_inline_art_since`] gave the inline graphics of each +/// symbol name it was asked for. A pass that checks only some layer trees keeps the names the +/// pass before it measured, so the names of all the type in the document stay listed. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct InlineMeasured(HashMap>); + /// Whether `t` has inline graphics whose bounds differ from what `bounds` gives their symbols. fn stale_by(t: &TextObject, bounds: &dyn Fn(&str) -> Option) -> bool { t.runs.iter().filter_map(|r| r.inline.as_ref()).any(|a| a.bounds != bounds(&a.symbol)) @@ -185,6 +242,22 @@ fn resolve_tree( layout: &mut dyn FnMut(&mut TextObject), changed: &mut Vec, ) -> bool { + resolve_since(None, n, bounds, layout, changed) +} + +/// [`resolve_tree`], given `old`: the node `n` was before an edit, in a document whose type was +/// resolved with the same `bounds`. The opacity mask art and children of `n` that are the same +/// nodes as `old`'s are skipped: their type already has these bounds. Without `old`, every node +/// of the tree is visited. +fn resolve_since( + old: Option<&Node>, + n: &mut Arc, + bounds: &dyn Fn(&str) -> Option, + layout: &mut dyn FnMut(&mut TextObject), + changed: &mut Vec, +) -> bool { + #[cfg(test)] + tests::VISITS.with(|v| v.set(v.get() + 1)); let mut copied = false; if matches!(&n.kind, NodeKind::Text(t) if stale_by(t, bounds)) { let node = Arc::make_mut(n); @@ -196,17 +269,17 @@ fn resolve_tree( } copied = true; } + let old_mask = old.and_then(|o| o.extras().mask.as_deref()).map(|m| &m.art); let mask = n.extras().mask.as_deref().and_then(|m| { - let mut art = m.art.clone(); - resolve_tree(&mut art, bounds, layout, changed).then_some(art) - }); - let mut kids = vec![]; - for (i, c) in n.children().into_iter().flatten().enumerate() { - let mut c = c.clone(); - if resolve_tree(&mut c, bounds, layout, changed) { - kids.push((i, c)); + if old_mask.is_some_and(|o| Arc::ptr_eq(o, &m.art)) { + return None; } - } + let mut art = m.art.clone(); + let old_art = old_mask.filter(|o| o.id == art.id).map(|o| &**o); + resolve_since(old_art, &mut art, bounds, layout, changed).then_some(art) + }); + let old_kids = old.map(|o| o.children().map_or(&[][..], Vec::as_slice)); + let kids = resolve_kids(old_kids, n.children().map_or(&[][..], Vec::as_slice), bounds, layout, changed); if mask.is_none() && kids.is_empty() { return copied; } @@ -224,6 +297,35 @@ fn resolve_tree( true } +/// Resolves the trees `kids` as [`resolve_since`] does, each with the node of `old` (the same list +/// before an edit) that has its id, found at the same position or else by id, and skips those that +/// are the same nodes as theirs. Without `old`, every tree is visited. Returns the position and new +/// node of each tree that changed. +fn resolve_kids( + old: Option<&[Arc]>, + kids: &[Arc], + bounds: &dyn Fn(&str) -> Option, + layout: &mut dyn FnMut(&mut TextObject), + changed: &mut Vec, +) -> Vec<(usize, Arc)> { + let mut by_id: Option>> = None; + let mut out = vec![]; + for (i, c) in kids.iter().enumerate() { + let o = old.and_then(|old| match old.get(i) { + Some(b) if b.id == c.id => Some(b), + _ => by_id.get_or_insert_with(|| old.iter().map(|b| (b.id, b)).collect()).get(&c.id).copied(), + }); + if o.is_some_and(|o| Arc::ptr_eq(o, c)) { + continue; + } + let mut c = c.clone(); + if resolve_since(o.map(|o| &**o), &mut c, bounds, layout, changed) { + out.push((i, c)); + } + } + out +} + /// The art bounds of each symbol, measured once in a pass of [`Document::resolve_inline_art_with`]. /// A symbol is first asked for after its own type is resolved (the pass goes in /// [`InlineGraph::order`]), so its measurement stays current for the rest of the pass. @@ -436,6 +538,112 @@ impl std::fmt::Debug for InlineCycles { mod tests { use super::*; + thread_local! { + /// How many nodes [`resolve_since`] has visited on this thread. + pub(super) static VISITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + } + + /// The nodes visited since the last call. + fn visits() -> usize { + VISITS.with(|v| v.replace(0)) + } + + /// A copy of `d` resolved by the full pass, and the ids that pass returns. + fn fully_resolved(d: &Document) -> (Document, Vec) { + let mut full = d.clone(); + let ids = full.resolve_inline_art_with(&mut |_| {}); + (full, ids) + } + + /// The children of the layer at `i`, for an edit. + fn layer_kids(d: &mut Document, i: usize) -> &mut Vec> { + match Arc::make_mut(&mut d.layers[i]).children_mut() { + Some(kids) => kids, + None => panic!("layer {i} is a group"), + } + } + + /// 50 groups of 20 squares, symbol `S`, type showing `S` in the first group, and type showing + /// `S` in the opacity mask of the second. + fn many_groups() -> Document { + let mut d = Document::new(500.0, 500.0); + let square = stroked(&mut d, Rect::new(0.0, 0.0, 10.0, 10.0)); + symbol(&mut d, "S", vec![square]); + for _ in 0..50 { + let kids = (0..20).map(|_| stroked(&mut d, Rect::new(0.0, 0.0, 5.0, 5.0))).collect(); + let group = Node::group(d.alloc_id(), kids); + d.layers.push(Arc::new(group)); + } + let t = showing(&mut d, "S"); + layer_kids(&mut d, 0).push(t); + let masked = showing(&mut d, "S"); + Arc::make_mut(&mut d.layers[1]).extras_mut().mask = Some(Box::new(crate::OpacityMask::new((*masked).clone(), true))); + d + } + + #[test] + fn a_pass_after_an_edit_checks_only_the_trees_the_edit_changed() { + let mut d = many_groups(); + let first = d.resolve_inline_art_since(None, &mut |_| {}); + assert!(!first.partial); + assert_eq!(first.changed.len(), 2); + let last = d.clone(); + visits(); + let _ = fully_resolved(&d); + let full_visits = visits(); + // The edit moves a square in the 31st group, adds type showing S to the 41st, and gives the + // second group's opacity mask new type: its 20 squares stay the same nodes. + let moved = stroked(&mut d, Rect::new(1.0, 1.0, 6.0, 6.0)); + layer_kids(&mut d, 30)[5] = moved; + let added = showing(&mut d, "S"); + layer_kids(&mut d, 40).push(added.clone()); + let mask_type = showing(&mut d, "S"); + if let Some(m) = Arc::make_mut(&mut d.layers[1]).extras_if_any().and_then(|e| e.mask.as_deref_mut()) { + m.art = mask_type.clone(); + } + let (want, ids) = fully_resolved(&d); + assert_eq!(ids, [mask_type.id, added.id]); + visits(); + let pass = d.resolve_inline_art_since(Some((&last, &first.measured)), &mut |_| {}); + let partial_visits = visits(); + assert!(pass.partial); + assert_eq!(pass.changed, ids); + assert_eq!(d, want); + // The three changed groups, the mask's new type, the moved square and the added type. + assert_eq!(partial_visits, 6); + assert!(full_visits > 1000, "{full_visits}"); + assert_eq!(pass.measured, first.measured); + } + + #[test] + fn changed_symbols_or_symbol_sizes_take_the_full_pass() { + let mut d = many_groups(); + let mut pass = d.resolve_inline_art_since(None, &mut |_| {}); + // A natural size for S, its art unchanged. + let last = d.clone(); + d.unknown.insert(SYMBOL_SIZES.into(), serde_json::json!({ "S": [40.0, 20.0] })); + let (want, ids) = fully_resolved(&d); + assert_eq!(ids.len(), 2); + pass = d.resolve_inline_art_since(Some((&last, &pass.measured)), &mut |_| {}); + assert!(!pass.partial); + assert_eq!((&d, &pass.changed), (&want, &ids)); + // New art for S. + let last = d.clone(); + let bigger = stroked(&mut d, Rect::new(0.0, 0.0, 30.0, 30.0)); + d.symbols[0].art = Arc::new(Node::group(d.alloc_id(), vec![bigger])); + let (want, ids) = fully_resolved(&d); + assert_eq!(ids.len(), 2); + pass = d.resolve_inline_art_since(Some((&last, &pass.measured)), &mut |_| {}); + assert!(!pass.partial); + assert_eq!((&d, &pass.changed), (&want, &ids)); + // A measurement that no longer holds, with the same symbols and foreign data. + let last = d.clone(); + let stale = InlineMeasured(HashMap::from([("S".to_owned(), Some(Rect::new(0.0, 0.0, 1.0, 1.0)))])); + pass = d.resolve_inline_art_since(Some((&last, &stale)), &mut |_| {}); + assert!(!pass.partial); + assert!(pass.changed.is_empty()); + } + /// The position of each node in `order`. fn positions(order: &[usize]) -> Vec { let mut at = vec![0; order.len()]; diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 7f26dc9a50..123e31bc08 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -21,7 +21,7 @@ pub mod graph; mod halftone_radii; pub mod hit; mod id_index; -pub use id_index::tree_walks; +pub use id_index::{path_lookups, tree_walks}; pub mod inks; mod inline; pub mod intertwine; @@ -31,7 +31,7 @@ mod symbol_nine_slice; pub mod symbol_overrides; mod symbol_pixel_aligned; mod symbol_registration; -pub use inline::{SYMBOL_HALF, SYMBOL_SIZES}; +pub use inline::{InlineMeasured, InlinePass, SYMBOL_HALF, SYMBOL_SIZES}; pub use shared::Shared; pub use symbol_export_type::{SYMBOL_EXPORT_TYPE, SymbolExportType}; pub use symbol_nine_slice::{ @@ -48,6 +48,8 @@ pub mod marks; mod mem; pub use mem::{appearance_heap_bytes, paint_heap_bytes}; pub mod metadata; +mod nearest; +pub use nearest::NearestFinder; pub mod node; pub mod objects_on_path; pub mod orient; @@ -168,7 +170,7 @@ use limits::MAX_NEXT_ID; pub use limits::{DocError, FORMAT_VERSION, MAX_COORD}; pub use records::{ImageBlob, MaskEdit, NewArtIds, SavedSelection, SavedView, SvgFilter, Symbol, SymbolEdit}; pub use stored_art::{StoredPlace, StoredRoot}; -pub use units::{ColorMode, Unit, parse_number}; +pub use units::{ColorMode, Unit, decimal_point, finite_in_every_unit, parse_number}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Document { diff --git a/crates/doc/src/live.rs b/crates/doc/src/live.rs index 28fd1dc632..337634db2e 100644 --- a/crates/doc/src/live.rs +++ b/crates/doc/src/live.rs @@ -66,7 +66,8 @@ pub use expand::{ use mesh::grid_eval; pub use mesh::{Coons, GradientMesh, MeshAppearance, MeshPiece, MeshPoint, MeshQuad, default_fidelity, grid_points, nodes_bounds}; pub use warp::{ - WARP_NET, WarpNet, WarpStyle, fit_piece, map_nonlinear, map_nonlinear_within, map_smooth_within, pieces, uses_net, warp_point, warp_version, + WARP_NET, WarpNet, WarpStyle, fit_piece, map_handles_within, map_nonlinear, map_nonlinear_within, map_smooth_within, pieces, uses_net, + warp_point, warp_version, }; #[cfg(test)] diff --git a/crates/doc/src/live/warp.rs b/crates/doc/src/live/warp.rs index dd48e8ef65..a921c7d2ff 100644 --- a/crates/doc/src/live/warp.rs +++ b/crates/doc/src/live/warp.rs @@ -508,6 +508,17 @@ pub fn map_smooth_within(path: &PathData, max_piece: f64, max: usize, f: impl Fn map_pieces_within(path, max_piece, max, &f, |p, h| mapped_handle(&f, p, h)) } +/// [`map_nonlinear_within`] with `handle(point, handle)` supplying each mapped handle position. +pub fn map_handles_within( + path: &PathData, + max_piece: f64, + max: usize, + f: impl Fn(Point) -> Point, + handle: impl Fn(Point, Point) -> Point, +) -> PathData { + map_pieces_within(path, max_piece, max, &f, handle) +} + /// Handle `h` of point `p` mapped through `f`: `f(p)` plus `f`'s derivative at `p` along `h - p` /// (a central difference), so the image curve leaves `f(p)` the way `f` takes the curve. fn mapped_handle(f: &impl Fn(Point) -> Point, p: Point, h: Point) -> Point { @@ -553,7 +564,8 @@ fn map_pieces_within(path: &PathData, max_piece: f64, max: usize, f: &impl Fn(Po let c = seg_cubic(sp, i); let k = pieces(poly_len(&c), max_piece, MAX_PIECES); for j in 0..k { - let sub = c.subsegment((j as f64 / k as f64)..((j + 1) as f64 / k as f64)); + // Evaluating an unchanged curve can overflow even when its control points are finite. + let sub = if k == 1 { c } else { c.subsegment((j as f64 / k as f64)..((j + 1) as f64 / k as f64)) }; if let Some(last) = res.last_mut() { last.h_out = handle(sub.p0, sub.p1); } @@ -613,3 +625,53 @@ pub(super) fn resample(poly: &[Point], m: usize) -> Vec { } out } + +#[cfg(test)] +mod handle_tests { + use super::*; + + #[test] + fn an_unsplit_curve_keeps_its_finite_control_points() { + let start = Point::new(1e308, 0.0); + let end = Point::new(1.03e308, 0.0); + let path = PathData::new(vec![SubPath::new( + vec![Anchor::with_handles(start, start, Point::new(1.01e308, 1.0)), Anchor::with_handles(end, Point::new(1.02e308, 1.0), end)], + false, + )]); + assert_eq!(map_handles_within(&path, 1.0, 2, |p| p, |_, h| h), path); + } + + #[test] + fn rounded_samples_preserve_a_smooth_interior_join() { + let center = Point::new(1e16, 0.0); + let path = PathData::new(vec![SubPath::new( + vec![ + Anchor::corner(center + vectorcraft_geom::kurbo::Vec2::new(-18.0, 0.0)), + Anchor::with_handles( + center, + center + vectorcraft_geom::kurbo::Vec2::new(-6.0, 0.0), + center + vectorcraft_geom::kurbo::Vec2::new(6.0, 0.0), + ), + Anchor::corner(center + vectorcraft_geom::kurbo::Vec2::new(18.0, 0.0)), + ], + false, + )]); + let mapped = map_smooth_within(&path, f64::INFINITY, 3, |p| Point::new(p.x, p.y + (p.x - center.x).powi(2) * 0.1)); + let join = &mapped.subpaths[0].anchors[1]; + let incoming = join.p - join.h_in; + let outgoing = join.h_out - join.p; + assert!(incoming.cross(outgoing).abs() < 1e-9, "{incoming:?} {outgoing:?}"); + assert!(incoming.dot(outgoing) > 0.0); + } + + #[test] + fn a_midpoint_rounded_to_an_endpoint_keeps_the_handle_direction() { + for x in [1e16, 1e16 + 2.0, -1e16] { + for offset in [-6.0, -2.0, 2.0, 6.0] { + let p = Point::new(x, 0.0); + let h = Point::new(x + offset, 0.0); + assert_eq!(mapped_handle(&|point| point, p, h), h); + } + } + } +} diff --git a/crates/doc/src/nearest.rs b/crates/doc/src/nearest.rs new file mode 100644 index 0000000000..0adc6269f9 --- /dev/null +++ b/crates/doc/src/nearest.rs @@ -0,0 +1,90 @@ +//! The nearest node of a kind at or above each of many objects, found along one index path per +//! object. + +use std::sync::Arc; + +use crate::id_index::Paths; +use crate::{Document, Node, NodeId}; + +/// Finds, for one object after another, the nearest node that passes a test: the object itself, +/// then its parent, and so on up to its layer. Made by [`Document::nearest_finder`]. +/// +/// Each node on the way is tested as [`Document::node`] gives its id, so the answer is the one that +/// `doc.ancestry(id)` read from the end, with `doc.node` for each id, gives. While the lookup cache +/// places the object and each id on its path where they are, a lookup reads that one path; an id +/// the cache does not place there (one that appears more than once, or a cache older than the +/// tree) is looked up with [`Document::node`]. +pub struct NearestFinder<'a> { + doc: &'a Document, + cache: Option>, + /// The cache entries from the top-level layer down to the object. + entries: Vec, + /// The nodes at those entries. + nodes: Vec<&'a Node>, +} + +impl Document { + /// A [`NearestFinder`] for this document. + pub fn nearest_finder(&self) -> NearestFinder<'_> { + NearestFinder { doc: self, cache: self.index.get(), entries: vec![], nodes: vec![] } + } +} + +impl<'a> NearestFinder<'a> { + /// The node nearest `id` (itself, then its parent, and so on up to its layer) for which `pred` + /// holds; `None` when `id` is not in the tree or no node on its path passes. + pub fn nearest(&mut self, id: NodeId, mut pred: impl FnMut(&Node) -> bool) -> Option<&'a Node> { + let doc = self.doc; + let ids: Vec = if self.cached_path(id) { + let cache = self.cache.as_deref()?; + // The depth of the first id from the object up that the cache does not place there. + let mut unplaced = None; + for (k, (&node, &e)) in self.nodes.iter().zip(&self.entries).enumerate().rev() { + if cache.entry(&node.id) != Some(Some(e)) { + unplaced = Some(k); + break; + } + if pred(node) { + return Some(node); + } + } + let k = unplaced?; + self.nodes[..=k].iter().map(|n| n.id).collect() + } else { + doc.ancestry(id).unwrap_or_default() + }; + let found = ids.into_iter().rev().find_map(|a| doc.node(a).filter(|n| pred(n))); + // Those lookups may have built the cache again. + self.cache = doc.index.get(); + found + } + + /// Fill `entries` and `nodes` with the cached path to `id`; false when the cache has no path for + /// it or the path no longer leads to it. + fn cached_path(&mut self, id: NodeId) -> bool { + self.entries.clear(); + self.nodes.clear(); + let Some(cache) = self.cache.as_deref() else { return false }; + let Some(Some(mut e)) = cache.entry(&id) else { return false }; + loop { + let Some((parent, _)) = cache.place(e) else { return false }; + self.entries.push(e); + if parent == u32::MAX { + break; + } + // A parent's entry is made before its children's, so the walk up ends. + if parent >= e { + return false; + } + e = parent; + } + self.entries.reverse(); + let mut siblings: &'a [Arc] = &self.doc.layers; + for &e in &self.entries { + let Some(n) = cache.place(e).and_then(|(_, i)| siblings.get(i as usize)) else { return false }; + self.nodes.push(&**n); + siblings = n.children().map_or(&[], |c| c.as_slice()); + } + self.nodes.last().is_some_and(|n| n.id == id) + } +} diff --git a/crates/doc/src/node/live_shape.rs b/crates/doc/src/node/live_shape.rs index 9ddc4e1bb6..a384836442 100644 --- a/crates/doc/src/node/live_shape.rs +++ b/crates/doc/src/node/live_shape.rs @@ -179,6 +179,48 @@ impl LiveShape { *xf = Affine::rotate_about((now - angle).to_radians(), centre) * *xf; } } + /// A line's length in the document, from its first end to its second. None for other shapes. + pub fn line_length(&self) -> Option { + let LiveShape::Line { a, b } = self else { return None }; + Some((*b - *a).hypot()) + } + /// A line's angle: the counterclockwise degrees in [0, 360) from the page's horizontal to the + /// direction from its first end to its second (the Rotate field's sense). 0 for a line whose + /// ends meet. None for other shapes. + pub fn line_angle(&self) -> Option { + let LiveShape::Line { a, b } = self else { return None }; + if a == b { + return Some(0.0); + } + // No −0° or 360° from rounding: a line drawn left to right reads 0°. + let a = (-self.angle_deg()).rem_euclid(360.0); + Some(if a > 360.0 - 1e-9 { 0.0 } else { a + 0.0 }) + } + /// Make a line `len` long (0 or more), keeping its first end in place and its direction, or + /// pointing it to the right when its ends meet. + pub fn set_line_length(&mut self, len: f64) { + let LiveShape::Line { a, b } = self else { return }; + if !len.is_finite() || len < 0.0 { + return; + } + let now = (*b - *a).hypot(); + *b = if now > 0.0 { *a + (*b - *a) * (len / now) } else { Point::new(a.x + len, a.y) }; + } + /// Turn a line about its midpoint to `angle` (degrees, as [`LiveShape::line_angle`]). A line + /// whose ends meet stays as it is. + pub fn set_line_angle(&mut self, angle: f64) { + let LiveShape::Line { a, b } = self else { return }; + let half = (*b - *a).hypot() / 2.0; + if !angle.is_finite() || half <= 0.0 { + return; + } + let mid = a.midpoint(*b); + let t = angle.to_radians(); + // The page's y axis points down, so a counterclockwise angle goes up the page. + let (dx, dy) = (half * t.cos(), -half * t.sin()); + *a = Point::new(mid.x - dx, mid.y - dy); + *b = Point::new(mid.x + dx, mid.y + dy); + } /// Make a polygon's sides equal (Make Sides Equal): drop the uneven scale and the shear from /// `xf`, keeping its centre, angle, reflection and [`LiveShape::polygon_radius`]. pub fn make_sides_equal(&mut self) { diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index a616080bce..42978c81b0 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -216,8 +216,10 @@ impl Node { /// 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 - /// takes in where its spine can put its keys and steps. + /// own strokes. Symbol instances are measured as in [`Node::visual_bounds`], taking in the + /// shapes their art paints with the geometry effects of their own fill or stroke + /// ([`crate::hit::set_image_paint`]). A blend's box takes in where its spine can put its keys + /// and steps. pub fn reach_bounds(&self) -> Option { self.reach(None) } @@ -254,14 +256,8 @@ impl Node { .map(|b| b.inflate(o, o)) } NodeKind::Intertwine { children } => children.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.reach(symbols))), - // The frame and each shape the image's own fills and strokes paint, a stroke's grown by - // the farthest it can reach from its shape. - NodeKind::Image(_) => { - crate::hit::image_paint(symbols.map(SymbolBoxes::document), self).iter().fold(self.geometric(symbols), |acc, (bp, _, item)| { - let o = if let crate::AppearanceItem::Stroke(s) = item { s.reach() } else { 0.0 }; - vectorcraft_geom::union_opt(acc, (!bp.elements().is_empty()).then(|| bp.bounding_box().inflate(o, o))) - }) - } + // The frame and each shape the image's own fills and strokes paint. + NodeKind::Image(_) => self.with_own_paint(self.geometric(symbols), symbols), // Keys and steps placed on a spine, turned to it with Align to Path, can reach past the // keys and the spine. NodeKind::Blend { children, spec } => { @@ -272,13 +268,15 @@ impl Node { 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))) } - // The live geometry effects of the clipping paths in the art can draw it past its box. + // The live geometry effects of the clipping paths in the art can draw it past its box, + // and the box takes in each shape the art paints with the geometry effects of the + // instance's own fill or stroke. NodeKind::SymbolInstance { symbol, xf } => { let Some((s, art, region)) = symbols.and_then(|s| { let a = s.art(symbol)?; Some((s, a, a.reshaped?)) }) else { - return self.visual(symbols); + return self.with_own_paint(self.visual(symbols), symbols); }; let map = s.document().symbol_slice_map_of(symbol, art.geometric, *xf); let placed = if moves_only(*xf) && map.is_none() { @@ -294,12 +292,22 @@ impl Node { map.map_or_else(|| xf.transform_rect_bbox(all), |m| m.placement_bounds(all)).inflate(grow, grow) }; let o = self.appearance.outset(); - vectorcraft_geom::union_opt(self.visual(symbols), self.projected(Some(placed)).map(|b| b.inflate(o, o))) + self.with_own_paint(vectorcraft_geom::union_opt(self.visual(symbols), self.projected(Some(placed)).map(|b| b.inflate(o, o))), symbols) } _ => self.visual(symbols), } } + /// `start` grown by each shape the node's own fills and strokes paint + /// ([`crate::hit::set_image_paint`]), a stroke's grown by the farthest it can reach from its + /// shape. + fn with_own_paint(&self, start: Option, symbols: Option<&SymbolBoxes>) -> Option { + crate::hit::image_paint(symbols.map(SymbolBoxes::document), self).iter().fold(start, |acc, (bp, _, item)| { + let o = if let crate::AppearanceItem::Stroke(s) = item { s.reach() } else { 0.0 }; + vectorcraft_geom::union_opt(acc, (!bp.elements().is_empty()).then(|| bp.bounding_box().inflate(o, o))) + }) + } + /// Geometric bounds (no stroke), recursively. Clip groups are bounded by their clip path. A /// symbol instance is measured as its transform applied to the 20 × 20 square around the origin /// that symbols made in the app keep their art in ([`Node::geometric_bounds_with`] measures diff --git a/crates/doc/src/setup.rs b/crates/doc/src/setup.rs index 4dd8394ce2..e91542fe1a 100644 --- a/crates/doc/src/setup.rs +++ b/crates/doc/src/setup.rs @@ -220,6 +220,13 @@ pub fn language_quotes(language: &str) -> Option { LANGUAGES.iter().find(|(l, _, _)| l.eq_ignore_ascii_case(language)).map(|(_, _, q)| *q) } +/// The BCP 47 tag of the [`LANGUAGES`] entry named or tagged `language` (case-insensitive), the +/// default's included (`en-US`): what a document's language ([`DocSetup::language`]) is written +/// as in an exported file. `None` for a language not in the list. +pub fn language_tag(language: &str) -> Option<&'static str> { + LANGUAGES.iter().find(|(n, t, _)| n.eq_ignore_ascii_case(language) || t.eq_ignore_ascii_case(language)).map(|(_, t, _)| *t) +} + /// The [`LANGUAGES`] entry named or tagged `language` (case-insensitive) as a character's /// language ([`crate::CharStyle::language`]) stores it: its tag, or `None` for the default (the /// first entry); `Err` for a language not in the list. @@ -404,6 +411,16 @@ impl DocSetup { mod tests { use super::*; + /// A document's language is written by its tag, the default's included (#3644). + #[test] + fn document_languages_have_their_tags() { + assert_eq!(language_tag(&DocSetup::default().language), Some("en-US")); + assert_eq!(language_tag("French"), Some("fr")); + assert_eq!(language_tag("german: swiss"), Some("de-CH")); + assert_eq!(language_tag("sr-latn"), Some("sr-Latn")); + assert_eq!((language_tag("Klingon"), language_tag("")), (None, None)); + } + /// Characters store a language of the list by its tag, the default as none. #[test] fn char_languages_are_stored_by_tag() { diff --git a/crates/doc/src/swatches.rs b/crates/doc/src/swatches.rs index 9c25427846..0ee84dc32c 100644 --- a/crates/doc/src/swatches.rs +++ b/crates/doc/src/swatches.rs @@ -187,8 +187,9 @@ impl Document { /// [`Document::map_solid_paints`] limited to the art in the subtrees of `ids` (each paint /// visited once even when an id is inside another). pub fn map_solid_paints_in(&mut self, ids: &[NodeId], f: &mut LinkFn) -> usize { + let listed: HashSet = ids.iter().copied().collect(); let roots: Vec = - ids.iter().copied().filter(|id| !self.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| ids.contains(p)))).collect(); + ids.iter().copied().filter(|id| !self.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| listed.contains(p)))).collect(); let mut n = 0; let mut g = relink(f); for id in roots { @@ -844,6 +845,77 @@ mod tests { assert_eq!(colors, [(Color::rgb(1.0, 0.0, 0.0), None)]); } + /// [`Document::map_solid_paints_in`] with each ancestor searched for in `ids` rather than looked up in a set. + fn map_solid_paints_in_by_search(d: &mut Document, ids: &[NodeId], f: &mut LinkFn) -> usize { + let roots: Vec = + ids.iter().copied().filter(|id| !d.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| ids.contains(p)))).collect(); + let mut n = 0; + let mut g = relink(f); + for id in roots { + let Some(node) = d.node(id) else { continue }; + if let Some((new, count)) = map_node(node, &mut g) + && let Some(slot) = d.node_mut(id) + { + *slot = new; + n += count; + } + } + n + } + + #[test] + fn mapping_within_ids_matches_a_search_of_the_ids() { + // Two layers: the first holds group `outer` (group `inner` with two rectangles, and a + // rectangle) and a rectangle; the second holds a rectangle. Each rectangle has its own color. + let mut d = Document::new(100.0, 100.0); + let first = d.layers[0].id; + let second = d.alloc_id(); + d.insert(None, usize::MAX, Node::layer(second, "Second", crate::LayerColor::Preset(1))).unwrap(); + let rect = |d: &mut Document, i: u8| { + let id = d.alloc_id(); + let r = shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)); + let color = Color::rgb(f32::from(i) / 8.0, 0.0, 0.0); + (id, Arc::new(Node::path(id, r, Appearance::basic(Paint::solid(color), Paint::solid(color), 1.0)))) + }; + let (r1, n1) = rect(&mut d, 1); + let (r2, n2) = rect(&mut d, 2); + let (r3, n3) = rect(&mut d, 3); + let (r4, n4) = rect(&mut d, 4); + let (r5, n5) = rect(&mut d, 5); + let (inner, outer) = (d.alloc_id(), d.alloc_id()); + let outer_node = Node::group(outer, vec![Arc::new(Node::group(inner, vec![n1, n2])), n3]); + d.insert(Some(first), usize::MAX, outer_node).unwrap(); + d.insert(Some(first), usize::MAX, Arc::unwrap_or_clone(n4)).unwrap(); + d.insert(Some(second), usize::MAX, Arc::unwrap_or_clone(n5)).unwrap(); + let missing = NodeId(u64::MAX); + let all = [first, second, outer, inner, r1, r2, r3, r4, r5, missing]; + // Every list of up to three of them: nested ids in both orders, duplicates, a missing id and none. + let mut lists: Vec> = vec![vec![]]; + let mut shorter: Vec> = vec![vec![]]; + for _ in 0..3 { + shorter = shorter.iter().flat_map(|l| all.map(|id| [l.as_slice(), &[id]].concat())).collect(); + lists.extend(shorter.iter().cloned()); + } + assert_eq!(lists.len(), 1 + 10 + 100 + 1000); + for ids in &lists { + // A callback that changes every paint it visits, so a paint visited twice counts twice. + let run = |map: &dyn Fn(&mut Document, &[NodeId], &mut LinkFn) -> usize| { + let mut d = d.clone(); + let mut visits = vec![]; + let n = map(&mut d, ids, &mut |c, s, t| { + visits.push((*c, s.clone(), *t)); + *s = Some(format!("{}", visits.len())); + *t *= 0.5; + true + }); + (n, visits, d.layers) + }; + let by_set = run(&|d, ids, f| d.map_solid_paints_in(ids, f)); + let by_search = run(&|d, ids, f| map_solid_paints_in_by_search(d, ids, f)); + assert_eq!(by_set, by_search, "{ids:?}"); + } + } + /// The colors [`node_colors`] visits, in its order, by a [`Node::walk`] that reads the whole subtree. fn full_walk(n: &Node, f: &mut dyn FnMut(&Color, Option<&str>)) { n.walk(&mut |m| { diff --git a/crates/doc/src/tests/lookups.rs b/crates/doc/src/tests/lookups.rs index 2f83b65c5e..9c5c278a53 100644 --- a/crates/doc/src/tests/lookups.rs +++ b/crates/doc/src/tests/lookups.rs @@ -157,6 +157,58 @@ fn cached_lookups_follow_any_edit_of_the_tree() { } } +/// Every node whose id is in `ids`, by walking the tree. +fn every_node(d: &Document, ids: &[NodeId]) -> Vec<*const Node> { + let mut out = vec![]; + d.walk(|n| { + if ids.contains(&n.id) { + out.push(n as *const Node); + } + }); + out +} + +/// [`Document::nodes_in_order`] gives every node with each id in tree order, repeated ids +/// included, with the cache built and without it, for a few ids (cached paths) and for many (a +/// walk). +#[test] +fn nodes_in_order_match_a_walk() { + for seed in 1..40 { + let (d, ids) = tree(seed); + let few: Vec = ids.iter().copied().step_by(17).collect(); + for cold in [true, false] { + if cold { + d.drop_lookup_cache(); + } else { + d.node(ids[0]); + } + for list in [&ids[..], &few[..], &ids[ids.len() / 2..ids.len() / 2 + 1], &[]] { + let found: Vec<*const Node> = d.nodes_in_order(list.iter().copied()).into_iter().map(|n| n as *const Node).collect(); + assert_eq!(found, every_node(&d, list), "seed {seed}, cold {cold}, {list:?}"); + } + } + // An id that the tree repeats: every node with it. + let Some(dup) = ids.iter().enumerate().find(|(i, id)| ids[..*i].contains(id)).map(|(_, id)| *id) else { continue }; + assert!(d.nodes_in_order([dup]).len() >= 2, "seed {seed}: {dup:?} is in the tree more than once"); + // A second node given an id once held once, after the cache was built: the lookup finds the + // cached node, which has that id; with the cache built afresh, both. + let mut d = d; + let once = ids.iter().copied().find(|id| every_node(&d, &[*id]).len() == 1 && d.node(*id).is_some_and(|n| !n.is_layer())); + let Some(once) = once else { continue }; + d.node(once); + let copy = Arc::new(Node::path(once, shapes::rectangle(Rect::new(0.0, 0.0, 2.0, 2.0)), Appearance::default_art())); + if let Some(ch) = Arc::make_mut(&mut d.layers[0]).children_mut() { + ch.insert(0, copy); + } + let found = d.nodes_in_order([once]); + assert!(!found.is_empty() && found.iter().all(|n| n.id == once), "seed {seed}: {once:?}"); + d.drop_lookup_cache(); + d.node(once); + let found: Vec<*const Node> = d.nodes_in_order([once]).into_iter().map(|n| n as *const Node).collect(); + assert_eq!(found, every_node(&d, &[once]), "seed {seed}: {once:?} cached afresh"); + } +} + /// Nodes of `d` picked and ordered by `seed`. None lies inside another, and each of them, and each /// node it is in, appears in the tree once. fn picks(d: &Document, seed: u64) -> Vec { @@ -282,3 +334,112 @@ fn edits_of_many_refuse_missing_repeated_and_nested_ids() { assert_eq!(serde_json::to_string(&b).ok(), saved, "{what}: the document stays as it was"); } } + +/// The nearest node passing `pred` at or above `id`, as `ancestry` read from the end with `node` +/// for each id finds it. +fn nearest_by_ancestry(d: &Document, id: NodeId, pred: impl Fn(&Node) -> bool) -> Option<*const Node> { + d.ancestry(id).unwrap_or_default().into_iter().rev().find_map(|a| d.node(a).filter(|n| pred(n))).map(|n| n as *const Node) +} + +/// [`Document::nearest_finder`] gives what [`nearest_by_ancestry`] gives for every id, on a clone +/// each, so both start from the same cache. +fn nearest_agrees(d: &Document, ids: &[NodeId], what: &str) { + type Pred = fn(&Node) -> bool; + let preds: [(&str, Pred); 5] = [ + ("group", |n| matches!(n.kind, NodeKind::Group { .. })), + ("layer", |n| n.is_layer()), + ("any", |_| true), + ("none", |_| false), + ("id divisible by 3", |n| n.id.0 % 3 == 0), + ]; + for (name, pred) in preds { + let (a, b) = (d.clone(), d.clone()); + let want: Vec<_> = ids.iter().map(|id| nearest_by_ancestry(&a, *id, pred)).collect(); + let mut find = b.nearest_finder(); + let got: Vec<_> = ids.iter().map(|id| find.nearest(*id, pred).map(|n| n as *const Node)).collect(); + assert_eq!(got, want, "{what}: {name}"); + } +} + +#[test] +fn nearest_finder_matches_the_ancestry_walk() { + for seed in 1..30 { + let (mut d, ids) = tree(seed); + nearest_agrees(&d, &ids, "no cache"); + d.node(ids[0]); + nearest_agrees(&d, &ids, "cached"); + // Every path in the first layer shifts: the cache is stale there. + let extra = d.alloc_id(); + let leaf = Arc::new(Node::path(extra, shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), Appearance::default_art())); + if let Some(ch) = Arc::make_mut(&mut d.layers[0]).children_mut() { + ch.insert(0, leaf); + } + nearest_agrees(&d, &ids, "a stale cache"); + // A group with the id of a node in the last layer, earlier in tree order than it, put in + // after the cache was built. + d.drop_lookup_cache(); + d.node(ids[0]); + let last = d.layers.len() - 1; + let dup = d.layers[last].children().and_then(|c| c.last()).map(|n| n.id); + if let Some(dup) = dup + && let Some(ch) = Arc::make_mut(&mut d.layers[0]).children_mut() + { + ch.insert(0, Arc::new(Node::group(dup, vec![]))); + } + nearest_agrees(&d, &ids, "a duplicate put in after the cache was built"); + d.drop_lookup_cache(); + nearest_agrees(&d, &ids, "a duplicate, cached afresh"); + } +} + +/// An id on the path that an earlier node of another kind also has: the earlier node is the one +/// tested, as `node` gives it. +#[test] +fn nearest_finder_tests_the_first_node_with_a_repeated_id() { + let mut d = Document::new(612.0, 792.0); + let layer = d.layers[0].id; + let leaf = |id: u64| Arc::new(Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art())); + d.insert(Some(layer), 0, Node::group(NodeId(500), vec![leaf(501)])).unwrap(); + d.insert(Some(layer), 1, Node::path(NodeId(600), shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art())).unwrap(); + // A group that has the path's id, after the path in tree order. + d.insert(Some(layer), 2, Node::group(NodeId(600), vec![leaf(601)])).unwrap(); + let is_group = |n: &Node| matches!(n.kind, NodeKind::Group { .. }); + for cached in [false, true] { + d.drop_lookup_cache(); + if cached { + d.node(layer); + } + let mut find = d.nearest_finder(); + assert_eq!(find.nearest(NodeId(501), is_group).map(|n| n.id), Some(NodeId(500)), "cached {cached}"); + assert_eq!(find.nearest(NodeId(601), is_group).map(|n| n.id), None, "cached {cached}: id 600 is the path"); + assert_eq!(find.nearest(NodeId(999_999), is_group).map(|n| n.id), None, "cached {cached}: not in the tree"); + } +} + +/// With the cache built, finding the nearest group of every object of a large tree looks no id up +/// and walks the tree no time. +#[test] +fn nearest_finder_reads_one_path_per_object() { + let mut d = Document::new(612.0, 792.0); + let layer = d.layers[0].id; + let mut leaves = vec![]; + for g in 0..2_000 { + let kids: Vec> = (0..3) + .map(|_| { + let id = d.alloc_id(); + leaves.push(id); + Arc::new(Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art())) + }) + .collect(); + let gid = d.alloc_id(); + d.insert(Some(layer), g, Node::group(gid, kids)).unwrap(); + } + d.drop_lookup_cache(); + d.node(layer); + let (lookups, walks) = (path_lookups(), tree_walks()); + let mut find = d.nearest_finder(); + let found = leaves.iter().filter(|id| find.nearest(**id, |n| matches!(n.kind, NodeKind::Group { .. })).is_some()).count(); + assert_eq!(found, leaves.len()); + assert_eq!(path_lookups() - lookups, 0, "lookups by id"); + assert_eq!(tree_walks() - walks, 0, "walks of the tree"); +} diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs index 6863960230..a07afd0843 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -32,8 +32,8 @@ pub use para_style::{ pub use runs::PATH_LEAD_MAX; pub use runs::{INLINE_CHAR, INLINE_MAX_SCALE, InlineArt, RubyAlign, RubyPosition, RubySpan, TextKind, TextRun, TextStyleDef, TypeAntiAlias}; pub use tabs_lists::{ - Bullet, DEFAULT_TAB_INTERVAL, LIST_HANGING_INDENT, LIST_LEVEL_INDENT, LIST_LEVELS, ListAlign, ListCounts, NumberStyle, ParaList, TabAlign, - TabStop, + Bullet, DEFAULT_TAB_INTERVAL, LIST_HANGING_INDENT, LIST_LEVEL_INDENT, LIST_LEVELS, ListAlign, ListCounts, MAX_LIST_START, NumberStyle, ParaList, + TabAlign, TabStop, }; pub use wrap::{resolve_wrap, wrap_outline, wrap_sources, wrap_work}; diff --git a/crates/doc/src/text/object.rs b/crates/doc/src/text/object.rs index c556f2f5b0..746c0b69d5 100644 --- a/crates/doc/src/text/object.rs +++ b/crates/doc/src/text/object.rs @@ -304,17 +304,40 @@ impl TextObject { /// Update the paragraph styles for replacing bytes `start..end` of the current plain text by /// `insert` (call before changing the runs). The paragraph the range starts in keeps its /// style (merging paragraphs: the first one's wins); paragraphs the insertion starts take that - /// style too (Return continues the paragraph it splits); later paragraphs keep theirs. + /// style too (Return continues the paragraph it splits), without the number its list gives it + /// ([`ParaList::start`]); later paragraphs keep theirs. When an insertion that starts new + /// paragraphs is made at the start of a paragraph and some of that paragraph's text stays + /// after it, that number moves with the text to the last paragraph the insertion starts. pub fn splice_paras(&mut self, start: usize, end: usize, insert: &str) { - if self.paras.is_empty() { + let added = insert.bytes().filter(|&b| b == b'\n').count(); + let numbered = |p: &ParaStyle| p.list.is_some_and(|l| l.start.is_some()); + // With one style for every paragraph, the new paragraphs take it as it is unless its list + // gives the paragraph a number. + if self.paras.is_empty() && (added == 0 || !numbered(&self.para)) { return; } let r = self.paragraphs_in(start, end); let v = self.paragraph_styles(); - let Some(keep) = v.get(r.start).cloned() else { return }; - let added = insert.bytes().filter(|&b| b == b'\n').count(); + let Some(mut keep) = v.get(r.start).cloned() else { return }; + let given = keep.list.and_then(|l| l.start); + if let Some(l) = keep.list.as_mut() { + l.start = None; + } let mut out: Vec = v.iter().take(r.start + 1).cloned().collect(); out.extend(std::iter::repeat_n(keep, added)); + let text = self.plain_text(); + let (at, to) = (start.min(end).min(text.len()), start.max(end).min(text.len())); + let at_para_start = text.as_bytes().get(..at).is_some_and(|b| b.last().is_none_or(|&c| c == b'\n')); + // The paragraph's text after the replaced bytes, which the last new paragraph then holds. + let text_kept = r.len() == 1 && text.as_bytes().get(to).is_some_and(|&c| c != b'\n'); + if given.is_some() && added > 0 && at_para_start && text_kept { + if let Some(l) = out.get_mut(r.start).and_then(|p| p.list.as_mut()) { + l.start = None; + } + if let Some(l) = out.last_mut().and_then(|p| p.list.as_mut()) { + l.start = given; + } + } out.extend(v.iter().skip(r.end).cloned()); self.paras = out; if let Some(first) = self.paras.first() { diff --git a/crates/doc/src/text/para_style.rs b/crates/doc/src/text/para_style.rs index 62c6b8dd33..17325d071c 100644 --- a/crates/doc/src/text/para_style.rs +++ b/crates/doc/src/text/para_style.rs @@ -631,6 +631,8 @@ pub enum FirstBaseline { XHeight, /// The first line's leading. Leading, + /// The top of the first line's ideographic em box touches the frame top. + EmBoxHeight, /// Exactly `first_baseline_min` below the top. Fixed, } diff --git a/crates/doc/src/text/tabs_lists.rs b/crates/doc/src/text/tabs_lists.rs index 26622fa115..2d62eb2f0d 100644 --- a/crates/doc/src/text/tabs_lists.rs +++ b/crates/doc/src/text/tabs_lists.rs @@ -206,15 +206,41 @@ pub struct ParaList { /// ([`Self::depth`]). The file saves it only when it is not 1. #[serde(skip_serializing_if = "is_first_level", deserialize_with = "read_level")] pub level: u8, + /// The number a numbered paragraph is given, 1 to [`MAX_LIST_START`]: the numbered paragraphs + /// after it at its level count on from it ([`Self::next_marker`]). None: it counts on from the + /// numbered paragraph before it. A bulleted paragraph does not use it. A paragraph made + /// with Return in a paragraph that has one does not take it, and a paragraph style does not + /// keep it. A saved number outside the range is read as the nearest one. The file saves it + /// only when it is set. + #[serde(skip_serializing_if = "Option::is_none", deserialize_with = "read_start")] + pub start: Option, } impl Default for ParaList { - /// A bulleted list with a dot, its marker aligned left, at level 1. + /// A bulleted list with a dot, its marker aligned left, at level 1, numbered on from the + /// paragraph before. fn default() -> Self { - Self { bullet: Bullet::default(), number: None, align: ListAlign::default(), level: 1 } + Self { bullet: Bullet::default(), number: None, align: ListAlign::default(), level: 1, start: None } } } +/// The largest number a numbered paragraph can be given ([`ParaList::start`]). +pub const MAX_LIST_START: u32 = 999_999_999; + +/// Reads a saved list start, a whole number or null, as the nearest of 1 to [`MAX_LIST_START`], +/// so a start such as 0 or 5000000000 opens the file at 1 or [`MAX_LIST_START`]. Anything else +/// is an error. +fn read_start<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> { + let start = match serde_json::Value::deserialize(d)? { + serde_json::Value::Null => return Ok(None), + serde_json::Value::Number(n) if n.is_i64() || n.is_u64() => { + n.as_i64().map_or(i64::from(MAX_LIST_START), |n| n.clamp(1, i64::from(MAX_LIST_START))) + } + _ => return Err(serde::de::Error::custom("a list start must be a whole number")), + }; + Ok(u32::try_from(start).ok()) +} + /// Is `level` the first list level, which the file does not save? fn is_first_level(level: &u8) -> bool { *level == 1 @@ -307,6 +333,12 @@ impl ParaList { Self { level, ..self } } + /// This list with the paragraph numbered `start` (1 to [`MAX_LIST_START`]; None: on from the + /// paragraph before). + pub fn starting_at(self, start: Option) -> Self { + Self { start, ..self } + } + /// The list's level, 1 to [`LIST_LEVELS`]: [`Self::level`], a value outside the range taken /// as the nearest level. pub fn depth(&self) -> usize { @@ -334,8 +366,9 @@ impl ParaList { /// paragraph has none and leaves the counts as they are. A paragraph with text sets the counts /// of the levels deeper than its own back to 0, so a deeper paragraph after it counts from 1 /// again; a bulleted one has its bullet and leaves the count of its level as it is, and a - /// numbered one adds one to the count of its level and is numbered with it. A paragraph back - /// at a shallower level then goes on with that level's count. + /// numbered one adds one to the count of its level and is numbered with it, or with the number + /// it is given ([`Self::start`]), which becomes the count of its level. A paragraph back at a + /// shallower level then goes on with that level's count. pub fn next_marker(list: Option, empty: bool, counts: &mut ListCounts) -> Option { let Some(list) = list else { *counts = ListCounts::default(); @@ -350,7 +383,7 @@ impl ParaList { } let count = &mut counts.0[level]; if list.number.is_some() { - *count = count.saturating_add(1); + *count = list.start.map_or_else(|| count.saturating_add(1), |s| s.clamp(1, MAX_LIST_START)); } Some(list.marker(*count)) } diff --git a/crates/doc/src/text/tests.rs b/crates/doc/src/text/tests.rs index a5230d5d86..63b763423d 100644 --- a/crates/doc/src/text/tests.rs +++ b/crates/doc/src/text/tests.rs @@ -456,6 +456,99 @@ fn list_levels_count_their_own_numbers_and_save_only_past_the_first() { assert_eq!(opened.list_level_counts, (1..=8).collect::>(), "a file keeps only the counts of levels 2 to 9"); } +/// A numbered paragraph given a number shows it, and the numbered paragraphs after it at its level +/// count on from it; deeper levels still count from 1 after it, a bulleted or empty paragraph does +/// not use the number, and a paragraph in no list still starts the count again. The file saves the +/// number only when it is set, and a saved number outside 1 to 999999999 reads as the nearest one. +#[test] +fn a_numbered_paragraph_given_a_number_starts_its_level_count_there() { + let num = |level, start| Some(ParaList::numbered(NumberStyle::Arabic).at_level(level).starting_at(start)); + let dot = Some(ParaList::bulleted(Bullet::Dot).starting_at(Some(7))); + let mut counts = ListCounts::default(); + let markers: Vec> = [ + (num(1, None), false), + (num(1, Some(5)), false), + (num(1, None), false), + (num(2, None), false), + (num(2, Some(1)), false), + (num(2, None), false), + (num(1, None), false), + (num(1, Some(9)), true), + (num(1, None), false), + (dot, false), + (num(1, Some(1)), false), + (None, false), + (num(1, None), false), + ] + .iter() + .map(|&(l, empty)| ParaList::next_marker(l, empty, &mut counts)) + .collect(); + let want = ["1.", "5.", "6.", "1.", "1.", "2.", "7.", "", "8.", "\u{2022}", "1.", "", "1."]; + assert_eq!(markers.iter().map(|m| m.as_deref().unwrap_or("")).collect::>(), want); + let mut counts = ListCounts::default(); + let roman = Some(ParaList::numbered(NumberStyle::UpperRoman).starting_at(Some(MAX_LIST_START))); + assert_eq!(ParaList::next_marker(roman, false, &mut counts).as_deref(), Some("999999999.")); + let zero = Some(ParaList::numbered(NumberStyle::Arabic).starting_at(Some(0))); + assert_eq!(ParaList::next_marker(zero, false, &mut counts).as_deref(), Some("1."), "a number below 1 counts as 1"); + assert_eq!(serde_json::to_value(num(1, None)).unwrap(), serde_json::json!({"bullet": "dot", "number": "arabic"})); + assert_eq!(serde_json::to_value(num(1, Some(5))).unwrap(), serde_json::json!({"bullet": "dot", "number": "arabic", "start": 5})); + let read = |v: serde_json::Value| serde_json::from_value::(v).unwrap().start; + assert_eq!(read(serde_json::json!({"number": "arabic", "start": 5})), Some(5)); + assert_eq!(read(serde_json::json!({"number": "arabic"})), None); + assert_eq!(read(serde_json::json!({"number": "arabic", "start": null})), None); + let starts = [serde_json::json!(0), serde_json::json!(-3), serde_json::json!(5_000_000_000_u64), serde_json::json!(u64::MAX)]; + assert_eq!( + starts.map(|s| read(serde_json::json!({ "number": "arabic", "start": s }))), + [Some(1), Some(1), Some(MAX_LIST_START), Some(MAX_LIST_START)], + "a saved number outside 1 to 999999999 reads as the nearest one" + ); + for bad in [serde_json::json!(2.5), serde_json::json!("5"), serde_json::json!(true)] { + assert!(serde_json::from_value::(serde_json::json!({ "start": bad })).is_err(), "{bad}"); + } +} + +/// Return in a paragraph that its list gives a number makes paragraphs without it, also while +/// every paragraph shares one style; Return at the start of its text moves the number with the +/// text, and Return elsewhere leaves it where it was. +#[test] +fn return_does_not_copy_a_paragraphs_number() { + let five = ParaStyle { list: Some(ParaList::numbered(NumberStyle::Arabic).starting_at(Some(5))), ..ParaStyle::default() }; + let starts = |t: &TextObject| t.paragraph_styles().iter().map(|p| p.list.and_then(|l| l.start)).collect::>(); + // One style for the whole text: Return after "one" splits it. + let mut t = TextObject::point(Point::ZERO, "onetwo", CharStyle::default()); + t.set_all_paras(five); + t.splice_paras(3, 3, "\n"); + t.runs[0].text.insert(3, '\n'); + t.normalize_paras(); + assert_eq!(starts(&t), [Some(5), None]); + assert!(t.para_at(1).list.is_some_and(|l| l.number == Some(NumberStyle::Arabic)), "the new paragraph stays in the list"); + // Return at the start of "two" (a paragraph with a number of its own): the number moves on + // with the text, and the empty paragraph left before it has none. + t.edit_paras(Some(1..2), |p| p.list = p.list.map(|l| l.starting_at(Some(8)))); + t.splice_paras(4, 4, "\n\n"); + t.runs[0].text.insert_str(4, "\n\n"); + t.normalize_paras(); + assert_eq!(t.plain_text(), "one\n\n\ntwo"); + assert_eq!(starts(&t), [Some(5), None, None, Some(8)]); + // A whole paragraph pasted at the start of "two": the number stays with "two". + t.splice_paras(6, 6, "Pasted\n"); + t.runs[0].text.insert_str(6, "Pasted\n"); + t.normalize_paras(); + assert_eq!(t.plain_text(), "one\n\n\nPasted\ntwo"); + assert_eq!(starts(&t), [Some(5), None, None, None, Some(8)]); + // "two" replaced by two paragraphs: none of its text is left, so the first new one keeps it. + t.splice_paras(13, 16, "A\nB"); + t.runs[0].text.replace_range(13..16, "A\nB"); + t.normalize_paras(); + assert_eq!(t.plain_text(), "one\n\n\nPasted\nA\nB"); + assert_eq!(starts(&t), [Some(5), None, None, None, Some(8), None]); + // Text without a number keeps one style for every paragraph. + let mut t = TextObject::point(Point::ZERO, "onetwo", CharStyle::default()); + t.set_all_paras(ParaStyle { list: Some(ParaList::numbered(NumberStyle::Arabic)), ..ParaStyle::default() }); + t.splice_paras(3, 3, "\n"); + assert!(t.paras.is_empty()); +} + /// In a threaded frame whose first paragraph continues from the frame before, the text at the /// frame's start is not the start of a paragraph, so typing a list's start there starts nothing. /// The paragraphs after it still start lists. @@ -554,6 +647,20 @@ fn text_flow_is_saved_only_when_by_rows() { assert!(serde_json::from_value::(serde_json::json!({"flow": "diagonal"})).is_err()); } +/// First Baseline Em Box Height saves as `emBoxHeight` with its minimum and reads back; files from +/// before it read their own first baseline as they did, Ascent when they have none. +#[test] +fn em_box_height_first_baseline_is_saved_and_read_back() { + let set = AreaOptions { first_baseline: FirstBaseline::EmBoxHeight, first_baseline_min: 9.0, ..AreaOptions::default() }; + let saved = serde_json::to_value(&set).unwrap(); + assert_eq!((saved["firstBaseline"].as_str(), saved["firstBaselineMin"].as_f64()), (Some("emBoxHeight"), Some(9.0))); + assert_eq!(serde_json::from_value::(saved).unwrap(), set); + let old = serde_json::json!({"firstBaseline": "leading", "firstBaselineMin": 3.0}); + assert_eq!(serde_json::from_value::(old).unwrap().first_baseline, FirstBaseline::Leading); + assert_eq!(serde_json::from_value::(serde_json::json!({})).unwrap().first_baseline, FirstBaseline::Ascent); + assert!(serde_json::from_value::(serde_json::json!({"firstBaseline": "emBox"})).is_err()); +} + /// 120 × 40 area type at (40, 40), its text drawn at twice its size. fn area_type() -> TextObject { let mut t = TextObject::point(Point::ZERO, "Some text", CharStyle::default()); diff --git a/crates/doc/src/units.rs b/crates/doc/src/units.rs index 5fabfece65..7e061d02c0 100644 --- a/crates/doc/src/units.rs +++ b/crates/doc/src/units.rs @@ -316,6 +316,37 @@ fn percent(s: &str) -> Option { } } +/// `text` typed in a numeric field, with a decimal comma read as a point: `0,1 mm` is `0.1 mm` +/// (#3837), and each number of a sum reads its own separator, so `100.5 mm-0,5` (a comma typed +/// after the value the field shows) is 100 mm (#5684). A number written with both separators has +/// two points once read, so `1,000.5` and `1.234,5` are refused rather than guessed at; so is a +/// number that reads as thousands ([`thousands`]). +pub fn decimal_point(text: &str) -> std::borrow::Cow<'_, str> { + if text.contains(',') && !thousands(text) { text.replace(',', ".").into() } else { text.into() } +} + +/// Is `text` a number written with a thousands comma, as `1,000`, `+1,000`, `12,500 mm` or +/// `1,000"`: a sign, one to three digits (not a lone 0), a comma, exactly three digits, then at +/// most a unit? Read as a decimal it would be a thousand times too small, so the field refuses it +/// instead (`0,125` and `1,25` are decimals). +fn thousands(text: &str) -> bool { + let number = text.trim(); + let number = number.strip_prefix(['+', '-']).unwrap_or(number); + let Some((whole, rest)) = number.split_once(',') else { return false }; + let (part, unit) = rest.split_at(rest.find(|c: char| !c.is_ascii_digit()).unwrap_or(rest.len())); + (1..=3).contains(&whole.len()) + && whole.bytes().all(|b| b.is_ascii_digit()) + && !whole.starts_with('0') + && part.len() == 3 + && unit.trim().chars().all(|c| c.is_alphabetic() || c == '"' || c == '\'') +} + +/// Is the length `pt` (points) a finite number in every unit of [`Unit::EAST_ASIAN`]? A length +/// near the largest number in points is too large in Q and Ha. +pub fn finite_in_every_unit(pt: f64) -> bool { + pt.is_finite() && Unit::EAST_ASIAN.iter().all(|u| u.from_pt(pt).is_finite()) +} + /// A unitless field value (percent, degrees, counts) with the same `+ - * /` arithmetic as /// [`Unit::parse`] (`45*2`, `100/3`); text other than digits, `.` and operators reads as nothing. pub fn parse_number(s: &str) -> Option { diff --git a/crates/effects/src/bake.rs b/crates/effects/src/bake.rs index 274f9bdcc4..36418ac913 100644 --- a/crates/effects/src/bake.rs +++ b/crates/effects/src/bake.rs @@ -28,7 +28,8 @@ use vectorcraft_geom::{Affine, FillRule, PathData, Rect, Vec2}; use crate::distort::{transform_move, transform_offsets}; use crate::group::{has_own_paint, paints}; use crate::reshape::{ - as_art, clipping_text_outline, dressed, geometry_effects, glyph_outlines, outline_nested_text, paint_type_clip, reshape_leaves, + as_art, clip_region_path, clipping_text_outline, dressed, geometry_effects, glyph_outlines, knockout_inside, outline_nested_text, + paint_type_clip, reshape_leaves, }; use crate::{ GeomContext, adjust_in_document, apply_geometry_carrying, crop_marks_art, evaluate_container, has_adjustment, has_crop_marks, has_geometry, @@ -502,13 +503,7 @@ fn clip_group_with_type_clip(d: &mut Document, n: &Node) -> Option { { return None; } - let (bp, rule) = crate::clip_outline(first)?; - let mut clip = Node::path(first.id, PathData::from_bezpath(&bp), Appearance::default()); - if let NodeKind::Path { rule: r, clipping, .. } = &mut clip.kind { - (*r, *clipping) = (rule, true); - } - clip.name = first.name.clone(); - clip.visible = first.visible; + let clip = clip_region_path(first)?; let paint = first.clip_paint(); // The type's fills and strokes as art: baked with the type's id, as the renderer draws them, // then given ids of their own. @@ -532,7 +527,8 @@ fn clip_group_with_type_clip(d: &mut Document, n: &Node) -> Option { return Some(m); }; // `n` keeps its id, name and transparency, and holds the clip group and the strokes over it. - let inner = Node::new(d.alloc_id(), NodeKind::Group { children: members, clip: true }); + let mut inner = Node::new(d.alloc_id(), NodeKind::Group { children: members, clip: true }); + knockout_inside(&mut m, &mut inner); match &mut m.kind { NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. } => { *children = vec![Arc::new(inner), stroke]; diff --git a/crates/effects/src/bake/tests.rs b/crates/effects/src/bake/tests.rs index deb705752f..70bdc7731b 100644 --- a/crates/effects/src/bake/tests.rs +++ b/crates/effects/src/bake/tests.rs @@ -776,7 +776,7 @@ fn type_outlined_next_to_type_that_stays_type_keeps_its_look() { let mut shadowed = type_node(55); shadowed.opacity = 0.5; shadowed.appearance.effects.push(fx("stylize.dropShadow", json!({}))); - // Type that clips a group is outlined as the plain outlines it clips by. + // Type that clips a group is outlined as a plain path of the region it clips by. let square = Node::path(NodeId(57), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default_art()); let clip = Node::new(NodeId(58), NodeKind::Group { children: vec![Arc::new(type_node(56)), Arc::new(square)], clip: true }); g.children_mut().unwrap().extend([Arc::new(shadowed), Arc::new(clip)]); @@ -789,7 +789,10 @@ fn type_outlined_next_to_type_that_stays_type_keeps_its_look() { let b = o.geometric_bounds().unwrap(); assert!(b.x0 < 30.0 && b.x1 > 220.0, "{b:?}"); let clipped = d.node(NodeId(58)).and_then(|n| n.children()).and_then(|c| c.first()).unwrap(); - assert!(matches!(clipped.kind, NodeKind::Group { .. }) && clipped.opacity == 1.0, "{clipped:?}"); + assert!(matches!(clipped.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) && clipped.opacity == 1.0, "{clipped:?}"); + // The region is copied with the type. + let b = clipped.geometric_bounds().unwrap(); + assert!(b.x0 < 30.0 && b.x1 > 220.0, "{b:?}"); } #[test] diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index ea727b804c..568aa583b1 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -189,7 +189,7 @@ pub fn effect_catalog() -> Vec { EXTRUDE, "Extrude & Bevel…", &["Effect", "3D and Materials"], - "{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the caps, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back (front; the back reads left to right as seen from behind), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane), y: pt (0), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the cap and clipped to it, on a solid cap only), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).", + "{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the caps and the side, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back|side (front; the back reads left to right as seen from behind; side is the walls and bevels), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on the side from the middle of the side unrolled flat, along the outline, clockwise from its top), y: pt (0; on the side from the front toward the back), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the face and clipped to it: on a cap of a solid object only, and on the side of a solid or hollow object wrapped around it and drawn only where its outside faces the viewer), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).", json!({"depth":50.0,"twist":0.0,"taper":100.0,"cap":true,"bevel":"none","bevelWidth":4.0,"bevelHeight":4.0,"bevelRepeat":1,"bevelSpace":0.0,"bevelInside":false,"bevelBothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"render":{"mode":"shaded"}}), ), g( @@ -277,7 +277,13 @@ pub fn effect_catalog() -> Vec { "{h: amount (10), v: amount (10), relative: bool (true: % of size), anchors: bool (true), in: bool (true), out: bool (true), seed: int (0)}", json!({"h": 10.0, "v": 10.0, "relative": true, "anchors": true, "in": true, "out": true, "seed": 0}), ), - g("distort.twist", "Twist…", DT, "{angle: deg (-3600..3600, 10)}", json!({"angle": 10.0})), + g( + "distort.twist", + "Twist…", + DT, + "{angle: deg (-3600..3600, 10)} Outer-circle anchors stay fixed; their handles follow the inward tangent.", + json!({"angle": 10.0}), + ), g( "distort.zigZag", "Zig Zag…", diff --git a/crates/effects/src/distort.rs b/crates/effects/src/distort.rs index 7a03a2f3aa..3fa1f3d152 100644 --- a/crates/effects/src/distort.rs +++ b/crates/effects/src/distort.rs @@ -6,7 +6,7 @@ use vectorcraft_geom::{Affine, Anchor, ParamCurve, PathData, Point, Rect, SubPat use vectorcraft_pathops::addons::pathtools::insert_at; use crate::util::{ - catmull_rom, fit_piece, flag, map_nonlinear_within, map_smooth_within, mean_size, noise, normal_at, num, pieces, seed, seg_cubic, smooth_points, + catmull_rom, fit_piece, flag, map_handles_within, map_nonlinear_within, mean_size, noise, normal_at, num, pieces, seed, seg_cubic, smooth_points, }; fn diag(b: Rect) -> f64 { @@ -328,7 +328,7 @@ pub fn tweak(path: &PathData, b: Rect, p: &Value) -> PathData { /// Twist: rotation that is strongest at the centre and fades to zero at the bounding circle, /// clockwise on the page for a positive `angle`, making at most `max` anchors. Its handles follow -/// the rotation's derivative ([`map_smooth_within`]), so the pieces join without kinks (#7069). +/// the rotation's directional derivative, including each side of the outer circle. pub fn twist(path: &PathData, b: Rect, angle: f64, max: usize) -> PathData { let ang = angle.clamp(-3600.0, 3600.0).to_radians(); if ang == 0.0 { @@ -336,16 +336,46 @@ pub fn twist(path: &PathData, b: Rect, angle: f64, max: usize) -> PathData { } let c = b.center(); let r = diag(b) / 2.0; + let half = Vec2::new(b.width() * 0.5, b.height() * 0.5); + let boundary = move |p: Point, length: f64| { + if length == r { + return true; + } + if !r.is_finite() || (length - r).abs() > 8.0 * f64::EPSILON * r { + return false; + } + // A bounds-relative distance identifies boundary points affected by center rounding. + (Vec2::new(p.x - b.x0, p.y - b.y0) - half).hypot() == r + }; let f = move |q: Point| { let d = q - c; - let t = (1.0 - d.hypot() / r).max(0.0); + let length = d.hypot(); + let t = (1.0 - length / r).max(0.0); // y runs down, so a positive turn is clockwise on the page. let a = ang * t; + if a == 0.0 { + return q; + } let (s, co) = a.sin_cos(); c + Vec2::new(d.x * co - d.y * s, d.x * s + d.y * co) }; let piece = (r / 8.0).min(r / (1.0 + ang.abs() * 2.0)); - map_smooth_within(path, piece, max, f) + map_handles_within(path, piece, max, f, |p, h| { + let v = h - p; + if !v.hypot().is_finite() { + return f(p); + } + let d = p - c; + let length = d.hypot(); + let radial = if length > 0.0 { (d / length).dot(v) } else { 0.0 }; + // The clamped rotation has different inward and outward derivatives at the circle. + let inside = if boundary(p, length) { radial < 0.0 } else { length < r }; + let gradient = if inside { -ang / r * radial } else { 0.0 }; + let tangent = if gradient == 0.0 { v } else { v + Vec2::new(-d.y, d.x) * gradient }; + let a = ang * (1.0 - length / r).max(0.0); + let (s, co) = a.sin_cos(); + f(p) + Vec2::new(tangent.x * co - tangent.y * s, tangent.x * s + tangent.y * co) + }) } const ZIGZAG_ARCLEN_ACCURACY: f64 = 1e-4; diff --git a/crates/effects/src/group.rs b/crates/effects/src/group.rs index 6b9681de19..a6f5af916b 100644 --- a/crates/effects/src/group.rs +++ b/crates/effects/src/group.rs @@ -110,13 +110,15 @@ fn leaves(doc: Option<&Document>, n: &Node, hook: Option, nodes: &S // Every path of the outline art, at any depth, is drawn inside the object's opacity // and blend mode. A symbol's art comes with the live objects and the instances of // other symbols inside it given as their art, and the type inside it outlined, so the - // art has nothing left for `hook` to give. + // art has nothing left for `hook` to give. Its fills and strokes carry the geometry + // effects of the instance's active fill and stroke, as the canvas draws them. if let Some(h) = hook && let Some(art) = h(n) { let art = match &n.kind { NodeKind::SymbolInstance { symbol, .. } if nodes.charge(&art) => { - let mut art = crate::reshape::symbol_art_with(&art, h, nodes, symbol); + let mut art = instance_art(doc, &art, h, nodes, symbol); + crate::reshape::add_instance_row_effects(doc, n, &mut art); crate::reshape::outline_nested_text(doc, &mut art, false); transparency_into_members(&mut art); art @@ -134,6 +136,19 @@ fn leaves(doc: Option<&Document>, n: &Node, hook: Option, nodes: &S } } +/// `art`, the art `hook` gave an instance of the symbol named `symbol`, with the live objects and +/// the instances of other symbols inside it given as their art +/// ([`crate::reshape::symbol_art_with`]). The art of each of those instances carries the geometry +/// effects of its own active fill and stroke ([`crate::reshape::add_instance_row_effects`]). +fn instance_art(doc: Option<&Document>, art: &Node, hook: OutlineHook, nodes: &SymbolNodes, symbol: &str) -> Node { + let drawn = |m: &Node| { + let mut a = hook(m)?; + crate::reshape::add_instance_row_effects(doc, m, &mut a); + Some(a) + }; + crate::reshape::symbol_art_with(art, &drawn, nodes, symbol) +} + /// `l`, a path drawn inside `n`: its opacity multiplied by `n`'s, and `n`'s blend mode when it is /// not Normal. fn within(l: &mut Node, n: &Node) { @@ -221,13 +236,15 @@ fn reshaped_art(doc: Option<&Document>, n: &Node, hook: Option, nod } }, // A symbol instance with a warp: its symbol's art placed by the instance, with the type - // inside it outlined, reshaped as one piece, as the renderer draws it. + // inside it outlined, reshaped as one piece, as the renderer draws it. The fills and strokes + // of the art then carry the geometry effects of the instance's active fill and stroke. NodeKind::SymbolInstance { symbol, .. } if !fx.is_empty() => { let h = hook?; let art = h(n).filter(|art| nodes.charge(art))?; - let mut art = crate::reshape::symbol_art_with(&art, h, nodes, symbol); + let mut art = instance_art(doc, &art, h, nodes, symbol); crate::reshape::outline_nested_text(doc, &mut art, false); members_as_drawn(doc, &mut art); + crate::reshape::add_instance_row_effects(doc, n, &mut art); let carry = crate::reshape::reshape_leaves_carrying(&mut art, &fx, &n.appearance.effects, doc); // The art's own fills and strokes follow the effects as its members do. if carry.moves(&art.appearance) { @@ -703,6 +720,11 @@ pub fn member_shapes(doc: Option<&Document>, n: &Node) -> Vec<(PathData, FillRul } } fn members(doc: Option<&Document>, n: &Node, out: &mut Vec<(PathData, FillRule)>) { + // A clip group whose clipping type's strokes paint around it is outlined as that clip + // group: the strokes outside the clip add nothing. + if let Some(inner) = crate::reshape::painted_clip_inner(n) { + return members(doc, inner, out); + } // A clip group shows its members only inside its clipping path: its outline is that // region, not the clipped members' own shapes, which may reach far outside it (#7289). if n.clips() { @@ -902,14 +924,18 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option { } let PreparedContainer { mut m, guides, paint, .. } = prepare_container(doc, n)?; if paint { - let shapes = member_shapes(doc, &m); - let bounds = m.geometric_bounds(); + // A clip group whose clipping type paints strokes is now a group of a clip group and those + // strokes ([`crate::reshape::paint_type_clip`]): its own fills and strokes paint inside + // that clip group. Such groups among the members are measured as their clip groups. + let wrapped = n.clips() && crate::reshape::painted_clip_inner(&m).is_some(); + let (shapes, bounds) = (member_shapes(doc, &m), crate::reshape::clip_bounds(&m)); let art = |items: &[AppearanceItem]| -> Vec> { items.iter().filter_map(|i| item_art(n.id, i, &shapes, bounds)).map(Arc::new).collect() }; let (below, above) = m.appearance.split_contents(); let (below, above) = (art(below), art(above)); - let at = usize::from(m.clips()); - if let Some(ch) = m.children_mut() { + let at = usize::from(wrapped || m.clips()); + let target = if wrapped { m.children_mut().and_then(|ch| ch.first_mut()).map(Arc::make_mut) } else { Some(&mut m) }; + if let Some(ch) = target.and_then(Node::children_mut) { let at = at.min(ch.len()); ch.splice(at..at, below); ch.extend(above); diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index dcd028f97d..a6b4ccece9 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -105,8 +105,8 @@ pub use solids::{ validate_three_d_params, view_options, with_graphic, }; pub use solids::{ - GRAPHIC_MAX_OFFSET, GRAPHIC_SCALE_RANGE, GRAPHICS_NOT_TAKEN, appearance_graphic_symbols, exports_three_d, graphic_frame_at, - graphics_reshaped_after, rename_appearance_graphic_symbol, + GRAPHIC_MAX_OFFSET, GRAPHIC_SCALE_RANGE, GRAPHICS_NOT_TAKEN, appearance_graphic_symbols, exports_three_d, graphic_fitting_scale, + graphic_frame_at, graphic_side_size, graphics_reshaped_after, rename_appearance_graphic_symbol, }; pub use stylize::{ScribbleSetting, scribble_setting_id, scribble_settings}; pub use svg_filter::SVG_FILTER; diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index 7f0ed1e2a9..85c36f2d89 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -387,7 +387,7 @@ fn row_effects_of(fx: &[Effect]) -> Vec { /// of a symbol whose art (in `doc`) holds an instance of `n`'s symbol, at any depth, keeps its /// appearance, so the effects never pass round a symbol that holds itself. Without `doc`, no /// instance in the art takes them. -fn add_instance_row_effects(doc: Option<&Document>, n: &Node, art: &mut Node) { +pub(crate) fn add_instance_row_effects(doc: Option<&Document>, n: &Node, art: &mut Node) { let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { return }; let fill = active_fill(n).map_or(vec![], |f| row_effects_of(&f.effects)); let stroke = active_stroke(n).map_or(vec![], |s| row_effects_of(&s.effects)); @@ -613,32 +613,101 @@ fn traced_opaque_area(bytes: &[u8]) -> Traced { /// rule and the fill or stroke that paints it: the paths (or compound paths) that [`reshape`] /// makes along its frame or, for those whose first effect is Outline Object, along the outline of /// its opaque area ([`opaque_area`]), with each fill's or stroke's geometry effects applied as the -/// renderer applies them. Empty for anything but an image with such fills or strokes. The swatches -/// and patterns that live-effect plug-ins painting their pieces name are looked up in `doc`, and -/// the image's pixels in `doc` when the image does not hold them. +/// renderer applies them. For a symbol instance whose active fill or stroke has a visible geometry +/// effect ([`has_item_geometry`]), the shapes that the fills and strokes of the art it draws paint +/// ([`instance_paint`]). Empty for anything else. The swatches and patterns that live-effect +/// plug-ins painting their pieces name are looked up in `doc`, and the image's pixels in `doc` when +/// the image does not hold them. pub fn image_paint(doc: Option<&Document>, n: &Node) -> Vec<(BezPath, FillRule, AppearanceItem)> { - if !matches!(n.kind, NodeKind::Image(_)) || !has_item_geometry(n) { - return vec![]; - } - let Some(art) = reshape(doc, n, None) else { return vec![] }; let mut out = vec![]; - art.walk(&mut |c| { - let (NodeKind::Path { rule, .. } | NodeKind::Compound { rule, .. }) = &c.kind else { return }; - let Some(g) = c.stroke_path() else { return }; - let ctx = GeomContext { doc, ..GeomContext::of(c) }; - for item in c.appearance.items.iter().filter(|i| crate::paints(i)) { - let fx = item.effects(); - let shape = if crate::has_geometry(fx) && !g.elements().is_empty() { - crate::apply_geometry_bez(fx, &g, g.bounding_box(), &ctx.item(item)) - } else { - g.clone() - }; - out.push((shape, *rule, item.clone())); - } - }); + if matches!(n.kind, NodeKind::SymbolInstance { .. }) { + let mut budget = SYMBOL_ART_MAX_NODES; + instance_paint(doc, n, 1, &mut budget, &mut out); + return out; + } + if !matches!(n.kind, NodeKind::Image(_)) || !has_item_geometry(n) { + return out; + } + let Some(art) = reshape(doc, n, None) else { return out }; + art.walk(&mut |c| push_painted(doc, c, &mut out)); out } +/// The shapes that the fills and strokes of path or compound path `c` paint, each with the +/// geometry effects of that fill or stroke applied ([`image_paint`]); nothing for other objects. +fn push_painted(doc: Option<&Document>, c: &Node, out: &mut Vec<(BezPath, FillRule, AppearanceItem)>) { + let (NodeKind::Path { rule, .. } | NodeKind::Compound { rule, .. }) = &c.kind else { return }; + let Some(g) = c.stroke_path() else { return }; + let ctx = GeomContext { doc, ..GeomContext::of(c) }; + for item in c.appearance.items.iter().filter(|i| crate::paints(i)) { + let fx = item.effects(); + let shape = if crate::has_geometry(fx) && !g.elements().is_empty() { + crate::apply_geometry_bez(fx, &g, g.bounding_box(), &ctx.item(item)) + } else { + g.clone() + }; + out.push((shape, *rule, item.clone())); + } +} + +/// The shapes that symbol instance `n`, `depth` instances deep, paints with the geometry effects of +/// its active fill and stroke ([`has_item_geometry`]): the paths of the art [`reshape`] makes of it, +/// each with its own geometry effects and those of each fill and stroke applied +/// ([`crate::bake_type_appearance`], [`push_painted`]), the paths that the own fills and strokes of +/// the groups and layers in the art paint and the results of their Pathfinder effects +/// ([`crate::evaluate_container`]), the shapes that the own fills and strokes of the images in the +/// art paint ([`image_paint`]), and the instances in that art that took those effects, in turn. +/// Hidden objects, clipping paths, guides, the members of clip groups and the original shapes of +/// Shaper groups add nothing, and neither does an instance more than +/// [`vectorcraft_doc::depth::MAX_DEPTH`] deep or whose symbol's art would take the objects measured +/// so far past `budget`. +fn instance_paint(doc: Option<&Document>, n: &Node, depth: usize, budget: &mut u64, out: &mut Vec<(BezPath, FillRule, AppearanceItem)>) { + let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { return }; + if depth >= vectorcraft_doc::depth::MAX_DEPTH || !has_item_geometry(n) { + return; + } + let Some(sym) = doc.and_then(|d| d.symbols.iter().find(|s| s.name == *symbol)) else { return }; + let count = sym.art.count() as u64; + if count > *budget { + return; + } + *budget -= count; + let Some(art) = reshape(doc, n, Some(&vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, n))) else { return }; + painted_in(doc, &art, depth, budget, out); +} + +/// [`instance_paint`] of the objects in `n`, art of an instance `depth` instances deep. +fn painted_in(doc: Option<&Document>, n: &Node, depth: usize, budget: &mut u64, out: &mut Vec<(BezPath, FillRule, AppearanceItem)>) { + if !n.visible { + return; + } + match &n.kind { + NodeKind::Path { clipping: false, guide: false, .. } | NodeKind::Compound { .. } => match crate::bake_type_appearance(doc, n) { + // One path for each fill and stroke, its effects applied. + Some(pieces) => painted_in(doc, &pieces, depth, budget, out), + None => push_painted(doc, n, out), + }, + NodeKind::Path { .. } => {} + NodeKind::Image(_) => out.extend(image_paint(doc, n)), + NodeKind::SymbolInstance { .. } => instance_paint(doc, n, depth + 1, budget, out), + _ if n.clips() => {} + _ => { + // A Pathfinder effect paints its result, not the members it combines. + let evaluated = (crate::has_container_appearance(n) || crate::has_pathfinder(n)).then(|| crate::evaluate_container(doc, n)).flatten(); + let g = evaluated.as_ref().unwrap_or(n); + if g.clips() { + return; + } + // A Shaper group's first member holds its original shapes, which are not drawn. The + // group's own fills and strokes can be painted before it, so it is found by its id. + let sources = n.extras().shaper.is_some().then(|| n.children().and_then(|c| c.first()).map(|c| c.id)).flatten(); + for c in g.children().into_iter().flatten().filter(|c| Some(c.id) != sources) { + painted_in(doc, c, depth, budget, out); + } + } + } +} + /// The glyph outlines of type `t` in text space with its underline and strikethrough bars: one /// path per run, and all of them as one. pub(crate) fn glyph_outlines(t: &vectorcraft_doc::TextObject) -> (Vec, kurbo::BezPath) { @@ -954,6 +1023,74 @@ pub(crate) fn clipping_text_outline(t: &Node) -> Option { Some(Node { visible: t.visible, ..o }) } +/// Clipping path `clip` of a clip group as a clipping path of the region it clips to +/// ([`crate::clip_outline`]), with its id, name and visibility. For type that paints, the geometry +/// effects of its fills and strokes reshape what they paint and leave that region as it is. +/// `None` when it has nothing to clip by. +pub(crate) fn clip_region_path(clip: &Node) -> Option { + let (bp, rule) = crate::clip_outline(clip)?; + let mut p = Node::path(clip.id, PathData::from_bezpath(&bp), Appearance::default()); + if let NodeKind::Path { rule: r, clipping, .. } = &mut p.kind { + (*r, *clipping) = (rule, true); + } + p.name = clip.name.clone(); + p.visible = clip.visible; + Some(p) +} + +/// Knockout Group for clip group `m` turned into a group around `inner`, a clip group of its +/// members, and its clipping path's strokes: `inner` takes `m`'s setting, so the clipped art knocks +/// out as before, and `m` is set Off so the strokes paint over it, as the renderer draws them. A +/// neutral `m` stays neutral, so both take the setting of the groups around them. +pub(crate) fn knockout_inside(m: &mut Node, inner: &mut Node) { + inner.knockout = m.knockout; + if m.knockout != vectorcraft_doc::Knockout::Neutral { + m.knockout = vectorcraft_doc::Knockout::Off; + } +} + +/// The clip group in `n` when `n` is a group or layer that [`paint_type_clip`] made of a clip +/// group and its clipping type's strokes: a group that does not clip whose first member is a clip +/// group with `n`'s id and whose second member has the id of that clip group's clipping path. The +/// clip group's region is what `n` stands for, as the clip group it was made from: the strokes +/// paint outside it and add nothing to its outline ([`crate::member_shapes`]) or its bounds +/// ([`clip_bounds`]). +pub(crate) fn painted_clip_inner(n: &Node) -> Option<&Node> { + if n.clips() || !matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) { + return None; + } + let [inner, stroke, ..] = n.children()?.as_slice() else { return None }; + let clip = inner.children()?.first()?; + (inner.clips() && inner.id == n.id && stroke.id == clip.id && !stroke.clips()).then_some(&**inner) +} + +/// The geometric bounds of `n` ([`Node::geometric_bounds`]) with each group or layer in it that +/// [`painted_clip_inner`] finds measured as its clip group, so the strokes of a clipping type +/// outside the clip do not widen them. +pub(crate) fn clip_bounds(n: &Node) -> Option { + fn holds(n: &Node) -> bool { + painted_clip_inner(n).is_some() || n.children().into_iter().flatten().any(|c| holds(c)) + } + fn unwrap(n: &mut Node) { + if let Some(inner) = painted_clip_inner(n) { + let mut inner = inner.clone(); + inner.visible = n.visible; + *n = inner; + } + for c in n.children_mut().into_iter().flatten() { + if holds(c) { + unwrap(Arc::make_mut(c)); + } + } + } + if !holds(n) { + return n.geometric_bounds(); + } + let mut probe = n.clone(); + unwrap(&mut probe); + probe.geometric_bounds() +} + /// Replace type anywhere inside `n` by its outlines, as art that keeps the type's look /// ([`as_art`]). Type in a clip group's clipping path (all of `n` when `clipping` is set) becomes /// its outlines with its visibility and effects ([`clipping_text_outline`]), and its fills and @@ -981,32 +1118,41 @@ pub(crate) fn outline_nested_text(doc: Option<&Document>, n: &mut Node, clipping } /// When `n` is a clip group or clipping layer whose clipping path is type that paints -/// ([`Node::clip_paint`]), make it the art the canvas draws for it: the type's outlines clip -/// ([`clipping_text_outline`]), its fills as art ([`as_art`]) paint behind the clipped art inside -/// the clip, and its strokes as art paint over it, outside the clip, in a group that `n` becomes -/// (keeping its id, name and transparency) with the clip group inside. The other members stay as -/// they are. Hidden type paints nothing. +/// ([`Node::clip_paint`]), make it the art the canvas draws for it: a path of the region the type +/// clips to clips ([`clip_region_path`]), its fills as art ([`as_art`]) paint behind the clipped +/// art inside the clip, and its strokes as art paint over it, outside the clip. Each part is the +/// type's art with only those fills or strokes, their own geometry effects applied. With strokes, +/// `n` becomes a group (keeping its id, name, visibility and transparency) that holds a clip group +/// of the clipping path, the fills and the other members, with `n`'s id, then the strokes; a +/// clipping layer keeps its ruler guides last. [`knockout_inside`] sets the Knockout Group of both, +/// and [`painted_clip_inner`] finds that clip group. The other members stay as they are. Hidden +/// type paints nothing. pub(crate) fn paint_type_clip(doc: Option<&Document>, n: &mut Node) { - let Some((first, rest)) = n.children().and_then(|ch| ch.split_first()) else { return }; - if !n.clips() || !matches!(first.kind, NodeKind::Text(_)) || !first.visible { + let Some(first) = n.children().and_then(|ch| ch.first()).filter(|_| n.clips()) else { return }; + if !matches!(first.kind, NodeKind::Text(_)) || !first.visible { return; } let paint = first.clip_paint(); if paint.fill.is_none() && paint.stroke.is_none() { return; } - let Some(clip) = clipping_text_outline(first) else { return }; + let Some(clip) = clip_region_path(first) else { return }; let art = |part: Option| part.and_then(|p| as_art(doc, &p, None)).map(Arc::new); - let members: Vec> = std::iter::once(Arc::new(clip)).chain(art(paint.fill)).chain(rest.iter().cloned()).collect(); - let stroke = art(paint.stroke); + let (fill, stroke) = (art(paint.fill), art(paint.stroke)); let id = n.id; - match (&mut n.kind, stroke) { - (NodeKind::Group { children, .. } | NodeKind::Layer { children, .. }, None) => *children = members, - (NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. }, Some(stroke)) => { - *children = vec![Arc::new(Node::new(id, NodeKind::Group { children: members, clip: true })), stroke]; - *clip = false; - } - _ => {} + let Some(ch) = n.children_mut() else { return }; + let Some(slot) = ch.first_mut() else { return }; + *slot = Arc::new(clip); + if let Some(fill) = fill { + ch.insert(1, fill); + } + let Some(stroke) = stroke else { return }; + let guides = ch.split_off(Node::guide_run_start(ch)); + let mut inner = Node::new(id, NodeKind::Group { children: std::mem::take(ch), clip: true }); + knockout_inside(n, &mut inner); + if let NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. } = &mut n.kind { + *children = [Arc::new(inner), stroke].into_iter().chain(guides).collect(); + *clip = false; } } @@ -1822,7 +1968,7 @@ impl Step<'_> { if !groups.is_empty() { carry_groups(art, groups, after, &|from, to| crate::Carry::of(&e.id, params, bounds, from, to, seed)); } - let drawn = warped.as_deref().map_or_else(|| art.geometric_bounds(), |w| w.bounds(art)); + let drawn = warped.as_deref().map_or_else(|| clip_bounds(art), |w| w.bounds(art)); let whole = (follows && !held).then(|| crate::Carry::of(&e.id, params, bounds, Some(bounds), drawn, seed)); Ran { kept: !kept_ids.is_empty(), took, masks, short, whole } } @@ -3247,6 +3393,9 @@ fn group_marks( NodeKind::Image(_) => (images.map_or_else(|| n.geometric_bounds(), |w| w.image_bounds(n)), false), NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. } if !n.extras().type_outlines => { let layer = matches!(n.kind, NodeKind::Layer { .. }); + // A clip group whose clipping type's strokes paint around it is measured as that clip + // group: the strokes outside the clip do not widen it ([`clip_bounds`]). + let clip = *clip || painted_clip_inner(n).is_some(); let skip = children.len().saturating_sub(n.editing_children().len()); let (mut bounds, mut held) = (None, false); for (i, c) in children.iter().enumerate() { @@ -3257,7 +3406,7 @@ fn group_marks( } at.pop(); // Only members measured in the bounds hold the group's gradients in place. - let counts = if *clip { i == 0 } else { i >= skip && (c.visible || !layer) }; + let counts = if clip { i == 0 } else { i >= skip && (c.visible || !layer) }; if counts { bounds = vectorcraft_geom::union_opt(bounds, b); held |= h; @@ -3473,16 +3622,17 @@ impl WarpedImages { /// The geometric bounds of `art` as it draws after the effects so far: each image this table /// lists measured by the pieces the warps and moves it took would cut it into, when the art - /// has room for them ([`cut_warped_images`]). + /// has room for them ([`cut_warped_images`]). The strokes of clipping type outside its clip + /// are left out ([`clip_bounds`]). pub(crate) fn bounds(&self, art: &Node) -> Option { if self.images.is_empty() || !self.fits(art, crate::distort::MAX_COPY_OBJECTS) { - return art.geometric_bounds(); + return clip_bounds(art); } // The pieces the images would be cut into now: each group of pieces is shown or hidden as // its image is, and hidden objects are left out of a layer's bounds. let mut probe = art.clone(); restore_warped_images(&mut probe, self, true); - probe.geometric_bounds() + clip_bounds(&probe) } /// The geometric bounds of image `n`: when this table lists it, measured by the pieces the diff --git a/crates/effects/src/revolve.rs b/crates/effects/src/revolve.rs index acd6cf7c94..43e60a0022 100644 --- a/crates/effects/src/revolve.rs +++ b/crates/effects/src/revolve.rs @@ -6,7 +6,7 @@ use serde_json::Value; use vectorcraft_doc::color::{Color, Paint}; use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, FillLayer, Node, NodeId, NodeKind}; use vectorcraft_geom::{FillRule, PathData, PathEl, Point, Rect, Vec2}; -use vectorcraft_three_d::{Edge, Revolve, SolidFaces}; +use vectorcraft_three_d::{Edge, PlanarFace, Revolve, SolidFaces}; use crate::solids::wireframe::{WireFace, wireframe_params}; use crate::solids::{ @@ -168,7 +168,7 @@ pub(crate) fn validate_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value) // With no member to carry them, the graphics' art must still fit its limits. None => { crate::solids::graphics::validate_symbols(doc, p)?; - crate::solids::graphics::validate_surface_symbols(doc, p)?; + crate::solids::graphics::validate_surface_symbols(doc, p, PlanarFace::Front)?; } } } @@ -201,10 +201,10 @@ fn check_graphics(doc: Option<&Document>, id: &str, path: &PathData, b: Rect, op let graphics = crate::solids::mapped_graphics(p); let Some(doc) = doc.filter(|_| id == REVOLVE && !graphics.is_empty()) else { return Ok(()) }; crate::solids::graphics::validate_symbols(doc, p)?; - crate::solids::graphics::validate_surface_symbols(doc, p)?; + crate::solids::graphics::validate_surface_symbols(doc, p, PlanarFace::Front)?; let faces = vectorcraft_three_d::revolve(path, b, options)?; let mut used = *copies; - match crate::solids::graphics::surface_parts(Some(doc), NodeId(0), &graphics, &faces, &|_, c| Paint::solid(c), &mut used) { + match crate::solids::graphics::surface_parts(Some(doc), NodeId(0), (&graphics, PlanarFace::Front), &faces, &|_, c| Paint::solid(c), &mut used) { Some(_) => { *copies = used; Ok(()) @@ -523,7 +523,7 @@ fn surface( let mut parts = if graphics.is_empty() { vec![] } else { - match crate::solids::graphics::surface_parts(doc, n.id, &graphics, &faces, &shade, &mut used) { + match crate::solids::graphics::surface_parts(doc, n.id, (&graphics, PlanarFace::Front), &faces, &shade, &mut used) { Some(parts) => { copies.graphics = used; parts diff --git a/crates/effects/src/revolve/tests_graphics.rs b/crates/effects/src/revolve/tests_graphics.rs index e21a88a26e..efe469e039 100644 --- a/crates/effects/src/revolve/tests_graphics.rs +++ b/crates/effects/src/revolve/tests_graphics.rs @@ -520,7 +520,8 @@ fn the_copies_of_a_graphics_paint_have_a_budget_of_their_own() { let faces = vectorcraft_three_d::revolve(path, path.bounds().unwrap(), options_of(REVOLVE, &p)).unwrap(); let parts_of = |symbol: &str, copies: &mut usize| { let graphics = crate::solids::mapped_graphics(&json!({"graphics": [{"symbol": symbol}]})); - crate::solids::graphics::surface_parts(Some(&d), NodeId(0), &graphics, &faces, &|_, c| Paint::solid(c), copies).map(|p| p.concat().len()) + crate::solids::graphics::surface_parts(Some(&d), NodeId(0), (&graphics, PlanarFace::Front), &faces, &|_, c| Paint::solid(c), copies) + .map(|p| p.concat().len()) }; // Each opaque part copies the paint into its fill and its seam stroke; a part with // transparent stops takes no seam stroke and copies it once. diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index 2f8d0bf7bd..2bda4dc126 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -30,7 +30,7 @@ pub use graphics::{ }; pub use graphics::{ MAX_OFFSET as GRAPHIC_MAX_OFFSET, NOT_TAKEN as GRAPHICS_NOT_TAKEN, SCALE_RANGE as GRAPHIC_SCALE_RANGE, appearance_graphic_symbols, - rename_appearance_graphic_symbol, + fitting as graphic_fitting_scale, rename_appearance_graphic_symbol, }; pub(crate) mod shadow; @@ -84,11 +84,14 @@ pub fn three_d_params_as(from: &str, params: &Value, to: &str) -> Value { } } // A plane has only a front, and Revolve's graphics go on its side, named the front, so graphics - // on the back cap are dropped. + // on the back cap and on Extrude & Bevel's side are dropped. if (to == ROTATE || to == crate::REVOLVE) && let Some(Value::Array(list)) = out.get_mut(GRAPHICS) { - list.retain(|g| g.get("face").and_then(Value::as_str) != Some(PlanarFace::Back.id())); + list.retain(|g| { + let face = g.get("face").and_then(Value::as_str); + face != Some(PlanarFace::Back.id()) && face != Some(PlanarFace::Side.id()) + }); } Value::Object(out) } @@ -177,6 +180,7 @@ pub fn extrude_options(p: &Value) -> Extrude { both_sides: flag(p, "bevelBothSides", false), }), hidden: false, + map_surface: false, } } @@ -253,6 +257,56 @@ fn facets(id: &str, path: &PathData, rule: FillRule, bounds: Rect, p: &Value) -> } } +/// [`facets`] of Extrude & Bevel with parameters `p`, with the pieces of the side of its longest +/// contour carrying where they lie on it unrolled ([`Facet::surface`]), for its side's graphics. +fn side_facets(path: &PathData, rule: FillRule, bounds: Rect, p: &Value) -> Result, String> { + #[cfg(test)] + SOLID_GEOMETRY_BUILT.with(|n| n.set(n.get() + 1)); + vectorcraft_three_d::extrude(path, rule, bounds, Extrude { map_surface: true, ..extrude_options(p) }, view_options(p)) +} + +/// [`side_facets`], and with `cast` the faces the solid's shadow is cast from, from the same build +/// ([`facets_and_faces`]). +fn side_facets_and_faces(path: &PathData, rule: FillRule, bounds: Rect, p: &Value, cast: bool) -> Result { + if !cast { + return side_facets(path, rule, bounds, p).map(|f| (f, None)); + } + #[cfg(test)] + SOLID_GEOMETRY_BUILT.with(|n| n.set(n.get() + 1)); + let options = Extrude { map_surface: true, ..extrude_options(p) }; + vectorcraft_three_d::extrude_shadowed(path, rule, bounds, options, view_options(p)).map(|(f, faces)| (f, Some(faces))) +} + +/// The part of `parts` ([`solid_parts`]) whose solid takes the graphics on Extrude & Bevel's side, +/// with parameters `p` and built about `bounds`: the first of those with the longest outline +/// ([`vectorcraft_three_d::extrude_side_size`]). `None` when the effect `id` is not Extrude & Bevel +/// or has no graphic on its side, or when no part has a side. +fn side_carrier(id: &str, p: &Value, parts: &[Part<'_>], bounds: Rect) -> Option { + if id != EXTRUDE || !mapped_graphics(p).iter().any(|g| g.face == PlanarFace::Side) { + return None; + } + let options = extrude_options(p); + parts + .iter() + .enumerate() + .filter_map(|(k, (_, _, area, rule, _, _))| vectorcraft_three_d::extrude_side_size(area, *rule, bounds, options).map(|(w, ..)| (k, w))) + .fold(None, |best: Option<(usize, f64)>, (k, w)| if best.is_some_and(|(_, top)| top >= w) { best } else { Some((k, w)) }) + .map(|(k, _)| k) +} + +/// The size of Extrude & Bevel's side unrolled for the graphics on it: the side of the part of +/// `shapes` that [`side_carrier`] picks, with parameters `p`, as wide as the part of it about x = 0 +/// that does not reach its cut and as tall as the length across its bevels and walls. +fn side_size(p: &Value, shapes: &[Profile]) -> Option<(f64, f64)> { + let (parts, bounds) = solid_parts(shapes, union_bounds(shapes)?); + let options = extrude_options(p); + parts + .iter() + .filter_map(|(_, _, area, rule, _, _)| vectorcraft_three_d::extrude_side_size(area, *rule, bounds, options)) + .fold(None, |best: Option<(f64, f64, f64)>, size| if best.is_some_and(|top| top.0 >= size.0) { best } else { Some(size) }) + .map(|(_, height, span)| (span, height)) +} + /// [`facets`], and with `cast` for Extrude & Bevel or Rotate the faces the solid's shadow is cast /// from, from the same build. Inflate's solids are built together ([`built_solids_cast`]), and the /// classic effects cast no shadow: they keep no faces. @@ -339,7 +393,8 @@ fn validate_solid_for(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at: reshape_members(n, before, &mut shapes); let b = union_bounds(&shapes).ok_or_else(|| format!("{label} requires a group holding a shape with at least two anchors"))?; check_profiles(id, p, &shapes, b)?; - return check_solids(id, p, &shapes); + check_solids(id, p, &shapes)?; + return check_side_graphics(doc, n, id, p, &shapes); } let (path, rule) = object_profile(n, label)?; let anchors = || format!("{label} requires a shape with at least two anchors"); @@ -356,7 +411,8 @@ fn validate_solid_for(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at: let b = path.bounds().ok_or_else(anchors)?; let shapes = [Profile { path, rule, items, opacity: 1.0, scopes: vec![] }]; check_profiles(id, p, &shapes, b)?; - check_solids(id, p, &shapes) + check_solids(id, p, &shapes)?; + check_side_graphics(doc, n, id, p, &shapes) } /// Does 3D effect `id` with parameters `p` cast a shadow: is it Extrude & Bevel, Inflate or Rotate @@ -370,6 +426,30 @@ fn visible(item: &AppearanceItem, member: f32) -> bool { paint_of(item, member).1 > 0.0 } +/// An error when the graphics on the side of Extrude & Bevel `id` with parameters `p`, with the +/// symbols of `doc`, are past their limits on the side of the solid of `shapes` that takes them +/// ([`side_carrier`]): their art, or the parts they draw on its pieces +/// ([`graphics::surface_parts`]), or when the object `n`'s surfaces can't be built at all. They are +/// built as the art builds them ([`surfaces_with`]), so its pieces are the ones the art draws, cuts +/// included. Without `doc` nothing is drawn, and nothing is checked. +fn check_side_graphics(doc: Option<&Document>, n: &Node, id: &str, p: &Value, shapes: &[Profile]) -> Result<(), String> { + let Some(doc) = doc else { return Ok(()) }; + let Some(b) = union_bounds(shapes) else { return Ok(()) }; + let (parts, bounds) = solid_parts(shapes, b); + if side_carrier(id, p, &parts, bounds).is_none() { + return Ok(()); + } + graphics::validate_surface_symbols(doc, p, PlanarFace::Side)?; + let fx = Effect { id: id.into(), params: p.clone(), visible: true }; + let mut dropped = false; + // Art that can't be built draws the source path, without the side's graphics. + let built = surfaces_with(Some(doc), n, &fx, shapes, false, &mut dropped); + if dropped || built.is_none() { + return Err("The graphics are too complex: simplify the symbols' art".into()); + } + Ok(()) +} + /// Do the solids 3D effect `id` with parameters `p` builds from the profiles of `shapes` about `b` /// build? Only the profiles no solid of [`check_solids`] is built from are built here: for Rotate /// every shape's, except with its shadow cast that of a shape with a visible fill, whose plane is @@ -414,7 +494,7 @@ fn check_solids(id: &str, p: &Value, shapes: &[Profile]) -> Result<(), String> { if !cast { return built_solids(id, p, &parts, bounds, MAX_OBJECT_FACES).try_for_each(|r| r.map(|_| ())); } - let built = built_solids_cast(id, p, &parts, bounds, MAX_OBJECT_FACES, true) + let built = built_solids_cast(id, p, &parts, bounds, MAX_OBJECT_FACES, true, None) .map(|r| r.map(|solid| solid.and_then(|(_, faces)| faces))) .collect::, String>>()?; cast_built(id, p, shapes, built).map(|_| ()) @@ -688,6 +768,30 @@ fn surface(n: &Node, facets: Vec, paint: &Paint, opacity: f32, blend: Ble group } +/// `surface`, a plain group of one face for each facet ([`surface`]), with each face followed by +/// the parts of the side's graphics that `parts` holds for its facet ([`graphics::surface_parts`]): +/// a face with parts becomes a group of the face and its parts, so nearer faces drawn after it +/// cover them too. `surface` is returned as it is when no facet has a part or it is not such a group. +fn with_side_parts(id: NodeId, mut surface: Node, parts: Vec>>) -> Node { + if parts.iter().all(Vec::is_empty) { + return surface; + } + let NodeKind::Group { children, clip: false } = &mut surface.kind else { return surface }; + if children.len() != parts.len() { + return surface; + } + for (child, extra) in children.iter_mut().zip(parts) { + if extra.is_empty() { + continue; + } + let mut list = Vec::with_capacity(extra.len() + 1); + list.push(child.clone()); + list.extend(extra); + *child = Arc::new(Node::group(id, list)); + } + surface +} + /// The bounds of every facet of `facets` together (`Rect::ZERO` when none has any). pub(crate) fn facets_bounds(facets: &[Facet]) -> Rect { facets.iter().filter_map(|f| f.path().bounds()).reduce(|a, c| a.union(c)).unwrap_or(Rect::ZERO) @@ -802,7 +906,7 @@ fn built_solids<'a>( bounds: Rect, limit: usize, ) -> impl Iterator>, String>> + 'a { - built_solids_cast(id, p, parts, bounds, limit, false).map(|r| r.map(|s| s.map(|(f, _)| f))) + built_solids_cast(id, p, parts, bounds, limit, false, None).map(|r| r.map(|s| s.map(|(f, _)| f))) } /// One solid's facets and, when its shadow is cast, the faces it is cast from. @@ -813,7 +917,9 @@ type CastingSolid = (Vec, Option); type SurfacesAndFaces = (Vec>, Vec>); /// [`built_solids`], and with `cast` for Extrude & Bevel or Inflate each solid's faces its shadow -/// is cast from, from the same build ([`SolidFaces`]). +/// is cast from, from the same build ([`SolidFaces`]). The solid of part `side`, when there is one, +/// is built with the pieces of its side carrying where they lie on it unrolled, for the graphics +/// on Extrude & Bevel's side ([`side_carrier`]). fn built_solids_cast<'a>( id: &'a str, p: &'a Value, @@ -821,6 +927,7 @@ fn built_solids_cast<'a>( bounds: Rect, limit: usize, cast: bool, + side: Option, ) -> impl Iterator, String>> + 'a { // Inflate's eye is placed for every puff together, as far away as the highest needs. let mut inflated = (id == INFLATE).then(|| -> Box>> { @@ -834,7 +941,7 @@ fn built_solids_cast<'a>( }); let mut kept = 0usize; let mut ended = false; - parts.iter().map_while(move |(item, _, area, rule, _, _)| { + parts.iter().enumerate().map_while(move |(k, (item, _, area, rule, _, _))| { if ended { return None; } @@ -846,6 +953,7 @@ fn built_solids_cast<'a>( SOLID_GEOMETRY_BUILT.with(|n| n.set(n.get() + 1)); each.next().unwrap_or_else(|| Ok((vec![], None))) } + None if side == Some(k) => side_facets_and_faces(area, *rule, bounds, p, cast), None => facets_and_faces(id, area, *rule, bounds, p, cast), }; let result = match built { @@ -1098,6 +1206,8 @@ fn cut(s: &Facet, c: &[Point], wall: &Facet, outline: &[Point], turn: f64) -> Op f.depth = s.depth_at(mid).unwrap_or(s.depth); f.contours = vec![points]; f.outline = s.outline.as_ref().and_then(|o| clip_to_side(o, c, &values, sign)); + // A piece keeps where the whole face lies on the side: the parts of the side's graphics + // drawn on it are cut to its own outline ([`graphics::SurfaceFace::curved`]). Some(f) }; Some((piece(1.0)?, piece(-1.0)?)) @@ -1776,6 +1886,12 @@ fn seen_ends(f: &[Facet]) -> impl Iterator { /// solid built also keeps the faces its shadow is cast from, from the same build, in the order the /// solids are built ([`cast_built`]); `None` for a stroke's solid left out of the art. fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile], cast: bool) -> Option { + surfaces_with(doc, n, fx, shapes, cast, &mut false) +} + +/// [`surfaces_for`], setting `side_dropped` when the graphics on Extrude & Bevel's side are past +/// their limits on the pieces drawn, and the solid that takes them draws without them. +fn surfaces_with(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile], cast: bool, side_dropped: &mut bool) -> Option { let b = union_bounds(shapes)?; let p = crate::merged_params(&fx.id, &fx.params); let classic = fx.id == CLASSIC_EXTRUDE || fx.id == CLASSIC_ROTATE; @@ -1818,9 +1934,13 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile return Some((if masks { masked(n.id, out) } else { out.into_iter().map(|(_, s)| s).collect() }, built)); } let (parts, bounds) = solid_parts(shapes, b); + // The graphics on Extrude & Bevel's side go once, on the side of the solid with the longest + // outline, whose pieces are built carrying where they lie on it. + let carrier = if graphics_on { side_carrier(&fx.id, &p, &parts, bounds) } else { None }; let mut solids = vec![]; let mut built = vec![]; - for ((item, opacity, _, _, scopes, member), f) in parts.iter().zip(built_solids_cast(&fx.id, &p, &parts, bounds, MAX_OBJECT_FACES, cast)) { + let made = built_solids_cast(&fx.id, &p, &parts, bounds, MAX_OBJECT_FACES, cast, carrier); + for (k, ((item, opacity, _, _, scopes, member), f)) in parts.iter().zip(made).enumerate() { let item: &AppearanceItem = item; match f { Ok(Some((f, _))) if !crate::revolve::paint_copies_add(&mut paint_bytes, facet_copies(&f, paint_ref(item), colored), paint_ref(item)) => { @@ -1830,8 +1950,12 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile solids.push((item, *opacity, *scopes, f, *member)); built.push(faces); } - // A stroke's outline past the limits is left out; the fill's solid still draws. - Ok(None) => built.push(None), + // A stroke's outline past the limits is left out; the fill's solid still draws, and + // the side's graphics on that outline are not drawn. + Ok(None) => { + built.push(None); + *side_dropped |= carrier == Some(k); + } // A loaded file or a shape edited past the limits (its own, or those of the object's // solids together) keeps drawing its source path instead of failing the frame; // commands validate the same evaluator and report its errors. @@ -1915,6 +2039,9 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile // ([`in_one_order`], [`underlaid_surface`]). let seals: Vec = solids.iter().map(|(.., f, _)| underlaid(f, colored)).collect(); let seal = |range: std::ops::Range| seals.get(range).is_some_and(|s| s.iter().any(|s| *s)); + let side_graphics = carrier.map(|_| mapped_graphics(&p)).unwrap_or_default(); + // The paint copies of the side's graphics, apart from those of the surfaces, as on Revolve. + let mut graphic_copies = 0usize; let surfaces: Vec = solids .into_iter() .map(|(item, member, scopes, f, shape)| { @@ -1922,10 +2049,22 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile let depths: Vec = f.iter().map(|f| Placed::of(f, shape, paints)).collect(); let ends = f.iter().map(|f| f.end.filter(|_| !f.away)).collect(); let (paint, opacity, blend) = paint_of(item, member); + // The carrier's pieces draw the parts of the side's graphics that fall on them; past + // the graphics' limits the solid draws without them. + let parts = if side_graphics.is_empty() || !f.iter().any(|f| f.surface.is_some()) { + vec![] + } else { + let shade = |f: &Facet, c: vectorcraft_doc::color::Color| Paint::solid(crate::lighting::shade(c, f.illumination)); + let parts = graphics::surface_parts(doc, n.id, (&side_graphics, PlanarFace::Side), &f, &shade, &mut graphic_copies); + *side_dropped |= parts.is_none(); + parts.unwrap_or_default() + }; + let drawn = parts.iter().any(|p| !p.is_empty()); let art = if classic { classic::surface(n, f, &paint, opacity, blend, &p) } else { - surface(n, f, &paint, opacity, blend, colored, split && shared.get(shape).copied().unwrap_or(false)) + let faces = drawn || (split && shared.get(shape).copied().unwrap_or(false)); + with_side_parts(n.id, surface(n, f, &paint, opacity, blend, colored, faces), parts) }; (depths, art, scopes, ends) }) @@ -2239,8 +2378,18 @@ pub fn graphics_reshaped_after(n: &Node, item: Option, index: usize) -> b /// Finds a 3D effect in a list of effects, with its index there. type Pick<'p> = dyn for<'e> Fn(&'e [Effect]) -> Option<(usize, &'e Effect)> + 'p; -/// [`graphic_frame`] of the 3D effect `pick` finds in the effects of `n` or its `item`. -fn frame_of(doc: Option<&Document>, n: &Node, item: Option, pick: &Pick<'_>) -> Option { +/// The size of the side unrolled of the Extrude & Bevel at `index` of the effects of `n` (on the +/// object itself with `item` `None`, else on its fill or stroke `item`), that a new graphic on it +/// fits: on the side of its solid with the longest outline, as wide as the part about x = 0 that +/// does not reach the side's cut, and as tall as the length across its bevels and walls. `None` when that effect is not a visible Extrude & Bevel with a +/// depth, or its art can't be built. +pub fn graphic_side_size(doc: Option<&Document>, n: &Node, item: Option, index: usize) -> Option<(f64, f64)> { + let (fx, shapes) = frame_shapes(doc, n, item, &|fx: &[Effect]| fx.get(index).filter(|e| e.visible && e.id == EXTRUDE).map(|e| (index, e)))?; + side_size(&crate::merged_params(&fx.id, &fx.params), &shapes) +} + +/// The 3D effect `pick` finds in the effects of `n` or its `item`, and the shapes it builds from. +fn frame_shapes(doc: Option<&Document>, n: &Node, item: Option, pick: &Pick<'_>) -> Option<(Effect, Vec)> { let n = &*resolve(doc, n, "").ok()?; let (fx, shapes) = if is_container(n) { let (index, fx) = pick(&n.appearance.effects).filter(|_| item.is_none())?; @@ -2264,6 +2413,12 @@ fn frame_of(doc: Option<&Document>, n: &Node, item: Option, pick: &Pick<' } } }; + Some((fx.clone(), shapes)) +} + +/// [`graphic_frame`] of the 3D effect `pick` finds in the effects of `n` or its `item`. +fn frame_of(doc: Option<&Document>, n: &Node, item: Option, pick: &Pick<'_>) -> Option { + let (fx, shapes) = frame_shapes(doc, n, item, pick)?; if !takes_graphics(&fx.id) { return None; } @@ -2289,10 +2444,19 @@ fn frame_of(doc: Option<&Document>, n: &Node, item: Option, pick: &Pick<' let plane = vectorcraft_three_d::plane_face_map(b, view); return Some(graphics::GraphicFrame::new(b, plane, None)); } - let (_, bounds) = solid_parts(&shapes, b); + let (parts, bounds) = solid_parts(&shapes, b); let options = extrude_options(&p); let map = |face| vectorcraft_three_d::extrude_face_map(bounds, options, view, face); - Some(graphics::GraphicFrame::new(bounds, map(PlanarFace::Front), map(PlanarFace::Back))) + let frame = graphics::GraphicFrame::new(bounds, map(PlanarFace::Front), map(PlanarFace::Back)); + // With graphics on the side, the part of it the viewer sees places their handles. + let side = side_carrier(&fx.id, &p, &parts, bounds) + .and_then(|k| parts.get(k)) + .and_then(|(_, _, area, rule, _, _)| side_facets(area, *rule, bounds, &p).ok()) + .map(|facets| graphics::SideFrame::of(&facets)); + Some(match side { + Some(side) => frame.with_side(side), + None => frame, + }) } /// The bounds of the art symbol `name` of `doc` draws as a graphic, in the symbol's coordinates. diff --git a/crates/effects/src/solids/graphics.rs b/crates/effects/src/solids/graphics.rs index 7ef2fe4e28..bf4a71ace7 100644 --- a/crates/effects/src/solids/graphics.rs +++ b/crates/effects/src/solids/graphics.rs @@ -1,6 +1,6 @@ -//! Graphics mapped onto a 3D object's planar faces (Window › 3D and Materials › Materials › -//! Graphics): the art of a document symbol drawn on Extrude & Bevel's front or back cap, or on a -//! plane, turned, foreshortened and shaded with that face and clipped to it. +//! Graphics mapped onto a 3D object's faces (Window › 3D and Materials › Materials › +//! Graphics): the art of a document symbol drawn on Extrude & Bevel's front or back cap or on its +//! side, or on a plane, turned, foreshortened and shaded with that face and clipped to it. //! //! The effect keeps its graphics in its `graphics` parameter, each `{symbol, face, x, y, scale, //! rotation}`: the symbol's name, the face, the offset of the graphic's center from the center of @@ -12,7 +12,10 @@ //! On Revolve the graphics lie on the swept side surface, unrolled flat //! ([`vectorcraft_three_d::SurfaceCell`]): x and y are the offset of the graphic's center from the //! middle of that surface, x around the axis and y along the profile, and each face of the side -//! draws the part of the graphics that falls on it ([`surface_parts`]). +//! draws the part of the graphics that falls on it ([`surface_parts`]). Graphics on Extrude & +//! Bevel's side (face `side`) lie on its walls and bevels unrolled the same way, x along the +//! outline and y from the front toward the back, drawn on the pieces of the side of the solid with +//! the longest outline. use std::sync::Arc; @@ -110,7 +113,7 @@ impl MappedGraphic { }; let face = match m.get("face") { None => PlanarFace::Front, - Some(v) => v.as_str().and_then(PlanarFace::parse).ok_or_else(|| format!("`{GRAPHICS}` face must be front or back"))?, + Some(v) => v.as_str().and_then(PlanarFace::parse).ok_or_else(|| format!("`{GRAPHICS}` face must be front, back or side"))?, }; let number = |key: &str, default: f64, (lo, hi): (f64, f64)| -> Result { match m.get(key) { @@ -139,7 +142,7 @@ impl MappedGraphic { * Affine::scale(self.scale / 100.0) * Affine::translate(-art.center().to_vec2()); match self.face { - PlanarFace::Front => place, + PlanarFace::Front | PlanarFace::Side => place, // Seen from behind, the back's right is the front's left. PlanarFace::Back => { Affine::translate(center.to_vec2()) * Affine::scale_non_uniform(-1.0, 1.0) * Affine::translate(-center.to_vec2()) * place @@ -148,8 +151,8 @@ impl MappedGraphic { } } -/// The 3D effects that take graphics: Extrude & Bevel (its caps), Rotate (the plane) and Revolve -/// (its swept side). +/// The 3D effects that take graphics: Extrude & Bevel (its caps and its side), Rotate (the plane) +/// and Revolve (its swept side). pub fn takes_graphics(id: &str) -> bool { id == super::EXTRUDE || id == super::ROTATE || id == crate::REVOLVE } @@ -165,7 +168,7 @@ pub fn mapped_graphics(p: &Value) -> Vec { /// Are the graphics in parameters `p` of 3D effect `id` valid? Only Extrude & Bevel, Rotate and /// Revolve take graphics; a plane has only a front, and Revolve's graphics go on its side, named -/// the front. +/// the front. Only Extrude & Bevel takes graphics on its side. pub fn validate(id: &str, p: &Value) -> Result<(), String> { let list = match p.get(GRAPHICS) { None => return Ok(()), @@ -183,10 +186,10 @@ pub fn validate(id: &str, p: &Value) -> Result<(), String> { } for v in list { let g = MappedGraphic::from_value(v)?; - if id == super::ROTATE && g.face == PlanarFace::Back { + if id == super::ROTATE && g.face != PlanarFace::Front { return Err("A plane has one face: map its graphics onto the front".into()); } - if id == crate::REVOLVE && g.face == PlanarFace::Back { + if id == crate::REVOLVE && g.face != PlanarFace::Front { return Err("Revolve maps graphics onto its side: map them onto the front".into()); } } @@ -598,14 +601,14 @@ struct Unrolled { place: Affine, } -/// The areas of `graphics` (those of the front: Revolve's side) placed on the unrolled side -/// surface, cut into straight pieces. A graphic whose symbol `doc` does not have, or whose art is -/// past the limits of [`pieces_of`], is left out. `None` when the pieces take more than -/// [`MAX_ELEMENTS`] points together. -fn unrolled(doc: &Document, graphics: &[MappedGraphic]) -> Option> { +/// The areas of `graphics` on `face` (the front, for Revolve's side, or Extrude & Bevel's side) +/// placed on the unrolled side surface, cut into straight pieces. A graphic whose symbol `doc` does +/// not have, or whose art is past the limits of [`pieces_of`], is left out. `None` when the pieces +/// take more than [`MAX_ELEMENTS`] points together. +fn unrolled(doc: &Document, graphics: &[MappedGraphic], face: PlanarFace) -> Option> { let mut pieces = vec![]; let mut points = 0usize; - for g in graphics.iter().filter(|g| g.face == PlanarFace::Front) { + for g in graphics.iter().filter(|g| g.face == face) { let Some(symbol) = doc.symbols.iter().find(|s| s.name == g.symbol) else { continue }; let Ok(art) = pieces_of(doc, symbol) else { continue }; let Some(bounds) = art.iter().filter_map(|p| p.path.bounds()).reduce(|a, b| a.union(b)) else { continue }; @@ -682,38 +685,96 @@ fn straight_pieces(path: &BezPath, points: &mut usize) -> Option> (*points <= MAX_ELEMENTS).then_some(polygons) } -/// Do the graphics in Revolve parameters `p` fit the limits with the symbols of `doc`? Their art, -/// cut into straight pieces on the side surface, may take up to [`MAX_ELEMENTS`] points together. -pub(crate) fn validate_surface_symbols(doc: &Document, p: &Value) -> Result<(), String> { +/// Do the graphics on `face` in parameters `p` (the front of Revolve, Extrude & Bevel's side) fit +/// the limits with the symbols of `doc`? Their art, cut into straight pieces on the side surface, +/// may take up to [`MAX_ELEMENTS`] points together. +pub(crate) fn validate_surface_symbols(doc: &Document, p: &Value, face: PlanarFace) -> Result<(), String> { let list = mapped_graphics(p); - if list.is_empty() || unrolled(doc, &list).is_some() { + if !list.iter().any(|g| g.face == face) || unrolled(doc, &list, face).is_some() { return Ok(()); } Err("The graphics are too complex: simplify the symbols' art".into()) } -/// The parts of `graphics` that fall on each of `faces`, a revolved surface's faces in drawing -/// order, for an object with id `id`: for each face, the nodes to draw right after it. Only faces -/// of the swept side that show their outside to the viewer carry a part, so a graphic narrows -/// toward the silhouette, is hidden past it and is covered by the nearer faces drawn after it. -/// `shade` gives the paint of a solid color on a face, as the surface under it is shaded; the -/// colors of gradients and patterns are multiplied by the face's light. A graphic whose symbol -/// `doc` does not have, or that is past the limits of its art, draws nothing. `None` past -/// [`MAX_ELEMENTS`] points together before they are cut at the faces, [`MAX_SURFACE_POINTS`] -/// after, [`MAX_SURFACE_CUTS`] points cut, or when the copies of their paints in the parts take -/// `copies`, the bytes of the copies of the object's graphics so far, past Revolve's budget for -/// them: commands refuse such graphics, and a loaded file draws the surface without them. -pub(crate) fn surface_parts( +/// A face of a side surface that graphics are drawn on ([`surface_parts`]): a face of Revolve's +/// swept side, or a piece of Extrude & Bevel's walls and bevels. +pub(crate) trait SurfaceFace { + /// Where the face lies on the side unrolled, when it is a face of the side that shows its + /// outside to the viewer. + fn outer_cell(&self) -> Option<&vectorcraft_three_d::SurfaceCell>; + /// The outline the face's parts are cut to, when it is not the polygon of its cell's corners: + /// its curved outline, when its edges along an end are curved, or the outline of a piece cut + /// from a larger face. + fn curved(&self) -> Option>; + fn rgb_light(&self) -> Option; + fn light(&self) -> [f64; 3]; + fn outline_path(&self) -> PathData; +} + +impl SurfaceFace for vectorcraft_three_d::Face { + fn outer_cell(&self) -> Option<&vectorcraft_three_d::SurfaceCell> { + self.surface.as_ref().filter(|c| c.outward && !self.cap) + } + fn curved(&self) -> Option> { + self.outline.as_ref().map(std::borrow::Cow::Borrowed) + } + fn rgb_light(&self) -> Option { + self.rgb_gradient + } + fn light(&self) -> [f64; 3] { + self.illumination + } + fn outline_path(&self) -> PathData { + self.path() + } +} + +impl SurfaceFace for Facet { + fn outer_cell(&self) -> Option<&vectorcraft_three_d::SurfaceCell> { + self.surface.as_ref().filter(|c| c.outward) + } + fn curved(&self) -> Option> { + if let Some(outline) = &self.outline { + return Some(std::borrow::Cow::Borrowed(outline)); + } + // A piece of a stroke's face cut where it passes through a wall keeps its face's cell. + let cut = self.surface.as_ref().is_some_and(|c| self.contours.len() != 1 || self.contours.first() != Some(&c.page)); + cut.then(|| std::borrow::Cow::Owned(self.path())) + } + fn rgb_light(&self) -> Option { + self.rgb_gradient + } + fn light(&self) -> [f64; 3] { + self.illumination + } + fn outline_path(&self) -> PathData { + self.path() + } +} + +/// The parts of the graphics on `face` of `graphics` (the front of Revolve, Extrude & Bevel's side) +/// that fall on each of `faces`, a side surface's faces in drawing order, for an object with id +/// `id`: for each face, the nodes to draw right after it. Only faces of the side that show their +/// outside to the viewer carry a part, so a graphic narrows toward the silhouette, is hidden past +/// it and is covered by the nearer faces drawn after it. `shade` gives the paint of a solid color +/// on a face, as the surface under it is shaded; the colors of gradients and patterns are +/// multiplied by the face's light. A graphic whose symbol `doc` does not have, or that is past the +/// limits of its art, draws nothing. `None` past [`MAX_ELEMENTS`] points together before they are +/// cut at the faces, [`MAX_SURFACE_POINTS`] after, [`MAX_SURFACE_CUTS`] points cut, or when the +/// copies of their paints in the parts take `copies`, the bytes of the copies of the object's +/// graphics so far, past Revolve's budget for them: commands refuse such graphics, and a loaded +/// file draws the surface without them. +pub(crate) fn surface_parts( doc: Option<&Document>, id: NodeId, - graphics: &[MappedGraphic], - faces: &[vectorcraft_three_d::Face], - shade: &dyn Fn(&vectorcraft_three_d::Face, vectorcraft_doc::color::Color) -> Paint, + (graphics, face): (&[MappedGraphic], PlanarFace), + faces: &[F], + shade: &dyn Fn(&F, vectorcraft_doc::color::Color) -> Paint, copies: &mut usize, ) -> Option>>> { let mut out: Vec>> = vec![vec![]; faces.len()]; let Some(doc) = doc else { return Some(out) }; - let pieces = unrolled(doc, graphics)?; + let pieces = unrolled(doc, graphics, face)?; let Some(all) = pieces.iter().map(|p| p.bounds).reduce(|a, b| a.union(b)) else { return Some(out) }; // Each piece listed in the buckets of the surface's x its bounds reach across. let width = (all.width() / SURFACE_BUCKETS as f64).max(1e-9); @@ -729,11 +790,12 @@ pub(crate) fn surface_parts( let mut cut_points = 0usize; let mut triangle_id = 0usize; for (face, parts) in faces.iter().zip(out.iter_mut()) { - let Some(cell) = face.surface.as_ref().filter(|c| c.outward && !face.cap) else { continue }; + let Some(cell) = face.outer_cell() else { continue }; if cell.uv.len() != cell.page.len() || !(3..=4).contains(&cell.uv.len()) { continue; } let triangles: &[[usize; 3]] = if cell.uv.len() == 3 { &[[0, 1, 2]] } else { &[[0, 1, 2], [0, 2, 3]] }; + let curved = face.curved(); for corners in triangles { triangle_id += 1; let pick = |of: &[Point]| corners.iter().map(|k| of.get(*k).copied()).collect::>>(); @@ -744,7 +806,7 @@ pub(crate) fn surface_parts( // where the graphic runs past the end of the profile. A four-cornered face is cut into // two triangles along its diagonal from corner 0 to corner 2: each takes the part of // the outline on its own side of it. - let window = if face.outline.is_some() { grown(window, 3.0) } else { window }; + let window = if curved.is_some() { grown(window, 3.0) } else { window }; // The pieces are looked up over the whole of the window they are cut to. let Some(reach) = window.iter().map(|p| Rect::from_points(*p, *p)).reduce(|a, b| a.union(b)) else { continue }; if reach.x1 < all.x0 || reach.x0 > all.x1 || reach.y1 < all.y0 || reach.y0 > all.y1 { @@ -771,7 +833,7 @@ pub(crate) fn surface_parts( } near.sort_unstable(); let own = corners.iter().find(|k| **k != 0 && **k != 2).and_then(|k| cell.page.get(*k)).filter(|_| triangles.len() == 2); - let rim = face.outline.as_ref().map(|outline| match (own, cell.page.first(), cell.page.get(2)) { + let rim = curved.as_deref().map(|outline| match (own, cell.page.first(), cell.page.get(2)) { (Some(&toward), Some(&a), Some(&b)) => { let side = side_of(a, b, toward); vectorcraft_pathops::boolean(outline, FillRule::NonZero, &side, FillRule::NonZero, vectorcraft_pathops::BoolOp::Intersect) @@ -834,21 +896,21 @@ pub(crate) fn surface_parts( /// The node of the part `path` (on the page, filled under `rule`) of `piece`, which `map` takes /// from the unrolled surface onto `face`. -fn surface_piece( +fn surface_piece( id: NodeId, piece: &Unrolled, (path, rule): (BezPath, FillRule), map: Affine, - face: &vectorcraft_three_d::Face, - shade: &dyn Fn(&vectorcraft_three_d::Face, vectorcraft_doc::color::Color) -> Paint, + face: &F, + shade: &dyn Fn(&F, vectorcraft_doc::color::Color) -> Paint, ) -> Node { let gradient_map = map * piece.place; // Under several lights a face's light varies across it in each channel: a solid color draws // as the face's own lit art in that color, clipped to the part. An opaque part also draws that // art clipped to a band of the seam stroke's width around its edges, as the other parts take // a stroke over their seams. - if let (Some(c), Some(light)) = (piece.paint.color().filter(|_| matches!(piece.paint, Paint::Solid { .. })), face.rgb_gradient) { - let lit = Arc::new(crate::lighting::rgb_gradient_art(id, &face.path(), &Paint::solid(c), light)); + if let (Some(c), Some(light)) = (piece.paint.color().filter(|_| matches!(piece.paint, Paint::Solid { .. })), face.rgb_light()) { + let lit = Arc::new(crate::lighting::rgb_gradient_art(id, &face.outline_path(), &Paint::solid(c), light)); let clipped = |area: &BezPath, rule: FillRule| { let mut clip = Node::path(id, PathData::from_bezpath(area), Appearance::default()); if let NodeKind::Path { rule: r, .. } = &mut clip.kind { @@ -881,7 +943,7 @@ fn surface_piece( match solid { Some(c) => f.paint = shade(face, c), None => { - vectorcraft_doc::recolor::map_paint(&mut f.paint, &|c| crate::lighting::shade(c, face.illumination)); + vectorcraft_doc::recolor::map_paint(&mut f.paint, &|c| crate::lighting::shade(c, face.light())); } } } @@ -996,23 +1058,106 @@ pub(super) fn art_bounds(doc: &Document, name: &str) -> Option { } /// Where a 3D object's graphics are drawn: the bounds its solids are built with (the graphics' -/// offsets are from their center) and the maps of its front and back faces, when it has them. -#[derive(Clone, Copy, Debug, PartialEq)] +/// offsets are from their center), the maps of its front and back faces, when it has them, and +/// the visible part of its side unrolled, when it has graphics there. +#[derive(Clone, Debug, PartialEq)] pub struct GraphicFrame { pub bounds: Rect, front: Option, back: Option, + side: Option, +} + +/// The pieces of Extrude & Bevel's side that show their outside to the viewer, as the graphics are +/// drawn on them ([`surface_parts`]): each piece's corners on the side unrolled and on the page, the +/// outline its parts are cut to when that is not the polygon of its corners, and its depth (larger +/// is nearer). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct SideFrame { + pieces: Vec, +} + +#[derive(Clone, Debug, PartialEq)] +struct SidePiece { + uv: Vec, + page: Vec, + outline: Option, + depth: f64, +} + +impl SideFrame { + /// The pieces of `facets` that carry where they lie on the side unrolled and show its outside. + pub(super) fn of(facets: &[Facet]) -> Self { + let pieces = facets + .iter() + .filter_map(|f| { + let cell = f.outer_cell().filter(|c| c.uv.len() == c.page.len() && (3..=4).contains(&c.uv.len()))?; + let outline = f.curved().map(|o| o.to_bezpath()); + Some(SidePiece { uv: cell.uv.clone(), page: cell.page.clone(), outline, depth: f.depth }) + }) + .collect(); + Self { pieces } + } + + /// Point `p` of the side unrolled mapped onto the page, or with `from_page` a page point mapped + /// onto the side unrolled, through the nearest piece whose drawn part holds it: within the + /// triangle of its corners on the same side of its diagonal from corner 0 to corner 2, grown and + /// cut to its outline as [`surface_parts`] cuts the parts. `None` when no piece holds it. + fn map(&self, p: Point, from_page: bool) -> Option { + let inside = |t: &[Point; 3], q: Point| { + let side = |a: Point, b: Point| (b - a).cross(q - a); + let s = [side(t[0], t[1]), side(t[1], t[2]), side(t[2], t[0])]; + s.iter().all(|v| *v >= -1e-9) || s.iter().all(|v| *v <= 1e-9) + }; + let mut best: Option<(Point, f64)> = None; + for piece in &self.pieces { + let (from, to) = if from_page { (&piece.page, &piece.uv) } else { (&piece.uv, &piece.page) }; + let triangles: &[[usize; 3]] = if from.len() == 3 { &[[0, 1, 2]] } else { &[[0, 1, 2], [0, 2, 3]] }; + for corners in triangles { + let pick = |of: &[Point]| Some([*of.get(corners[0])?, *of.get(corners[1])?, *of.get(corners[2])?]); + let (Some(a), Some(b)) = (pick(from), pick(to)) else { continue }; + let window = if piece.outline.is_some() { grown(a, 3.0) } else { a }; + if !inside(&window, p) { + continue; + } + // A four-cornered piece's two triangles meet along its diagonal: each holds its side. + if triangles.len() == 2 + && let (Some(&d0), Some(&d2), Some(&own)) = (from.first(), from.get(2), from.get(if corners[1] == 1 { 1 } else { 3 })) + { + let across = |q: Point| (d2 - d0).cross(q - d0); + if across(p) * across(own) < 0.0 { + continue; + } + } + let Some(q) = triangle_map(&a, &b).map(|m| m * p).filter(|q| q.is_finite()) else { continue }; + let on_page = if from_page { p } else { q }; + if piece.outline.as_ref().is_some_and(|o| !o.contains(on_page)) { + continue; + } + if best.is_none_or(|(_, depth)| piece.depth > depth) { + best = Some((q, piece.depth)); + } + } + } + best.map(|(q, _)| q) + } } impl GraphicFrame { pub(super) fn new(bounds: Rect, front: Option, back: Option) -> Self { - Self { bounds, front, back } + Self { bounds, front, back, side: None } + } + + /// The frame with the visible part of the side `side`, for its graphics' handles. + pub(super) fn with_side(self, side: SideFrame) -> Self { + Self { side: Some(side), ..self } } pub fn map(&self, face: PlanarFace) -> Option<&FaceMap> { match face { PlanarFace::Front => self.front.as_ref(), PlanarFace::Back => self.back.as_ref(), + PlanarFace::Side => None, } } @@ -1023,23 +1168,34 @@ impl GraphicFrame { match face { PlanarFace::Front => Point::new(c.x + x, c.y + y), PlanarFace::Back => Point::new(c.x - x, c.y + y), + PlanarFace::Side => Point::new(x, y), } } /// Where graphic `g`'s center lands on the page, and whether its face is turned toward the - /// viewer. `None` when the object has no such face or the point has no page point. + /// viewer. `None` when the object has no such face or the point has no page point. A graphic on + /// the side lands where its center is on the part of the side the viewer sees, and is `None` + /// elsewhere. pub fn handle(&self, g: &MappedGraphic) -> Option<(Point, bool)> { + if g.face == PlanarFace::Side { + return Some((self.side.as_ref()?.map(Point::new(g.x, g.y), false)?, true)); + } let map = self.map(g.face)?; Some((map.to_page(self.art_point(g.face, (g.x, g.y)))?, map.visible)) } - /// The offset of a graphic on `face` whose center lands on page point `page`. + /// The offset of a graphic on `face` whose center lands on page point `page`. On the side, only + /// a point on the part of the side the viewer sees has one. pub fn offset_at(&self, face: PlanarFace, page: Point) -> Option<(f64, f64)> { - let art = self.map(face)?.to_art(page)?; + let art = match face { + PlanarFace::Side => self.side.as_ref()?.map(page, true)?, + _ => self.map(face)?.to_art(page)?, + }; let c = self.bounds.center(); let (x, y) = match face { PlanarFace::Front => (art.x - c.x, art.y - c.y), PlanarFace::Back => (c.x - art.x, art.y - c.y), + PlanarFace::Side => (art.x, art.y), }; (x.abs() <= MAX_OFFSET && y.abs() <= MAX_OFFSET).then_some((x, y)) } @@ -1047,11 +1203,17 @@ impl GraphicFrame { /// The scale (percent) at which art with bounds `art` fits inside the object's bounds, at most /// 100: where a newly mapped graphic starts. pub fn fitting_scale(&self, art: Rect) -> f64 { - let fit = (self.bounds.width() / art.width().max(1e-9)).min(self.bounds.height() / art.height().max(1e-9)); - (fit * 100.0).clamp(SCALE_RANGE.0, 100.0) + fitting(self.bounds.width(), self.bounds.height(), art) } } +/// The scale (percent) at which art with bounds `art` fits inside a `width` × `height` area, at +/// most 100. +pub fn fitting(width: f64, height: f64, art: Rect) -> f64 { + let fit = (width / art.width().max(1e-9)).min(height / art.height().max(1e-9)); + (fit * 100.0).clamp(SCALE_RANGE.0, 100.0) +} + /// The symbols the graphics of `n`'s 3D effects name (its own effects and its fills' and strokes'). pub fn graphic_symbols(n: &Node) -> Vec { appearance_graphic_symbols(&n.appearance) @@ -1135,3 +1297,7 @@ pub fn with_graphic(p: &Value, g: &MappedGraphic) -> Value { #[cfg(test)] #[path = "tests_graphics.rs"] mod tests; + +#[cfg(test)] +#[path = "tests_graphics_side.rs"] +mod tests_side; diff --git a/crates/effects/src/solids/tests.rs b/crates/effects/src/solids/tests.rs index 378299d514..b77903714e 100644 --- a/crates/effects/src/solids/tests.rs +++ b/crates/effects/src/solids/tests.rs @@ -774,6 +774,7 @@ fn a_stroke_face_through_a_fill_wall_is_cut_where_their_depths_meet() { side: true, away: false, end: None, + surface: None, plane: Some(DepthPlane { normal, offset, center: Point::ZERO, eye: None }), }; let wall = facet(0.0, [0.0, 0.0, 1.0], 0.0); diff --git a/crates/effects/src/solids/tests_graphics.rs b/crates/effects/src/solids/tests_graphics.rs index fe89dd1f84..92113017f9 100644 --- a/crates/effects/src/solids/tests_graphics.rs +++ b/crates/effects/src/solids/tests_graphics.rs @@ -531,12 +531,13 @@ fn graphics_are_checked() { let n = object(EXTRUDE, json!({})); let check = |id: &str, graphics: Value| validate_three_d_in(None, &n, id, &json!({"graphics": graphics})); assert!(check(EXTRUDE, json!([{"symbol": "Mark", "face": "back", "x": 3.0, "scale": 50.0, "rotation": -90.0}])).is_ok()); + assert!(check(EXTRUDE, json!([{"symbol": "Mark", "face": "side", "x": -40.0, "y": 5.0}])).is_ok()); assert!(check(EXTRUDE, json!([])).is_ok()); for bad in [ json!("Mark"), json!([{"face": "front"}]), json!([{"symbol": ""}]), - json!([{"symbol": "Mark", "face": "side"}]), + json!([{"symbol": "Mark", "face": "top"}]), json!([{"symbol": "Mark", "scale": 0.0}]), json!([{"symbol": "Mark", "rotation": 400.0}]), json!([{"symbol": "Mark", "x": "1"}]), @@ -546,10 +547,12 @@ fn graphics_are_checked() { assert!(check(EXTRUDE, bad.clone()).is_err(), "{bad}"); } assert!(check(ROTATE, json!([{"symbol": "Mark", "face": "back"}])).is_err()); + assert!(check(ROTATE, json!([{"symbol": "Mark", "face": "side"}])).is_err()); assert!(check(INFLATE, json!([{"symbol": "Mark"}])).is_err()); // Revolve takes graphics on its side, named the front; Revolve (Classic) takes none. assert!(validate_three_d_params(crate::REVOLVE, &json!({"graphics": [{"symbol": "Mark"}]})).is_ok()); assert!(validate_three_d_params(crate::REVOLVE, &json!({"graphics": [{"symbol": "Mark", "face": "back"}]})).is_err()); + assert!(validate_three_d_params(crate::REVOLVE, &json!({"graphics": [{"symbol": "Mark", "face": "side"}]})).is_err()); assert!(validate_three_d_params(crate::CLASSIC_REVOLVE, &json!({"graphics": [{"symbol": "Mark"}]})).is_err()); // A loaded file's invalid entries are left out when drawn. assert_eq!(mapped_graphics(&json!({"graphics": [{"symbol": "Mark"}, {"face": "back"}, 3]})).len(), 1); @@ -569,10 +572,13 @@ fn the_frame_at_an_index_is_that_effects() { #[test] fn a_change_to_a_plane_drops_the_back_caps_graphics() { - let p = json!({"graphics": [{"symbol": "Mark", "face": "front"}, {"symbol": "Mark", "face": "back"}]}); + let p = json!({"graphics": [{"symbol": "Mark", "face": "front"}, {"symbol": "Mark", "face": "back"}, {"symbol": "Mark", "face": "side"}]}); let plane = three_d_params_as(EXTRUDE, &p, ROTATE); assert_eq!(plane["graphics"], json!([{"symbol": "Mark", "face": "front"}])); assert!(validate_three_d_params(ROTATE, &plane).is_ok()); + // Revolve drops the side's graphics too; Extrude & Bevel keeps every face's. + assert_eq!(three_d_params_as(EXTRUDE, &p, crate::REVOLVE)["graphics"], json!([{"symbol": "Mark", "face": "front"}])); + assert_eq!(three_d_params_as(EXTRUDE, &p, EXTRUDE)["graphics"], p["graphics"]); // Back to Extrude & Bevel, the front's graphic stays. assert_eq!(three_d_params_as(ROTATE, &plane, EXTRUDE)["graphics"], plane["graphics"]); } diff --git a/crates/effects/src/solids/tests_graphics_side.rs b/crates/effects/src/solids/tests_graphics_side.rs new file mode 100644 index 0000000000..d216ff7d0d --- /dev/null +++ b/crates/effects/src/solids/tests_graphics_side.rs @@ -0,0 +1,255 @@ +//! Graphics on Extrude & Bevel's side: its walls and bevels unrolled flat. + +use serde_json::json; +use vectorcraft_doc::color::Color; +use vectorcraft_doc::{StrokeLayer, Symbol}; +use vectorcraft_geom::shapes; + +use super::super::{EXTRUDE, graphic_frame, graphic_side_size, solid_art_in, validate_three_d_in}; +use super::*; + +fn red() -> Color { + Color::rgb(1.0, 0.0, 0.0) +} + +fn square(id: u64, r: Rect, paint: Paint) -> Node { + Node::path(NodeId(id), shapes::rectangle(r), Appearance::basic(paint, Paint::None, 0.0)) +} + +/// A document with symbol "Mark": a red 10 × 10 square. +fn document() -> Document { + let mut d = Document::new(1000.0, 1000.0); + d.symbols.push(Symbol { + dynamic: false, + name: "Mark".into(), + art: Arc::new(square(0, Rect::new(500.0, 500.0, 510.0, 510.0), Paint::solid(red()))), + }); + d +} + +/// A gray 100 × 100 square at (0, 0), extruded 50 pt, seen from above (its top wall faces the +/// viewer, its front edge at the bottom of the page), with `params` over that. +fn object(params: Value) -> Node { + let mut p = json!({"rotationX": -90.0, "rotationY": 0.0, "rotationZ": 0.0, "shade": false}); + if let (Some(p), Some(extra)) = (p.as_object_mut(), params.as_object()) { + p.extend(extra.clone()); + } + let mut n = square(7, Rect::new(0.0, 0.0, 100.0, 100.0), Paint::solid(Color::rgb(0.5, 0.5, 0.5))); + n.appearance.effects.push(crate::new_effect(EXTRUDE, &p).unwrap()); + n +} + +fn is_red(p: &Paint) -> bool { + p.color().is_some_and(|c| c.to_rgb()[0] > 0.3 && c.to_rgb()[1] < 0.1) +} + +/// The groups of a face and the parts of the side's graphics drawn on it, each part's outline. +fn faces_with_parts(art: &Node) -> Vec> { + let mut out = vec![]; + art.walk(&mut |n| { + if let NodeKind::Group { children, clip: false } = &n.kind + && let Some((face, parts)) = children.split_first() + && matches!(face.kind, NodeKind::Path { .. }) + && !parts.is_empty() + { + let red: Vec = parts + .iter() + .filter(|p| p.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Fill(f) if is_red(&f.paint)))) + .filter_map(|p| p.path_data().cloned()) + .collect(); + if red.len() == parts.len() { + out.push(red); + } + } + }); + out +} + +fn bounds(parts: &[Vec]) -> Rect { + parts.iter().flatten().filter_map(PathData::bounds).reduce(|a, b| a.union(b)).unwrap() +} + +fn near(a: Rect, b: Rect) -> bool { + [(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(p, q)| (p - q).abs() < 1e-6) +} + +/// x runs along the outline from the top's middle, clockwise as the front is seen, and y from the +/// middle of the side toward the back. +#[test] +fn a_side_graphic_lies_on_the_wall_at_its_offset() { + let d = document(); + let n = object(json!({"graphics": [{"symbol": "Mark", "face": "side"}]})); + let art = solid_art_in(Some(&d), &n).unwrap(); + let found = faces_with_parts(&art); + assert_eq!(found.len(), 1, "drawn once, on the top wall"); + // Seen from above, the top wall runs from its front edge (page y 75) to its back (page y 25). + assert!(near(bounds(&found), Rect::new(45.0, 45.0, 55.0, 55.0)), "{:?}", bounds(&found)); + let moved = object(json!({"graphics": [{"symbol": "Mark", "face": "side", "x": 20.0, "y": 10.0, "scale": 200.0}]})); + let found = faces_with_parts(&solid_art_in(Some(&d), &moved).unwrap()); + assert!(near(bounds(&found), Rect::new(60.0, 30.0, 80.0, 50.0)), "{:?}", bounds(&found)); + // Without the document nothing is drawn; a graphic on the side leaves the caps without one. + assert!(faces_with_parts(&solid_art_in(None, &n).unwrap()).is_empty()); +} + +/// A graphic that reaches past a corner runs on around it onto the next wall. +#[test] +fn a_side_graphic_runs_around_a_corner() { + let d = document(); + // x = 50 is the top's right end. + let from_above = object(json!({"graphics": [{"symbol": "Mark", "face": "side", "x": 50.0}]})); + let found = faces_with_parts(&solid_art_in(Some(&d), &from_above).unwrap()); + assert!(near(bounds(&found), Rect::new(95.0, 45.0, 100.0, 55.0)), "only the top's part shows: {:?}", bounds(&found)); + // Turned to show the top and the right, both walls draw their part. + let turned = object(json!({"rotationX": -30.0, "rotationY": -40.0, "graphics": [{"symbol": "Mark", "face": "side", "x": 50.0}]})); + assert_eq!(faces_with_parts(&solid_art_in(Some(&d), &turned).unwrap()).len(), 2); + // Twist and taper carry the graphic; it stays on the side. + let twisted = + object(json!({"rotationX": -30.0, "rotationY": -40.0, "twist": 60.0, "taper": 50.0, "graphics": [{"symbol": "Mark", "face": "side"}]})); + let found = faces_with_parts(&solid_art_in(Some(&d), &twisted).unwrap()); + assert!(!found.is_empty() && found.iter().flatten().all(|p| p.bounds().is_some_and(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite())))); +} + +/// The handle lands where the graphic's center is on the visible side, and a page point there +/// gives back its offset; a graphic on a hidden wall has no handle. +#[test] +fn the_sides_handle_moves_the_graphic_on_its_visible_part() { + let d = document(); + let g = MappedGraphic::from_value(&json!({"symbol": "Mark", "face": "side", "x": 10.0, "y": -5.0})).unwrap(); + let n = object(json!({"graphics": [g.to_value()]})); + let frame = graphic_frame(Some(&d), &n, None).unwrap(); + let (at, visible) = frame.handle(&g).unwrap(); + assert!(visible && at.distance(Point::new(60.0, 55.0)) < 1e-6, "{at:?}"); + let (x, y) = frame.offset_at(PlanarFace::Side, Point::new(40.0, 45.0)).unwrap(); + assert!((x + 10.0).abs() < 1e-6 && (y - 5.0).abs() < 1e-6, "{x} {y}"); + // The bottom's middle, half way around, is hidden from above; so is a page point off the top. + let hidden = MappedGraphic { x: 200.0, ..g.clone() }; + assert!(frame.handle(&hidden).is_none()); + assert!(frame.offset_at(PlanarFace::Side, Point::new(50.0, 90.0)).is_none()); + // Without a graphic on the side, the frame places no handle there. + let caps = graphic_frame(Some(&d), &object(json!({"graphics": [{"symbol": "Mark"}]})), None).unwrap(); + assert!(caps.handle(&g).is_none()); +} + +/// On a curved wall, whose pieces are cut to its curved outline, the handle sits on the graphic's +/// center and a page point there gives back its offset. +#[test] +fn the_handle_follows_a_curved_side() { + let d = document(); + let g = MappedGraphic::from_value(&json!({"symbol": "Mark", "face": "side", "x": 6.0, "y": 3.0})).unwrap(); + let mut n = object(json!({"rotationX": -60.0, "graphics": [g.to_value()]})); + if let NodeKind::Path { path, .. } = &mut n.kind { + *path = shapes::ellipse(Rect::new(0.0, 0.0, 100.0, 100.0)); + } + let frame = graphic_frame(Some(&d), &n, None).unwrap(); + let (at, visible) = frame.handle(&g).unwrap(); + assert!(visible); + let (x, y) = frame.offset_at(PlanarFace::Side, at).unwrap(); + assert!((x - 6.0).abs() < 1e-6 && (y - 3.0).abs() < 1e-6, "{x} {y}"); +} + +/// A hollow object has no caps but takes graphics on its side; a stroke's solid, whose outline is +/// the longest, takes them once. +#[test] +fn a_hollow_or_stroked_object_takes_a_side_graphic() { + let d = document(); + let hollow = object(json!({"cap": false, "graphics": [{"symbol": "Mark", "face": "side"}, {"symbol": "Mark"}]})); + let art = solid_art_in(Some(&d), &hollow).unwrap(); + assert!(near(bounds(&faces_with_parts(&art)), Rect::new(45.0, 45.0, 55.0, 55.0))); + let mut stroked = object(json!({"graphics": [{"symbol": "Mark", "face": "side"}]})); + stroked.appearance.items.push(AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::rgb(0.2, 0.2, 0.2)), 10.0))); + let found = faces_with_parts(&solid_art_in(Some(&d), &stroked).unwrap()); + assert_eq!(found.len(), 1, "on the stroke's outer wall only"); + assert!(near(bounds(&found), Rect::new(45.0, 45.0, 55.0, 55.0)), "{:?}", bounds(&found)); + // The stroke's outer outline is 440 pt long, cut at a bottom corner 165 pt each way from the + // top's middle: a new graphic fits the 330 pt about x = 0 and the depth. + assert_eq!(graphic_side_size(Some(&d), &stroked, None, 0), Some((330.0, 50.0))); +} + +/// A stroke's face cut where it passes through a wall keeps the whole face's place on the side, and +/// each piece draws only the part of the graphic within its own outline. +#[test] +fn a_piece_cut_from_a_face_draws_its_own_part() { + let d = document(); + let facet = |x: f64, normal: [f64; 3], offset: f64| { + let square = vec![Point::new(x, 0.0), Point::new(x + 10.0, 0.0), Point::new(x + 10.0, 10.0), Point::new(x, 10.0)]; + let uv = square.iter().map(|p| Point::new(p.x - x, p.y)).collect(); + Facet { + contours: vec![square.clone()], + depth: 0.0, + brightness: 1.0, + illumination: [1.0; 3], + normal, + rgb_gradient: None, + outline: None, + side: true, + away: false, + end: None, + surface: Some(vectorcraft_three_d::SurfaceCell { page: square, uv, outward: true }), + plane: Some(vectorcraft_three_d::DepthPlane { normal, offset, center: Point::ZERO, eye: None }), + } + }; + let wall = facet(0.0, [0.0, 0.0, 1.0], 0.0); + // z = x - 8: behind the wall left of x = 8, in front of it right of it. + let r = std::f64::consts::FRAC_1_SQRT_2; + let mut stroke = vec![facet(5.0, [-r, 0.0, r], -8.0 * r)]; + super::super::cut_through(std::slice::from_ref(&wall), &mut stroke, &mut 10, &mut 0); + assert_eq!(stroke.len(), 2, "cut where it passes through the wall"); + // The graphic covers the whole face, x 5 to 15 on the page. + let graphics = mapped_graphics(&json!({"graphics": [{"symbol": "Mark", "face": "side", "x": 5.0, "y": 5.0}]})); + let shade = |_: &Facet, c: Color| Paint::solid(c); + let parts = surface_parts(Some(&d), NodeId(0), (&graphics, PlanarFace::Side), &stroke, &shade, &mut 0).unwrap(); + let drawn: Vec = + parts.iter().map(|on| on.iter().filter_map(|n| n.path_data().and_then(PathData::bounds)).reduce(|a, b| a.union(b)).unwrap()).collect(); + // Each piece draws its own side of x = 8 (where the wall cuts it), together the whole graphic. + let (left, right) = (drawn[0].x0.min(drawn[1].x0), drawn[0].x1.max(drawn[1].x1)); + assert!((left - 5.0).abs() < 1e-6 && (right - 15.0).abs() < 1e-6, "{drawn:?}"); + assert!(drawn.iter().all(|b| (b.x0 - 8.0).abs() < 1e-6 || (b.x1 - 8.0).abs() < 1e-6), "{drawn:?}"); +} + +/// Commands refuse a side graphic whose curves, cut into straight pieces on the side, pass the +/// limit of points, though its own path elements are few; on a cap it is accepted. +#[test] +fn a_side_graphic_past_its_limits_is_refused() { + let mut d = document(); + // 200 circles 200,000 pt across: a few elements each, hundreds of thousands of points cut. + let mut subpaths = vec![]; + for k in 0..200 { + let x = f64::from(k); + subpaths.extend(shapes::ellipse(Rect::new(x, 0.0, x + 2e5, 2e5)).subpaths); + } + let rings = Node::path(NodeId(0), PathData::new(subpaths), Appearance::basic(Paint::solid(red()), Paint::None, 0.0)); + d.symbols.push(Symbol { dynamic: false, name: "Rings".into(), art: Arc::new(rings) }); + let n = object(json!({})); + let side = json!({"rotationX": -90.0, "graphics": [{"symbol": "Rings", "face": "side"}]}); + assert!(validate_three_d_in(Some(&d), &n, EXTRUDE, &side).is_err()); + assert!(validate_three_d_in(Some(&d), &n, EXTRUDE, &json!({"rotationX": -90.0, "graphics": [{"symbol": "Rings"}]})).is_ok()); + assert!(validate_three_d_in(Some(&d), &n, EXTRUDE, &json!({"graphics": [{"symbol": "Mark", "face": "side"}]})).is_ok()); +} + +/// With the shadow on, the solid that carries the side's graphics is built once, for both its faces +/// and its shadow: the graphic keeps its place on the wall, and the shadow is the one the object +/// casts without a graphic. +#[test] +fn a_side_graphic_keeps_its_place_with_the_shadow_on() { + let d = document(); + let shadow = |art: &Node| { + let first = &art.children().unwrap()[0]; + let [AppearanceItem::Fill(fill)] = first.appearance.items.as_slice() else { panic!("no shadow first: {first:?}") }; + assert!(fill.paint.color() == Some(Color::BLACK) && (fill.opacity - 0.5).abs() < 1e-6, "{fill:?}"); + first.path_data().and_then(PathData::bounds).unwrap() + }; + let lit = json!({"shade": true, "lightHeight": 90.0, "shadow": true, "shadowDistance": 50.0}); + let mut with_graphic = lit.clone(); + with_graphic["graphics"] = json!([{"symbol": "Mark", "face": "side"}]); + let n = object(with_graphic); + super::super::SOLID_GEOMETRY_BUILT.with(|b| b.set(0)); + super::super::SOLIDS_BUILT.with(|b| b.set(0)); + let art = solid_art_in(Some(&d), &n).unwrap(); + let builds = (super::super::SOLID_GEOMETRY_BUILT.with(std::cell::Cell::get), super::super::SOLIDS_BUILT.with(std::cell::Cell::get)); + assert_eq!(builds, (1, 1), "one build for the faces and the shadow"); + let found = faces_with_parts(&art); + assert_eq!(found.len(), 1, "drawn once, on the top wall"); + assert!(near(bounds(&found), Rect::new(45.0, 45.0, 55.0, 55.0)), "{:?}", bounds(&found)); + let without = solid_art_in(Some(&d), &object(lit)).unwrap(); + assert!(near(shadow(&art), shadow(&without)), "{:?} {:?}", shadow(&art), shadow(&without)); +} diff --git a/crates/effects/src/solids/tests_shadow.rs b/crates/effects/src/solids/tests_shadow.rs index 2d82d571c8..a2d8d03ad9 100644 --- a/crates/effects/src/solids/tests_shadow.rs +++ b/crates/effects/src/solids/tests_shadow.rs @@ -379,7 +379,7 @@ fn a_stroke_left_out_of_the_art_casts_no_shadow() { let p = crate::merged_params(id, &json!({"shadow": true})); let (parts, bounds) = solid_parts(&shapes, union_bounds(&shapes).unwrap()); let mut built: Vec> = - built_solids_cast(id, &p, &parts, bounds, MAX_OBJECT_FACES, true).map(|r| r.unwrap().and_then(|(_, faces)| faces)).collect(); + built_solids_cast(id, &p, &parts, bounds, MAX_OBJECT_FACES, true, None).map(|r| r.unwrap().and_then(|(_, faces)| faces)).collect(); let stroke = parts.iter().position(|(item, ..)| matches!(item, AppearanceItem::Stroke(_))).unwrap(); assert!(built.len() == 2 && built.iter().all(Option::is_some), "{id}"); let (both, _, cast) = cast_built(id, &p, &shapes, built.clone()).unwrap().unwrap(); diff --git a/crates/effects/src/tests.rs b/crates/effects/src/tests.rs index 52b38f986d..2a34fb1d07 100644 --- a/crates/effects/src/tests.rs +++ b/crates/effects/src/tests.rs @@ -1708,6 +1708,115 @@ fn twist_joins_its_pieces_smoothly() { } } +#[test] +fn twist_boundary_handles_follow_the_inward_tangent() { + let line = PathData::single(SubPath::polyline(&[Point::new(40.0, 30.0), Point::new(60.0, 30.0)], false)); + let bounds = Rect::new(40.0, 30.0, 60.0, 30.0); + for angle in [90.0_f64, 400.0, -720.0] { + let out = apply_geometry(&[fx("distort.twist", json!({"angle": angle}))], &line, bounds); + let anchors = &out.subpaths[0].anchors; + let start = anchors.first().unwrap(); + let end = anchors.last().unwrap(); + assert_eq!(start.p, Point::new(40.0, 30.0)); + assert_eq!(end.p, Point::new(60.0, 30.0)); + for (actual, expected) in [ + (start.h_out - start.p, vectorcraft_geom::Vec2::new(1.0, -angle.to_radians())), + (end.h_in - end.p, vectorcraft_geom::Vec2::new(-1.0, angle.to_radians())), + ] { + assert!(actual.hypot() > 1e-9); + let error = (actual.x * expected.y - actual.y * expected.x).atan2(actual.dot(expected)).to_degrees().abs(); + assert!(error < 0.05, "{angle} degrees: boundary tangent differs by {error} degrees"); + } + } +} + +#[test] +fn twist_large_coordinate_joins_preserve_boundary_sides() { + use vectorcraft_geom::Anchor; + + let center = 1e16; + for offset in [32.0, 64.0] { + let p = Point::new(center + offset, 0.0); + let line = PathData::single(SubPath::new( + vec![ + Anchor::corner(Point::new(p.x - 18.0, 0.0)), + Anchor::with_handles(p, Point::new(p.x - 6.0, 0.0), Point::new(p.x + 6.0, 0.0)), + Anchor::corner(Point::new(p.x + 18.0, 0.0)), + ], + false, + )); + let out = crate::distort::twist(&line, Rect::new(center - 64.0, 0.0, center + 64.0, 0.0), 90.0, 3); + let join = &out.subpaths[0].anchors[1]; + if offset == 64.0 { + assert_eq!(join.h_out, Point::new(p.x + 6.0, 0.0)); + let actual = join.h_in - join.p; + let expected = vectorcraft_geom::Vec2::new(-1.0, std::f64::consts::FRAC_PI_2); + let error = actual.cross(expected).atan2(actual.dot(expected)).abs(); + assert!(error < 1e-9, "{actual:?}"); + } else { + let incoming = join.p - join.h_in; + let outgoing = join.h_out - join.p; + assert!(incoming.cross(outgoing).abs() < 1e-9, "{incoming:?} {outgoing:?}"); + assert!(incoming.dot(outgoing) > 0.0); + } + } +} + +#[test] +fn twist_fractional_boundary_handles_use_each_sides_derivative() { + use vectorcraft_geom::Anchor; + + for (bounds, step) in [(Rect::new(40.1, 30.0, 60.3, 30.0), 1.0), (Rect::new(-60.3, 30.0, -40.1, 30.0), 1.0)] { + for x in [bounds.x0, bounds.x1] { + for angle in [90.0_f64, 400.0, -720.0] { + let p = Point::new(x, 30.0); + let line = PathData::single(SubPath::new( + vec![ + Anchor::corner(Point::new(x - 3.0 * step, 30.0)), + Anchor::with_handles(p, Point::new(x - step, 30.0), Point::new(x + step, 30.0)), + Anchor::corner(Point::new(x + 3.0 * step, 30.0)), + ], + false, + )); + let out = crate::distort::twist(&line, bounds, angle, 3); + assert!( + out.subpaths[0].anchors.iter().all(|a| a.p.is_finite() && a.h_in.is_finite() && a.h_out.is_finite()), + "x={x} angle={angle}: {:?}", + out.subpaths[0].anchors + ); + let join = &out.subpaths[0].anchors[1]; + assert!(join.p.distance(p) < 1e-10, "{:?}", join.p); + let a = angle.to_radians(); + let expected = if x == bounds.x0 { [(-1.0, 0.0), (1.0, -a)] } else { [(-1.0, a), (1.0, 0.0)] }; + for (actual, (dx, dy)) in [join.h_in - join.p, join.h_out - join.p].into_iter().zip(expected) { + let expected = vectorcraft_geom::Vec2::new(dx, dy); + let error = actual.cross(expected).atan2(actual.dot(expected)).abs(); + assert!(error < 1e-9, "x={x} angle={angle}: {actual:?}, join={join:?}, source={:?}", line.subpaths[0].anchors[1]); + } + } + } + } + let bounds = Rect::new(1e16, 30.0, 1e16 + 18.0, 30.0); + let center = bounds.center(); + let line = PathData::single(SubPath::polyline(&[Point::new(center.x - 4.0, center.y), center, Point::new(center.x + 4.0, center.y)], false)); + let out = crate::distort::twist(&line, bounds, 90.0, 3); + assert_eq!(out.subpaths[0].anchors[1].p, center); + let bounds = Rect::new(0.0, 30.0, 2e16, 30.0); + let p = Point::new(bounds.x1 - 8.0, 30.0); + let line = PathData::single(SubPath::new( + vec![ + Anchor::corner(Point::new(p.x - 12.0, p.y)), + Anchor::with_handles(p, Point::new(p.x - 4.0, p.y), Point::new(p.x + 4.0, p.y)), + Anchor::corner(Point::new(p.x + 12.0, p.y)), + ], + false, + )); + let out = crate::distort::twist(&line, bounds, 90.0, 3); + let join = &out.subpaths[0].anchors[1]; + assert!(join.p.y - p.y > 10.0, "{:?}", join.p); + assert!(join.h_out.y - join.p.y < -4.0, "{join:?}"); +} + #[test] fn twist_fixes_the_outer_circle_and_rotates_inside() { let out = run("distort.twist", json!({"angle": 0}), &square()); diff --git a/crates/effects/src/tests/clipfx.rs b/crates/effects/src/tests/clipfx.rs index 57566fbb28..d13c59f229 100644 --- a/crates/effects/src/tests/clipfx.rs +++ b/crates/effects/src/tests/clipfx.rs @@ -543,3 +543,337 @@ fn raster_and_hidden_effects_leave_the_clip_as_it_is() { assert_eq!(bounds(&clipping_path(1, effects)), Rect::new(50.0, 50.0, 150.0, 150.0)); } } + +fn blue() -> Paint { + Paint::solid(Color::rgb(0.0, 0.0, 1.0)) +} + +fn green() -> Paint { + Paint::solid(Color::rgb(0.0, 1.0, 0.0)) +} + +/// "IIII" at 40 pt from (5, 60) in a test font built from the bundled Source Sans 3 +/// ([`vectorcraft_text::test_fonts::height_font`]), its characters filled blue when `fill` and +/// stroked green 2 pt wide when `stroke`. +fn painted_type(id: u64, fill: bool, stroke: bool) -> Node { + use vectorcraft_doc::text::{CharStyle, TextObject}; + use vectorcraft_text::test_fonts::{HEIGHT_FAMILY, height_font}; + static FONT: std::sync::Once = std::sync::Once::new(); + FONT.call_once(|| { + vectorcraft_text::FontDb::global().add_font(height_font(true).expect("the test font builds")); + }); + let style = CharStyle { + font_family: HEIGHT_FAMILY.into(), + size: 40.0, + fill: if fill { blue() } else { Paint::None }, + stroke: if stroke { green() } else { Paint::None }, + stroke_width: 2.0, + ..Default::default() + }; + Node::new(NodeId(id), NodeKind::Text(Box::new(TextObject::point(vectorcraft_geom::Point::new(5.0, 60.0), "IIII", style)))) +} + +/// Does `n` or an object in it have a blue fill (`fill`) or a green stroke? +fn paints(n: &Node, fill: bool) -> bool { + use vectorcraft_doc::AppearanceItem; + let own = n.appearance.items.iter().any(|i| match i { + AppearanceItem::Fill(f) => fill && f.paint == blue(), + AppearanceItem::Stroke(s) => !fill && s.paint == green() && s.width > 0.0, + }); + own || n.children().into_iter().flatten().any(|c| paints(c, fill)) +} + +/// What the first clip group in `n` paints: the bounds of the region it clips to, the bounds of +/// the blue fill art right after its clipping path (behind the clipped art), the bounds of the +/// green stroke art right after the clip group (over it, outside the clip), and whether a green +/// stroke paints inside the clip group. +type Painted = (Rect, Option, Option, bool); + +fn painted_clip(n: &Node) -> Option { + let ch = n.children()?; + for (i, c) in ch.iter().enumerate() { + if let NodeKind::Group { children, clip: true } = &c.kind { + let region = clip_outline(children.first()?)?.0.bounding_box(); + let fill = children.get(1).filter(|f| paints(f, true)).and_then(|f| f.geometric_bounds()); + let stroke = ch.get(i + 1).filter(|s| paints(s, false)).and_then(|s| s.geometric_bounds()); + let inside = children.iter().skip(1).any(|m| paints(m, false)); + return Some((region, fill, stroke, inside)); + } + if let Some(found) = painted_clip(c) { + return Some(found); + } + } + None +} + +fn near_rect(a: Rect, b: Rect) -> bool { + (a.x0 - b.x0).abs() < 0.5 && (a.y0 - b.y0).abs() < 0.5 && (a.x1 - b.x1).abs() < 0.5 && (a.y1 - b.y1).abs() < 0.5 +} + +#[test] +fn painted_clipping_type_survives_enclosing_geometry_effect() { + // Type that paints a fill, a stroke, both or neither clips a red square, in a group whose + // Transform (moving everything 10 pt down, beside other type that stays type in the export) or + // Offset Path reshapes its members: the canvas and the export keep the type's fill as art + // behind the square inside the clip and its stroke as art over the clip group, both reshaped + // with the clip. + let plain = clip_outline(&painted_type(3, false, false)).expect("the type clips").0.bounding_box(); + assert!(plain.width() > 10.0 && plain.height() > 10.0, "the type has glyph outlines: {plain:?}"); + let effects = [fx("distort.transform", json!({"moveV": 10})), fx("path.offsetPath", json!({"offset": 1}))]; + for effect in effects { + for (fill, stroke) in [(true, false), (false, true), (true, true), (false, false)] { + let clipped = clip_group(2, painted_type(3, fill, stroke)); + let mut outer = Node::group(NodeId(1), vec![Arc::new(clipped), Arc::new(painted_type(5, true, false))]); + outer.appearance.effects.push(effect.clone()); + let canvas = crate::evaluate_container(None, &outer).unwrap(); + let mut d = Document::new(400.0, 400.0); + let layer = d.layers[0].id; + d.insert(Some(layer), 0, outer).unwrap(); + let baked = bake_document(&d).unwrap(); + let exported = baked.layers.iter().find_map(|l| painted_clip(l)); + for (what, found) in [("canvas", painted_clip(&canvas)), ("export", exported)] { + let case = format!("{what}, {}, fill {fill}, stroke {stroke}", effect.id); + let (region, fills, strokes, inside) = found.unwrap_or_else(|| panic!("{case}: no clip group")); + if effect.id == "distort.transform" { + assert!((region.y0 - plain.y0 - 10.0).abs() < 0.5 && (region.x0 - plain.x0).abs() < 0.5, "{case}: {region:?} from {plain:?}"); + } else { + let grown = Rect::new(plain.x0 - 1.0, plain.y0 - 1.0, plain.x1 + 1.0, plain.y1 + 1.0); + assert!(near_rect(region, grown), "{case}: {region:?} is {plain:?} offset by 1 pt"); + } + assert_eq!(fills.is_some(), fill, "{case}: fill art {fills:?}"); + assert_eq!(strokes.is_some(), stroke, "{case}: stroke art {strokes:?}"); + assert!(!inside, "{case}: the stroke paints outside the clip"); + for art in fills.into_iter().chain(strokes) { + assert!(near_rect(art, region), "{case}: the paint {art:?} follows the clip {region:?}"); + } + } + } + } +} + +/// The group in `n` that holds a clip group and then the green stroke art of its clipping type, +/// with that clip group. +fn stroke_wrapper(n: &Node) -> Option<(&Node, &Node)> { + let ch = n.children()?; + if let [inner, stroke, ..] = ch.as_slice() + && matches!(inner.kind, NodeKind::Group { clip: true, .. }) + && !n.clips() + && paints(stroke, false) + { + return Some((n, inner)); + } + ch.iter().find_map(|c| stroke_wrapper(c)) +} + +#[test] +fn clipping_type_strokes_paint_over_a_knockout_clip_group() { + // A clip group set to Knockout Group On, Off or neutral, clipped by type that strokes: its + // clipped art knocks out as the clip group says, and the type's stroke paints over it without + // knocking it out, as the canvas draws the live clip group. The type is reshaped by a group's + // Transform around it, or by its own Offset Path. + use vectorcraft_doc::Knockout; + for (knockout, around) in [(Knockout::On, Knockout::Off), (Knockout::Off, Knockout::Off), (Knockout::Neutral, Knockout::Neutral)] { + for own in [false, true] { + let mut ty = painted_type(3, true, true); + if own { + ty.appearance.effects.push(fx("path.offsetPath", json!({"offset": 1}))); + } + let mut clipped = clip_group(2, ty); + clipped.knockout = knockout; + let mut outer = Node::group(NodeId(1), vec![Arc::new(clipped)]); + if !own { + outer.appearance.effects.push(fx("distort.transform", json!({"moveV": 10}))); + } + let mut d = Document::new(400.0, 400.0); + let layer = d.layers[0].id; + d.insert(Some(layer), 0, outer.clone()).unwrap(); + let baked = bake_document(&d).unwrap(); + let canvas = if own { None } else { crate::evaluate_container(None, &outer) }; + let exported = baked.layers.iter().find_map(|l| stroke_wrapper(l)); + for (what, found) in [("canvas", canvas.as_ref().and_then(stroke_wrapper)), ("export", exported)] { + if own && what == "canvas" { + continue; + } + let case = format!("{what}, own effect {own}, knockout {knockout:?}"); + let (wrapper, inner) = found.unwrap_or_else(|| panic!("{case}: no group around the clip")); + assert_eq!(inner.knockout, knockout, "{case}: the clipped art knocks out as before"); + assert_eq!(wrapper.knockout, around, "{case}: the stroke does not knock out the clipped art"); + } + } + } +} + +#[test] +fn a_clip_groups_own_fill_stays_in_the_clip_when_its_clipping_type_strokes() { + // A clip group with a yellow fill of its own and an Offset Path effect, clipped by type that + // strokes: the group's fill still paints inside the clip, and the type's stroke over it. + let yellow = Paint::solid(Color::rgb(1.0, 1.0, 0.0)); + let mut group = clip_group(2, painted_type(3, false, true)); + group.appearance = + Appearance { effects: vec![fx("path.offsetPath", json!({"offset": 0}))], ..Appearance::basic(yellow.clone(), Paint::None, 0.0) }.into(); + let canvas = crate::evaluate_container(None, &group).unwrap(); + let (_, _, strokes, inside) = painted_clip(&Node::group(NodeId(9), vec![Arc::new(canvas.clone())])).unwrap(); + assert!(strokes.is_some() && !inside, "{canvas:?}"); + let NodeKind::Group { children, clip: false } = &canvas.kind else { panic!("not a group around the clip: {canvas:?}") }; + let NodeKind::Group { children: clipped, clip: true } = &children[0].kind else { panic!("no clip group first: {children:?}") }; + let yellow_in = |n: &Node| n.appearance.items.iter().any(|i| matches!(i, vectorcraft_doc::AppearanceItem::Fill(f) if f.paint == yellow)); + assert!(clipped.iter().skip(1).any(|c| yellow_in(c)), "the group's fill paints inside the clip: {clipped:?}"); + assert!(!children.iter().skip(1).any(|c| yellow_in(c)), "{children:?}"); +} + +#[test] +fn a_clip_groups_own_gradient_spans_the_clip_when_its_clipping_type_strokes() { + // A clip group with an unplaced linear gradient fill of its own and an Offset Path effect, + // clipped by type with a stroke whose Transform effect moves it 60 pt right: the gradient + // spans the region the clipping path clips to. + use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop}; + let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::WHITE)]; + let unplaced = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops)))); + let mut ty = painted_type(3, false, false); + ty.appearance = Appearance::basic(Paint::None, green(), 2.0).into(); + for item in &mut ty.appearance.items { + if let vectorcraft_doc::AppearanceItem::Stroke(s) = item { + s.effects.push(fx("distort.transform", json!({"moveH": 60}))); + } + } + let mut group = clip_group(2, ty); + group.appearance = + Appearance { effects: vec![fx("path.offsetPath", json!({"offset": 0}))], ..Appearance::basic(unplaced, Paint::None, 0.0) }.into(); + let canvas = crate::evaluate_container(None, &group).unwrap(); + let NodeKind::Group { children, clip: false } = &canvas.kind else { panic!("not a group around the clip: {canvas:?}") }; + let NodeKind::Group { children: clipped, clip: true } = &children[0].kind else { panic!("no clip group first: {children:?}") }; + let region = clip_outline(&clipped[0]).expect("the type clips").0.bounding_box(); + let fill = clipped.iter().skip(1).find_map(|c| match c.appearance.fill_paint() { + Paint::Gradient(g) => g.geom, + _ => None, + }); + let geom = fill.unwrap_or_else(|| panic!("no gradient fill inside the clip: {clipped:?}")); + let (left, right) = (geom.start.x.min(geom.end.x), geom.start.x.max(geom.end.x)); + assert!((left - region.x0).abs() < 0.5 && (right - region.x1).abs() < 0.5, "the gradient {geom:?} spans the clip {region:?}"); +} + +#[test] +fn a_groups_own_fill_paints_only_the_clip_of_clipping_type_whose_stroke_moves() { + // A group with a fill of its own (solid, or an unplaced linear gradient) and a Transform effect + // (moving everything 10 pt down, or scaling it to half its width around its middle) holds a + // clip group clipped by type whose stroke has a Transform effect moving it 60 pt right, + // outside the clip. On the canvas and in the export, the clip region is the type's glyphs + // reshaped by the group's effect, and the group's fill paints that region alone, its gradient + // spanning it: the moved stroke adds nothing to the region, the fill or the box the group's + // effect scales around. + use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop}; + let yellow = Paint::solid(Color::rgb(1.0, 1.0, 0.0)); + let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::WHITE)]; + let unplaced = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops)))); + let mut ty = painted_type(3, false, false); + ty.appearance = Appearance::basic(Paint::None, green(), 2.0).into(); + for item in &mut ty.appearance.items { + if let vectorcraft_doc::AppearanceItem::Stroke(s) = item { + s.effects.push(fx("distort.transform", json!({"moveH": 60}))); + } + } + let live = clip_outline(&ty).expect("the type clips").0.bounding_box(); + let moved = Rect::new(live.x0, live.y0 + 10.0, live.x1, live.y1 + 10.0); + // Scaled to half its width around the middle of the clip, which the stroke does not move. + let (mid, quarter) = ((live.x0 + live.x1) / 2.0, live.width() / 4.0); + let narrowed = Rect::new(mid - quarter, live.y0, mid + quarter, live.y1); + // The group's own fill art: every object outside the clip groups whose own fill is `paint`. + fn own_fills<'a>(n: &'a Node, paint: &Paint, out: &mut Vec<&'a Node>) { + let mine = n.appearance.items.iter().any(|i| match (i, paint) { + (vectorcraft_doc::AppearanceItem::Fill(f), Paint::Gradient(_)) => matches!(f.paint, Paint::Gradient(_)), + (vectorcraft_doc::AppearanceItem::Fill(f), p) => f.paint == *p, + _ => false, + }); + if mine { + out.push(n); + } + for c in n.children().into_iter().flatten().filter(|c| !c.clips()) { + own_fills(c, paint, out); + } + } + let cases = [(json!({"moveV": 10}), moved), (json!({"scaleH": 50, "scaleV": 100}), narrowed)]; + for ((params, region), paint) in cases.iter().flat_map(|c| [yellow.clone(), unplaced.clone()].map(|p| (c.clone(), p))) { + let mut outer = Node::group(NodeId(1), vec![Arc::new(clip_group(2, ty.clone()))]); + outer.appearance = + Appearance { effects: vec![fx("distort.transform", params.clone())], ..Appearance::basic(paint.clone(), Paint::None, 0.0) }.into(); + let canvas = crate::evaluate_container(None, &outer).unwrap(); + let mut d = Document::new(400.0, 400.0); + let layer = d.layers[0].id; + d.insert(Some(layer), 0, outer).unwrap(); + let baked = bake_document(&d).unwrap(); + let exported = baked.layers[0].children().and_then(|ch| ch.first()).cloned().expect("the export holds the group"); + for (what, art) in [("canvas", &canvas), ("export", &*exported)] { + let case = format!("{what}, {params}, {}", if matches!(paint, Paint::Gradient(_)) { "gradient" } else { "solid" }); + let (clip, _, strokes, _) = painted_clip(art).unwrap_or_else(|| panic!("{case}: no clip group in {art:?}")); + assert!(near_rect(clip, region), "{case}: the clip {clip:?} is the type's glyphs reshaped {region:?}"); + let strokes = strokes.unwrap_or_else(|| panic!("{case}: no stroke art")); + assert!(strokes.x1 > region.x1 + 25.0, "{case}: the stroke {strokes:?} moves outside the clip {region:?}"); + let mut fills = vec![]; + own_fills(art, &paint, &mut fills); + assert!(!fills.is_empty(), "{case}: no fill art of the group in {art:?}"); + let painted = fills.iter().filter_map(|f| f.geometric_bounds()).reduce(|a, b| a.union(b)).unwrap(); + assert!(near_rect(painted, region), "{case}: the group's fill {painted:?} paints the clip {region:?}"); + if let Paint::Gradient(_) = paint { + for fill in fills { + let geom = match fill.appearance.fill_paint() { + Paint::Gradient(g) => g.geom, + _ => None, + }; + let geom = geom.unwrap_or_else(|| panic!("{case}: the gradient is not placed: {fill:?}")); + let (left, right) = (geom.start.x.min(geom.end.x), geom.start.x.max(geom.end.x)); + assert!( + (left - region.x0).abs() < 0.5 && (right - region.x1).abs() < 0.5, + "{case}: the gradient {geom:?} spans the clip {region:?}" + ); + } + } + } + } +} + +#[test] +fn a_clip_groups_placed_gradient_follows_free_distort_by_the_clip_when_its_clipping_type_strokes() { + // A clip group with a placed linear gradient fill of its own, in a group with Free Distort, + // clipped by type whose stroke has a Transform effect moving it 60 pt right, outside the clip: + // the gradient moves and scales from the clip's bounds, as for the same clip group whose type + // does not stroke. The moved stroke adds nothing to those bounds. + use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop}; + let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::WHITE)]; + let ramp = GradientPaint::new(Gradient::new(GradientKind::Linear, stops)); + let geom = GradientGeom { start: (10.0, 45.0).into(), end: (30.0, 45.0).into(), aspect: 1.0, focal: None }; + let placed = Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..ramp })); + fn placed_geom(n: &Node) -> Option { + if let Paint::Gradient(g) = n.appearance.fill_paint() + && g.geom.is_some() + { + return g.geom; + } + n.children().into_iter().flatten().find_map(|c| placed_geom(c)) + } + let ends = |stroke: bool| { + let mut ty = painted_type(3, false, false); + if stroke { + ty.appearance = Appearance::basic(Paint::None, green(), 2.0).into(); + for item in &mut ty.appearance.items { + if let vectorcraft_doc::AppearanceItem::Stroke(s) = item { + s.effects.push(fx("distort.transform", json!({"moveH": 60}))); + } + } + } + let mut group = clip_group(2, ty); + group.appearance = Appearance::basic(placed.clone(), Paint::None, 0.0).into(); + let mut outer = Node::group(NodeId(1), vec![Arc::new(group)]); + let corners = json!({"corners": [[1.0 / 3.0, 0.0], [4.0 / 3.0, 0.0], [1.0, 1.0], [0.0, 1.0]]}); + outer.appearance.effects.push(fx("distort.freeDistort", corners)); + let canvas = crate::evaluate_container(None, &outer).unwrap(); + if stroke { + assert!(stroke_wrapper(&canvas).is_some(), "the type's stroke paints around the clip: {canvas:?}"); + } + placed_geom(&canvas).unwrap_or_else(|| panic!("no placed gradient: {canvas:?}")) + }; + let (plain, stroked) = (ends(false), ends(true)); + assert!( + plain.start.distance(stroked.start) < 0.5 && plain.end.distance(stroked.end) < 0.5, + "the gradient {stroked:?} follows the clip as {plain:?} does" + ); +} diff --git a/crates/effects/src/util.rs b/crates/effects/src/util.rs index de203b4955..6b79d19999 100644 --- a/crates/effects/src/util.rs +++ b/crates/effects/src/util.rs @@ -71,7 +71,7 @@ pub fn seg_cubic(sp: &SubPath, i: usize) -> CubicBez { /// Non-linear path mapping (shared with live envelopes in `vectorcraft-doc`), and the split of /// segments into pieces within an anchor budget. -pub use vectorcraft_doc::live::{fit_piece, map_nonlinear_within, map_smooth_within, pieces}; +pub use vectorcraft_doc::live::{fit_piece, map_handles_within, map_nonlinear_within, pieces}; /// About how many lines the renderer flattens `path` into at 1 px/pt: one for a straight /// segment, and for a curve the count Wang's formula gives at vello's tolerance of 0.25 px, diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 4e07b323c1..a8209b9b42 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -59,6 +59,9 @@ chrono = { workspace = true } craft-xml = { workspace = true } # The compound file that holds a Word 97-2003 document placed as type (place/doc.rs). cfb = "0.15" +# The Text Import Options character sets other than Unicode and ANSI (place/text.rs). Already in +# Cargo.lock (vectorcraft-eps), so this adds no new crate. +encoding_rs = { workspace = true } kurbo = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } @@ -70,8 +73,9 @@ log = { workspace = true } [target.'cfg(unix)'.dependencies] rustix = { workspace = true, features = ["std", "process"] } -# Whether a recovery area's lock file is still the one that was opened (`FolderStore::still_named`). -# Already in Cargo.lock (walkdir), so this adds no new crate. +# Whether a recovery area's lock file is still the one that was opened (`FolderStore::still_named`), +# and whether two paths a script names are one file (`script::files`). Already in Cargo.lock +# (walkdir), so this adds no new crate. [target.'cfg(windows)'.dependencies] same-file = "1.0.6" diff --git a/crates/engine/examples/layer_select_bench.rs b/crates/engine/examples/layer_select_bench.rs new file mode 100644 index 0000000000..256cada3af --- /dev/null +++ b/crates/engine/examples/layer_select_bench.rs @@ -0,0 +1,154 @@ +//! `cargo run --release -p vectorcraft-engine --example layer_select_bench` prints the time of a +//! Shift-click in the Layers panel's selection column (`layer.selectAll {id, add: true}`) on a layer of +//! 2,000, 20,000 and 50,000 rectangles, with all of its art selected (the click removes it) and with +//! every other object selected (the click adds the rest). Each case is timed one id at a time (`old`, +//! the loop the command used before, copied here) and in one pass (`new`), side by side in one +//! process: first the whole command, then the selection step alone. Each case checks that both give +//! the same selection and reply before it is timed. +//! `ITERS` sets the runs per case (default 7); each row is the median wall time in ms, followed by +//! every run of `old` and of `new`. +// Example (dev tool): unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::collections::HashSet; +use std::hint::black_box; +use std::time::Instant; + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, Document, Node, NodeId, Selection}; +use vectorcraft_engine::Session; +use vectorcraft_geom::{Anchor, PathData, Point, SubPath}; + +fn iters() -> usize { + std::env::var("ITERS").ok().and_then(|v| v.parse().ok()).unwrap_or(7).max(1) +} + +fn median(ms: &[f64]) -> f64 { + let mut ms = ms.to_vec(); + ms.sort_by(f64::total_cmp); + ms[ms.len() / 2] +} + +/// A document whose first layer holds `n` 10 pt squares in a row → (document, layer, squares). +fn squares(n: usize) -> (Document, NodeId, Vec) { + let mut doc = Document::new(1600.0, 1200.0); + let layer = doc.layers[0].id; + let ids = (0..n) + .map(|i| { + let (x, y) = ((i % 100) as f64 * 12.0, (i / 100) as f64 * 12.0); + let corners = [(x, y), (x + 10.0, y), (x + 10.0, y + 10.0), (x, y + 10.0)]; + let path = PathData::single(SubPath::new(corners.iter().map(|&(x, y)| Anchor::corner(Point::new(x, y))).collect(), true)); + let id = doc.alloc_id(); + doc.insert(Some(layer), usize::MAX, Node::path(id, path, Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 1.0))).unwrap(); + id + }) + .collect(); + (doc, layer, ids) +} + +/// `layer.selectAll {id: layer, add: true}` before the change: the layer's art checked, removed or +/// added one id at a time with [`Selection::contains`], [`Selection::remove`] and [`Selection::add`]. +fn old_command(s: &mut Session, layer: NodeId) -> Value { + let st = s.doc().unwrap(); + let ids = st.doc.node(layer).unwrap().layer_art(true); + let all_selected = !ids.is_empty() && ids.iter().all(|i| st.selection.contains(*i)); + let rows = st.layer_rows.clone(); + s.select(|_, sel| old_step(sel, &ids, all_selected)).unwrap(); + let st = s.doc_mut().unwrap(); + st.layer_rows = rows; + json!({ "selected": st.selection.objects.iter().map(|i| i.0).collect::>() }) +} + +fn old_step(sel: &mut Selection, ids: &[NodeId], all_selected: bool) { + for i in ids { + if all_selected { sel.remove(*i) } else { sel.add(*i) } + } +} + +fn new_command(s: &mut Session, layer: NodeId) -> Value { + s.execute("layer.selectAll", &json!({"id": layer.0, "add": true})).unwrap() +} + +/// Every run of `old` and of `new`, run in turn, each from `prepare`'s state. +fn time(mut prepare: impl FnMut() -> S, old: impl Fn(&mut S), new: impl Fn(&mut S)) -> (Vec, Vec) { + let run = |s: &mut S, f: &dyn Fn(&mut S)| { + let t = Instant::now(); + f(s); + t.elapsed().as_secs_f64() * 1000.0 + }; + let (mut olds, mut news) = (Vec::new(), Vec::new()); + for _ in 0..iters() { + let mut s = prepare(); + olds.push(run(&mut s, &old)); + black_box(&s); + let mut s = prepare(); + news.push(run(&mut s, &new)); + black_box(&s); + } + (olds, news) +} + +fn row(name: &str, (old, new): (Vec, Vec)) { + let (o, n) = (median(&old), median(&new)); + let list = |ms: &[f64]| ms.iter().map(|m| format!("{m:.2}")).collect::>().join(" "); + println!(" {name:<40} {o:>12.3} ms {n:>12.3} ms {:>9.1}x", o / n.max(1e-9)); + println!(" old runs: {}", list(&old)); + println!(" new runs: {}", list(&new)); +} + +fn main() { + println!(" {:<40} {:>15} {:>15} {:>10}", "case", "old", "new", "speedup"); + for n in [2_000usize, 20_000, 50_000] { + println!("{n} objects"); + let (doc, layer, ids) = squares(n); + let mut s = Session::new(); + s.add_document(doc, None); + let mut all = Selection::default(); + all.set(ids.iter().copied()); + let mut half = Selection::default(); + half.set(ids.iter().copied().step_by(2)); + for (name, start) in [("all selected (removes)", &all), ("half selected (adds)", &half)] { + let reset = |s: &mut Session| { + let st = s.doc_mut().unwrap(); + st.selection = start.clone(); + st.layer_rows.clear(); + }; + // Both ways give the same selection and reply. + reset(&mut s); + let old_reply = old_command(&mut s, layer); + let old_sel = s.doc().unwrap().selection.clone(); + reset(&mut s); + let new_reply = new_command(&mut s, layer); + assert_eq!(s.doc().unwrap().selection, old_sel, "{name}: the same selection"); + assert_eq!(new_reply, old_reply, "{name}: the same reply"); + + let (mut olds, mut news) = (Vec::new(), Vec::new()); + for _ in 0..iters() { + for (f, ms) in [(old_command as fn(&mut Session, NodeId) -> Value, &mut olds), (new_command, &mut news)] { + reset(&mut s); + let t = Instant::now(); + black_box(f(&mut s, layer)); + ms.push(t.elapsed().as_secs_f64() * 1000.0); + } + } + row(&format!("command, {name}"), (olds, news)); + // The selection step alone, on a copy of the starting selection. + let art = s.doc().unwrap().doc.node(layer).unwrap().layer_art(true); + let selected: HashSet = start.objects.iter().copied().collect(); + let all_selected = art.iter().all(|i| selected.contains(i)); + let new_step = |sel: &mut Selection| { + if all_selected { + sel.remove_all(art.iter().copied()); + } else { + sel.add_all(art.iter().copied()); + } + }; + let (mut a, mut b) = (start.clone(), start.clone()); + old_step(&mut a, &art, all_selected); + new_step(&mut b); + assert_eq!(a, b, "{name}: the same selection step"); + row(&format!("selection step, {name}"), time(|| start.clone(), |sel| old_step(sel, &art, all_selected), new_step)); + } + } +} diff --git a/crates/engine/examples/link_colors_bench.rs b/crates/engine/examples/link_colors_bench.rs new file mode 100644 index 0000000000..d403339706 --- /dev/null +++ b/crates/engine/examples/link_colors_bench.rs @@ -0,0 +1,217 @@ +//! `cargo run --release -p vectorcraft-engine --example link_colors_bench` prints the time +//! `Document::map_solid_paints_in` takes to link the paints of selected objects to swatches, as Add Used +//! Colors and New Color Group do for the selection with global swatches, on synthetic documents: 2,000 and +//! 20,000 rectangles in one layer, and 5,000 rectangles in 1,000 groups of groups, selected with and +//! without the groups that hold them. The fills and strokes use 50 colors, each with a swatch to link to. +//! For each it times two ways of finding the selected objects that no other selected object holds: a +//! search of the id list for each ancestor of each id, and a lookup of each ancestor in a set of the ids +//! (as `map_solid_paints_in` does). Both then link the same paints in the same loop. It checks that both +//! give the same count, visit the same paints in the same order and leave the same document as +//! `map_solid_paints_in` before it times them. +//! `ITERS` sets the runs per row (default 7); the two ways run in alternating order, each run links 10 +//! fresh copies of the document, and each row is the median time of one call. On Linux the times are the CPU time of the main thread, which runs +//! everything, in ms; elsewhere they are wall times. +// Example (dev tool): unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::collections::{HashMap, HashSet}; +use std::hint::black_box; +use std::sync::Arc; +use std::time::Instant; + +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::swatches::{LinkFn, map_node_solid_paints}; +use vectorcraft_doc::{Appearance, Document, Node, NodeId}; +use vectorcraft_geom::{Rect, shapes}; + +/// The colors the rectangles use, each with a swatch to link to. +const COLORS: usize = 50; + +/// The calls in each timed run; a row gives the time of one call. +const REPS: usize = 10; + +/// A way of finding the ids that no other listed id holds. +type Roots = fn(&Document, &[NodeId]) -> Vec; + +/// A way of applying a link function to the paints of the listed ids, returning the count changed. +type Map<'a> = dyn FnMut(&mut Document, &[NodeId], &mut LinkFn) -> usize + 'a; + +fn iters() -> usize { + std::env::var("ITERS").ok().and_then(|v| v.parse().ok()).unwrap_or(7).max(1) +} + +fn median(mut ms: Vec) -> f64 { + ms.sort_by(f64::total_cmp); + ms[ms.len() / 2] +} + +/// The CPU time of the calling thread in ns, from `/proc/thread-self/schedstat` (Linux only). +fn thread_cpu_ns() -> Option { + std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok() +} + +/// The time `f` takes, in ms: CPU time where the system reports it, wall time otherwise. +fn measure(f: impl FnOnce()) -> f64 { + match thread_cpu_ns() { + Some(start) => { + f(); + thread_cpu_ns().map_or(f64::NAN, |end| end.saturating_sub(start) as f64 / 1e6) + } + None => { + let t = Instant::now(); + f(); + t.elapsed().as_secs_f64() * 1000.0 + } + } +} + +/// Color `i` of [`COLORS`]: each has its own red value. +fn color(i: usize) -> Color { + Color::rgb(i as f32 / COLORS as f32, 0.5, 0.25) +} + +/// The bits of a color's red value, which tell the colors of [`color`] apart; `u32::MAX` for other color models. +fn red_bits(c: &Color) -> u32 { + match c { + Color::Rgb { r, .. } => r.to_bits(), + _ => u32::MAX, + } +} + +/// The ids in the order given, less those with an ancestor in the list: a search of the list for each ancestor. +fn roots_by_search(d: &Document, ids: &[NodeId]) -> Vec { + ids.iter().copied().filter(|id| !d.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| ids.contains(p)))).collect() +} + +/// [`roots_by_search`] with each ancestor looked up in a set of the ids. +fn roots_by_set(d: &Document, ids: &[NodeId]) -> Vec { + let listed: HashSet = ids.iter().copied().collect(); + ids.iter().copied().filter(|id| !d.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| listed.contains(p)))).collect() +} + +/// `f` applied to the paints of the subtrees of the ids `roots` finds, each node holding a changed +/// paint put in place: the work of `map_solid_paints_in`. +fn map_in(d: &mut Document, ids: &[NodeId], roots: Roots, f: &mut LinkFn) -> usize { + let mut n = 0; + for id in roots(d, ids) { + let Some(mut node) = d.node(id).cloned() else { continue }; + let count = map_node_solid_paints(&mut node, f); + if count > 0 + && let Some(slot) = d.node_mut(id) + { + *slot = node; + n += count; + } + } + n +} + +/// Link every paint whose color has a swatch to that swatch, as Add Used Colors does for global +/// swatches, recording each paint visited. Returns the count and the visits. +fn link(d: &mut Document, ids: &[NodeId], map: &mut Map) -> (usize, Vec<(Color, Option)>) { + let names: HashMap = (0..COLORS).map(|i| (red_bits(&color(i)), format!("Swatch {i}"))).collect(); + let mut visits = vec![]; + let n = map(d, ids, &mut |c, s, _| { + visits.push((*c, s.clone())); + match names.get(&red_bits(c)) { + Some(name) if s.is_none() => { + *s = Some(name.clone()); + true + } + _ => false, + } + }); + (n, visits) +} + +fn rect(d: &mut Document, i: usize) -> Arc { + let id = d.alloc_id(); + let (x, y) = ((i % 100) as f64 * 12.0, (i / 100) as f64 * 12.0); + let r = shapes::rectangle(Rect::new(x, y, x + 10.0, y + 10.0)); + let a = Appearance::basic(Paint::solid(color(i % COLORS)), Paint::solid(color((i + 7) % COLORS)), 1.0); + Arc::new(Node::path(id, r, a)) +} + +/// `n` rectangles in the first layer, all selected. +fn flat(n: usize) -> (Document, Vec) { + let mut d = Document::new(1600.0, 1200.0); + let l = d.layers[0].id; + let mut ids = vec![]; + for i in 0..n { + let node = rect(&mut d, i); + ids.push(node.id); + d.insert(Some(l), usize::MAX, Arc::unwrap_or_clone(node)).unwrap(); + } + (d, ids) +} + +/// 1,000 groups in the first layer, each holding a group of 5 rectangles: the rectangles, and with +/// `groups` the two groups above each of them too, listed first. +fn nested(groups: bool) -> (Document, Vec) { + let mut d = Document::new(1600.0, 1200.0); + let l = d.layers[0].id; + let (mut outer_ids, mut leaves) = (vec![], vec![]); + for g in 0..1_000 { + let rects: Vec> = (0..5).map(|i| rect(&mut d, g * 5 + i)).collect(); + leaves.extend(rects.iter().map(|r| r.id)); + let inner = Node::group(d.alloc_id(), rects); + let outer = Node::group(d.alloc_id(), vec![Arc::new(inner.clone())]); + if groups { + outer_ids.extend([outer.id, inner.id]); + } + d.insert(Some(l), usize::MAX, outer).unwrap(); + } + outer_ids.extend(leaves); + (d, outer_ids) +} + +fn bench(name: &str, (doc, ids): (Document, Vec)) { + let mut shipped = doc.clone(); + let want = link(&mut shipped, &ids, &mut |d, ids, f| d.map_solid_paints_in(ids, f)); + for roots in [roots_by_search as Roots, roots_by_set] { + let mut d = doc.clone(); + let got = link(&mut d, &ids, &mut |d, ids, f| map_in(d, ids, roots, f)); + assert_eq!(got, want, "{name}: the same count and visits"); + assert_eq!(d.layers, shipped.layers, "{name}: the same document"); + } + let (mut old, mut new, mut real) = (vec![], vec![], vec![]); + let timed = |map: &mut Map| { + let mut docs = vec![doc.clone(); REPS]; + measure(|| { + for d in &mut docs { + black_box(link(d, black_box(&ids), &mut *map)); + } + }) / REPS as f64 + }; + for i in 0..iters() { + let run = |roots: Roots, out: &mut Vec| out.push(timed(&mut |d, ids, f| map_in(d, ids, roots, f))); + if i % 2 == 0 { + run(roots_by_search, &mut old); + run(roots_by_set, &mut new); + } else { + run(roots_by_set, &mut new); + run(roots_by_search, &mut old); + } + real.push(timed(&mut |d, ids, f| d.map_solid_paints_in(ids, f))); + } + let (old, new, real) = (median(old), median(new), median(real)); + println!(" {name:<46} {:>7} {:>7} {old:>12.3} {new:>12.3} {real:>12.3} {:>8.1}x", ids.len(), want.0, old / new); +} + +fn main() { + let unit = if thread_cpu_ns().is_some() { "CPU ms" } else { "wall ms" }; + println!( + " {:<46} {:>7} {:>7} {:>12} {:>12} {:>12} {:>9}", + "document", + "ids", + "linked", + format!("search, {unit}"), + format!("set, {unit}"), + format!("shipped, {unit}"), + "speedup" + ); + bench("2,000 rectangles in one layer", flat(2_000)); + bench("20,000 rectangles in one layer", flat(20_000)); + bench("5,000 rectangles in 1,000 groups of groups", nested(false)); + bench("the same with the 2,000 groups listed first", nested(true)); +} diff --git a/crates/engine/examples/stroke_targets_bench.rs b/crates/engine/examples/stroke_targets_bench.rs new file mode 100644 index 0000000000..b576968e49 --- /dev/null +++ b/crates/engine/examples/stroke_targets_bench.rs @@ -0,0 +1,146 @@ +//! `cargo run --release -p vectorcraft-engine --example stroke_targets_bench` prints the time `stroke.set` +//! takes to list its targets on documents of 2,000, 10,000 and 20,000 rectangles, all in one group. For +//! each size it times, on the same leaves, the merge that checks each leaf against the growing list and +//! the merge that checks it against a set, checks that the two lists are equal, and then times the whole +//! `stroke.set {weight: 3}` command twice: once with the group named and once with every rectangle named. +//! The whole-command rows include the document copy the command makes for undo; each run is undone +//! before the next, outside the timed part. +//! On Linux each row is the thread's CPU time, read from `/proc/thread-self/schedstat`; elsewhere +//! it is wall time, and the first line says which. `ITERS` sets the runs per row (default 7); each +//! row is the median in ms. A run of the two merge rows repeats the merge 1,000,000 / paths times +//! and gives the time of one. +// Example (dev tool): unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::collections::HashSet; +use std::hint::black_box; +use std::time::Instant; + +use serde_json::{Value, json}; +use vectorcraft_color::Color; +use vectorcraft_doc::{Document, NodeId}; +use vectorcraft_engine::Session; +use vectorcraft_geom::Rect; +use vectorcraft_testkit::fixtures::DocBuilder; + +fn iters() -> usize { + std::env::var("ITERS").ok().and_then(|v| v.parse().ok()).unwrap_or(7).max(1) +} + +/// The thread's CPU time in ns, or `None` where `/proc/thread-self/schedstat` cannot be read. +fn cpu_ns() -> Option { + std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok() +} + +/// The time `f` takes in ms: CPU time when [`cpu_ns`] reads, wall time otherwise. +fn ms(f: impl FnOnce()) -> f64 { + let (cpu, wall) = (cpu_ns(), Instant::now()); + f(); + match (cpu, cpu_ns()) { + (Some(a), Some(b)) => (b - a) as f64 / 1e6, + _ => wall.elapsed().as_secs_f64() * 1000.0, + } +} + +fn median(mut v: Vec) -> f64 { + v.sort_by(f64::total_cmp); + v[v.len() / 2] +} + +/// `n` 10 pt squares in one group, and the squares' ids in stacking order. +fn document(n: usize) -> (Document, NodeId, Vec) { + let mut b = DocBuilder::new(4000.0, 4000.0); + let kids: Vec<_> = (0..n) + .map(|i| { + let (x, y) = ((i % 200) as f64 * 12.0, (i / 200) as f64 * 12.0); + b.rect_node(Rect::new(x, y, x + 10.0, y + 10.0), Color::rgb(0.2, 0.4, 0.6)) + }) + .collect(); + let leaves = kids.iter().map(|k| k.id).collect(); + let group = b.group(kids, false); + (b.build(), group, leaves) +} + +/// The merge that checks each leaf against the growing list. +fn listed(mut out: Vec, leaves: Vec) -> Vec { + for id in leaves { + if !out.contains(&id) { + out.push(id); + } + } + out +} + +/// The merge that checks each leaf against a set seeded with `out`. +fn with_set(mut out: Vec, leaves: Vec) -> Vec { + let mut seen: HashSet = out.iter().copied().collect(); + for id in leaves { + if seen.insert(id) { + out.push(id); + } + } + out +} + +fn row(name: &str, ms: f64) { + println!(" {name:<52} {ms:>10.3} ms"); +} + +/// The median time of `stroke.set {weight: 3}` on `ids`, each run undone outside the timed part. +fn whole_command(s: &mut Session, ids: &[NodeId], n: usize) -> f64 { + let p: Value = json!({"ids": ids.iter().map(|id| id.0).collect::>(), "weight": 3}); + let runs = (0..iters()) + .map(|_| { + let mut r = Value::Null; + let t = ms(|| r = black_box(s.execute("stroke.set", &p).unwrap())); + assert_eq!(r["objects"], n, "{r}"); + s.execute("edit.undo", &json!({})).unwrap(); + t + }) + .collect(); + median(runs) +} + +fn bench(n: usize) { + println!("{n} paths in one group"); + let (doc, group, leaves) = document(n); + + // Each run merges `reps` times, on copies made before the clock starts, and gives the time of one. + let reps = (1_000_000 / n).max(1); + let time = |f: fn(Vec, Vec) -> Vec| -> (f64, Vec) { + let mut last = Vec::new(); + let runs = (0..iters()) + .map(|_| { + let mut work: Vec> = (0..reps).map(|_| leaves.clone()).collect(); + let mut done = Vec::with_capacity(reps); + let t = ms(|| { + for input in &mut work { + done.push(f(Vec::new(), black_box(std::mem::take(input)))); + } + }); + last = done.pop().unwrap(); + t / reps as f64 + }) + .collect(); + (median(runs), last) + }; + let (old, a) = time(listed); + let (new, b) = time(with_set); + assert_eq!(a, b, "both merges give the same list"); + assert_eq!(a, leaves); + row("target merge, list search", old); + row("target merge, set", new); + println!(" {:<52} {:>10.1}x", "ratio", old / new); + + let mut s = Session::new(); + s.add_document(doc, None); + row("stroke.set, whole command, the group named", whole_command(&mut s, &[group], n)); + row("stroke.set, whole command, every path named", whole_command(&mut s, &leaves, n)); +} + +fn main() { + println!("{}", if cpu_ns().is_some() { "thread CPU time, median of runs" } else { "wall time, median of runs" }); + for n in [2_000, 10_000, 20_000] { + bench(n); + } +} diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index c4a86dd3a5..cd29ab4154 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -407,7 +407,18 @@ pub fn command_specs() -> &'static [CommandSpec] { /// The command `id`: a built-in one, or a command an installed plug-in adds /// ([`plugin::command_specs`]). pub fn find_command(id: &str) -> Option<&'static CommandSpec> { - command_specs().iter().find(|c| c.id == id).or_else(|| plugin::find_spec(id)) + static INDEX: std::sync::OnceLock> = std::sync::OnceLock::new(); + INDEX.get_or_init(|| index_by_id(command_specs())).get(id).copied().or_else(|| plugin::find_spec(id)) +} + +/// `specs` by id. An id that more than one spec has names the first of them, as a search of +/// `specs` in order finds. +pub(crate) fn index_by_id(specs: &[CommandSpec]) -> std::collections::HashMap<&'static str, &CommandSpec> { + let mut index = std::collections::HashMap::with_capacity(specs.len()); + for spec in specs { + index.entry(spec.id).or_insert(spec); + } + index } /// Runs command `spec`'s implementation with `p`. A plug-in command's runs the plug-in @@ -821,12 +832,16 @@ pub(crate) fn unique_name_from(base: &str, next: &mut std::collections::HashMap< pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000; pub(crate) use addons::{DecodedImages, refresh_color_masks}; +/// Packaging Tools' blanks and the objects their print leaves out, for the Fold Preview window. +pub use addons::{fold_source, print_hidden}; /// Document Info's category titles and the Objects category's count labels. pub use docinfo::{CATEGORIES, OBJECT_LABELS}; pub use docmenu::guide_indexes; -pub(crate) use edit::{settle_interaction, typing_in_progress}; +pub(crate) use edit::{Unrecorded, settle_interaction, typing_in_progress}; pub(crate) use object::bounds_rewrite; pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned}; +/// The rules `object.scale`, `object.reflect` and `object.shear` check their params with. +pub use object::{reflect_axis, scale_factors, shear_tangent}; pub use plugin_call::{Location, ParamsPlace, key_location, location_in, location_keys}; pub use select::SIMILAR; pub(crate) use vectorcraft_doc::range::parse_range; @@ -886,6 +901,9 @@ pub(crate) use buildcmds::TracePresetChanges; /// The shapes a group selected alone gives the Pathfinder panel. pub use pathops::shape_count; +/// The Shape Mode commands' warning when a selected open path encloses no area. +pub use pathops::SHAPE_MODE_OPEN_PATH_NO_AREA; + /// The gaps View › Show Live Paint Gaps shows on a Live Paint group. pub use buildcmds::live_paint_gaps; @@ -901,6 +919,10 @@ pub use brushsym::current_symbol; /// Data window reads files by it too). pub use variablecmds::utf16_order_without_mark; +/// How the Graph Data window's Import Data and Import Data Sets' `%` columns read a graph data +/// file: its size limit, its text, its cells and the data `graph.setData` takes from them. +pub use graph::{MAX_GRAPH_DATA_FILE, graph_cell_text, graph_data_from_grid, graph_data_text, graph_grid_from_text}; + /// The Variables panel's sort (`variable.sort`) and its rows in that order. pub use variablecmds::{VariableSort, VariableSortKey, variable_order}; diff --git a/crates/engine/src/cmd/addons.rs b/crates/engine/src/cmd/addons.rs index 8c310878fd..03fb17f436 100644 --- a/crates/engine/src/cmd/addons.rs +++ b/crates/engine/src/cmd/addons.rs @@ -14,8 +14,10 @@ mod pen; mod select; mod shapes; mod typetools; +mod units; pub(crate) use image::{DecodedImages, refresh_color_masks}; +pub use packaging::{fold_source, print_hidden}; pub(crate) use packaging::{role_swatch_edited, role_swatches_merged}; use super::CommandSpec; @@ -35,5 +37,6 @@ pub fn specs() -> Vec { v.extend(select::specs()); v.extend(shapes::specs()); v.extend(typetools::specs()); + v.extend(units::specs()); v } diff --git a/crates/engine/src/cmd/addons/packaging.rs b/crates/engine/src/cmd/addons/packaging.rs index 6099386b98..9de16ca200 100644 --- a/crates/engine/src/cmd/addons/packaging.rs +++ b/crates/engine/src/cmd/addons/packaging.rs @@ -6,8 +6,10 @@ //! (Object › Plug-ins › Packaging Tools) and its Fold Lines panel are the UI's. mod check; +mod fold; mod roles; +pub use fold::{fold_source, print_hidden}; pub(crate) use roles::{role_swatch_edited, role_swatches_merged}; use super::super::CommandSpec; @@ -15,6 +17,7 @@ use super::super::CommandSpec; pub fn specs() -> Vec { let mut v = roles::specs(); v.extend(check::specs()); + v.extend(fold::specs()); v } diff --git a/crates/engine/src/cmd/addons/packaging/check.rs b/crates/engine/src/cmd/addons/packaging/check.rs index da8f7f25dd..9507a17daa 100644 --- a/crates/engine/src/cmd/addons/packaging/check.rs +++ b/crates/engine/src/cmd/addons/packaging/check.rs @@ -4,7 +4,7 @@ use serde_json::{Value, json}; use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; use vectorcraft_geom::PathData; -use vectorcraft_three_d::fold::{FoldLine, IssueCode, LineKind, MAX_SEGMENTS, blanks}; +use vectorcraft_three_d::fold::{Blank, FoldLine, Issue, IssueCode, LineKind, MAX_SEGMENTS, blanks}; use super::super::super::pathops::length_given; use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, switch_or}; @@ -14,7 +14,7 @@ use crate::{Result, Session}; const CHECK: &str = "addon.packaging.check"; /// How far apart the ends of two lines may be and still be joined, in points. -const TOLERANCE: (f64, f64, f64) = (0.01, 0.1, 10.0); +pub(super) const TOLERANCE: (f64, f64, f64) = (0.01, 0.1, 10.0); pub fn specs() -> Vec { vec![cmd!( @@ -101,23 +101,44 @@ fn kind(role: Role) -> LineKind { } } -fn check(s: &mut Session, p: &Value) -> Result { - let select = switch_or(p, "select", false, CHECK)?; - let tolerance = match length_given(p, "tolerance", CHECK)? { - None => TOLERANCE.1, - Some(t) if (TOLERANCE.0..=TOLERANCE.2).contains(&t) => t, - Some(_) => return Err(bad(CHECK, format!("`tolerance` must be from {} to {} pt", TOLERANCE.0, TOLERANCE.2))), - }; +/// The fold lines a check or a fold reads: where they came from (`ids`, `selection` or +/// `document`), the lines, and the ids of those on a non-printing layer. +pub(super) struct Lines { + pub scope: &'static str, + pub lines: Vec, + pub non_printing: Vec, +} + +/// The tolerance `p` gives for `cmd`, or the default. +pub(super) fn tolerance(p: &Value, cmd: &str) -> Result { + match length_given(p, "tolerance", cmd)? { + None => Ok(TOLERANCE.1), + Some(t) if (TOLERANCE.0..=TOLERANCE.2).contains(&t) => Ok(t), + Some(_) => Err(bad(cmd, format!("`tolerance` must be from {} to {} pt", TOLERANCE.0, TOLERANCE.2))), + } +} + +/// The fold lines among the objects `p` names for `cmd` (`ids`, else the selection), or, while +/// nothing is selected and `ids` is left out, every shown fold line of the document. Hidden lines +/// are left out in every scope, members of a selected group included. +pub(super) fn lines(s: &Session, p: &Value, cmd: &str) -> Result { let given = p.get("ids").is_some_and(|v| !v.is_null()); - let roots = checked_ids_or_selection(s, p, CHECK)?; + let roots = checked_ids_or_selection(s, p, cmd)?; let d = &s.doc()?.doc; - // Hidden lines are left out in every scope, members of a selected group included. let shown = |ids: Vec| ids.into_iter().filter(|id| d.is_visible(*id)).collect::>(); - let (scope, targets) = match (given, roots.is_empty()) { - (true, _) => ("ids", shown(role_targets(d, &roots, false).0)), - (false, false) => ("selection", shown(role_targets(d, &roots, false).0)), - (false, true) => ("document", shown_targets(d)), - }; + Ok(match (given, roots.is_empty()) { + (true, _) => lines_of(d, "ids", shown(role_targets(d, &roots, false).0)), + (false, false) => lines_of(d, "selection", shown(role_targets(d, &roots, false).0)), + (false, true) => document_lines(d), + }) +} + +/// Every shown fold line of `d`. +pub(super) fn document_lines(d: &Document) -> Lines { + lines_of(d, "document", shown_targets(d)) +} + +fn lines_of(d: &Document, scope: &'static str, targets: Vec) -> Lines { let table = RoleTable::of(d); let mut lines = vec![]; let mut non_printing = vec![]; @@ -136,12 +157,21 @@ fn check(s: &mut Session, p: &Value) -> Result { segments = segments.saturating_add(path.subpaths.iter().map(|sp| sp.segment_count()).sum()); lines.push(FoldLine { path, kind: kind(role), key: id.0 }); } - let (found, mut issues) = blanks(&lines, tolerance); - if !non_printing.is_empty() { - issues.push(vectorcraft_three_d::fold::Issue { code: IssueCode::NonPrinting, keys: non_printing, at: None }); + Lines { scope, lines, non_printing } +} + +/// The blanks `lines` make and their issues, the non-printing one last. +pub(super) fn found(lines: &Lines, tolerance: f64) -> (Vec, Vec) { + let (found, mut issues) = blanks(&lines.lines, tolerance); + if !lines.non_printing.is_empty() { + issues.push(Issue { code: IssueCode::NonPrinting, keys: lines.non_printing.clone(), at: None }); } - let ok = !issues.iter().any(|i| i.code.is_error()); - let rows: Vec = issues + (found, issues) +} + +/// `issues` as the rows `addon.packaging.check` and `addon.packaging.fold` answer with. +pub(super) fn issue_rows(issues: &[Issue], scope: &str) -> Vec { + issues .iter() .map(|i| { let mut row = json!({ @@ -155,7 +185,18 @@ fn check(s: &mut Session, p: &Value) -> Result { } row }) - .collect(); + .collect() +} + +fn check(s: &mut Session, p: &Value) -> Result { + let select = switch_or(p, "select", false, CHECK)?; + let tolerance = tolerance(p, CHECK)?; + let lines = lines(s, p, CHECK)?; + let scope = lines.scope; + let (found, issues) = found(&lines, tolerance); + let d = &s.doc()?.doc; + let ok = !issues.iter().any(|i| i.code.is_error()); + let rows = issue_rows(&issues, scope); if select { let mut ids: Vec = issues.iter().flat_map(|i| i.keys.iter().map(|k| NodeId(*k))).filter(|id| d.node(*id).is_some()).collect(); ids.sort_unstable_by_key(|id| id.0); diff --git a/crates/engine/src/cmd/addons/packaging/fold.rs b/crates/engine/src/cmd/addons/packaging/fold.rs new file mode 100644 index 0000000000..068b2375c9 --- /dev/null +++ b/crates/engine/src/cmd/addons/packaging/fold.rs @@ -0,0 +1,110 @@ +//! Fold Preview's model (`addon.packaging.fold`): a blank folded into its 3D shape by +//! [`vectorcraft_three_d::fold::fold`], and what the Fold Preview window needs to draw it: the +//! document's blanks ([`fold_source`]) and the objects its print leaves out ([`print_hidden`]). + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; +use vectorcraft_three_d::fold::{Blank, Issue, fold, pick}; + +use super::super::super::{CommandSpec, bad, cmd, finite_numbers, has_doc, number_or}; +use super::check::{TOLERANCE, document_lines, found, issue_rows, lines, tolerance}; +use super::roles::{RoleTable, can_carry}; +use crate::{Result, Session}; + +const FOLD: &str = "addon.packaging.fold"; + +pub fn specs() -> Vec { + vec![cmd!( + query "addon.packaging.fold", + "Fold", + [], + None, + "{ids?: [id…] (default: the selection), base?: [x, y] (the panel under this point; default: the largest panel), amount?: 0..1 (1), tolerance?: pt 0.01..10 (0.1)} fold the blank that the fold lines among the objects make (as addon.packaging.check finds them; while nothing is selected and ids is left out, every fold line of the document) into its 3D shape. The base panel stays in place; every other panel turns about the hinges that join it to the base, each by its angle times amount: a Crease or a Perforation by 90° away from the printed side, a Partial Cut by 90° toward it. Hinges that close a loop of panels are not turned about: gap is how far apart their two placements end up when every hinge is folded all the way, whatever amount is, and closes is true within tolerance or 0.5% of the hinge's length. Changes nothing in the document → {ok (no error), blank (the index of the blank folded, or null when none is), blanks, base, panels: [{outline (SVG path data, document coordinates), frame: {x, y, z, origin} (where the flat blank's x and y directions, its printed side and its origin go, in points: x right, y up, z toward the printed side of the flat blank), parent (null for the base and loose panels), depth}], hinges: [{a, b, angle (degrees), kind: tree|closing, closes, gap}], collisions: [[a, b]] (panels that pass through each other; panels stacked in one plane do not), issues (as addon.packaging.check)}. Errors: a base point in no panel", + has_doc, + fold_command + )] +} + +/// The blanks the shown fold lines of `d` make, and their issues (`addon.packaging.check` on the +/// whole document): what the Fold Preview window folds. +pub fn fold_source(d: &Document) -> (Vec, Vec) { + found(&document_lines(d), TOLERANCE.1) +} + +/// The objects the print on a folded blank leaves out: the layers that do not print and, unless +/// `fold_lines`, every object with a line role. +pub fn print_hidden(d: &Document, fold_lines: bool) -> Vec { + fn walk(n: &Node, table: &RoleTable, fold_lines: bool, out: &mut Vec) { + match &n.kind { + NodeKind::Layer { printable: false, .. } => out.push(n.id), + NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().for_each(|c| walk(c, table, fold_lines, out)), + _ if !fold_lines && can_carry(n) && table.role_of(n).is_some() => out.push(n.id), + _ => {} + } + } + let table = RoleTable::of(d); + let mut out = vec![]; + d.layers.iter().for_each(|l| walk(l, &table, fold_lines, &mut out)); + out +} + +fn fold_command(s: &mut Session, p: &Value) -> Result { + let tolerance = tolerance(p, FOLD)?; + let amount = number_or(p, "amount", 1.0, FOLD)?; + if !(0.0..=1.0).contains(&amount) { + return Err(bad(FOLD, "`amount` must be from 0 to 1")); + } + let base = match p.get("base") { + None | Some(Value::Null) => None, + Some(v) => { + let [x, y] = finite_numbers::<2>(v).ok_or_else(|| bad(FOLD, "`base` must be a point: [x, y]"))?; + Some(vectorcraft_geom::Point::new(x, y)) + } + }; + let lines = lines(s, p, FOLD)?; + let (blanks, issues) = found(&lines, tolerance); + let ok = !issues.iter().any(|i| i.code.is_error()); + let picked = pick(&blanks, base); + if base.is_some() && picked.is_none() { + return Err(bad(FOLD, "`base` is in no panel")); + } + let folded = picked.and_then(|(b, panel)| Some((b, blanks.get(b)?, fold(blanks.get(b)?, Some(panel), amount, tolerance)?))); + let Some((index, blank, f)) = folded else { + return Ok(json!({ + "ok": ok, "blank": null, "blanks": blanks.len(), "base": null, "panels": [], "hinges": [], "collisions": [], + "issues": issue_rows(&issues, lines.scope), + })); + }; + let column = |m: &[[f64; 3]; 3], k: usize| json!([m[0][k], m[1][k], m[2][k]]); + let panels: Vec = blank + .panels + .iter() + .zip(&f.panels) + .map(|(panel, placed)| { + json!({ + "outline": panel.outline.to_bezpath().to_svg(), + "frame": {"x": column(&placed.pose.m, 0), "y": column(&placed.pose.m, 1), "z": column(&placed.pose.m, 2), "origin": placed.pose.t}, + "parent": placed.parent, + "depth": placed.depth, + }) + }) + .collect(); + let hinges: Vec = f + .hinges + .iter() + .map(|h| json!({"a": h.a, "b": h.b, "angle": h.angle, "kind": if h.tree { "tree" } else { "closing" }, "closes": h.closes, "gap": h.gap})) + .collect(); + Ok(json!({ + "ok": ok, + "blank": index, + "blanks": blanks.len(), + "base": f.base, + "panels": panels, + "hinges": hinges, + "collisions": f.collisions.iter().map(|(a, b)| [a, b]).collect::>(), + "issues": issue_rows(&issues, lines.scope), + })) +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/addons/packaging/fold/tests.rs b/crates/engine/src/cmd/addons/packaging/fold/tests.rs new file mode 100644 index 0000000000..4c423021f5 --- /dev/null +++ b/crates/engine/src/cmd/addons/packaging/fold/tests.rs @@ -0,0 +1,157 @@ +//! Tests for the Fold Preview's model: a blank drawn in a document folded into its 3D shape. + +use serde_json::{Value, json}; + +use crate::*; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap(); + s +} + +fn path(s: &mut Session, d: &str) -> u64 { + s.execute("path.create", &json!({ "d": d })).unwrap()["id"].as_u64().unwrap() +} + +fn role(s: &mut Session, role: &str, ids: &[u64]) { + s.execute("addon.packaging.setRole", &json!({ "role": role, "ids": ids })).unwrap(); +} + +fn fold(s: &mut Session, p: Value) -> Value { + s.execute("addon.packaging.fold", &p).unwrap() +} + +/// A tray blank: a 100 pt base (x 140 to 240, y 140 to 240) with a 40 pt wall on each side → +/// (outline, creases). +fn tray(s: &mut Session) -> (u64, Vec) { + let outline = path(s, "M140 100 L240 100 L240 140 L280 140 L280 240 L240 240 L240 280 L140 280 L140 240 L100 240 L100 140 L140 140 Z"); + let creases = vec![path(s, "M140 140 L240 140"), path(s, "M240 140 L240 240"), path(s, "M240 240 L140 240"), path(s, "M140 240 L140 140")]; + role(s, "cut", &[outline]); + role(s, "crease", &creases); + s.execute("select.none", &json!({})).unwrap(); + (outline, creases) +} + +fn vector(v: &Value) -> [f64; 3] { + let a = v.as_array().unwrap(); + [a[0].as_f64().unwrap(), a[1].as_f64().unwrap(), a[2].as_f64().unwrap()] +} + +/// The middle of the bounds of the points of SVG path data `d` (absolute moves and lines only). +fn middle(d: &str) -> [f64; 2] { + let n: Vec = d.split(|c: char| !(c.is_ascii_digit() || c == '.' || c == '-')).filter_map(|t| t.parse().ok()).collect(); + let span = |k: usize| n.iter().skip(k).step_by(2).fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), &t| (lo.min(t), hi.max(t))); + let ((x0, x1), (y0, y1)) = (span(0), span(1)); + [(x0 + x1) / 2.0, (y0 + y1) / 2.0] +} + +fn near(a: [f64; 3], b: [f64; 3]) -> bool { + a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-9) +} + +#[test] +fn a_tray_folds_its_walls_up_round_the_base() { + let mut s = session(); + tray(&mut s); + let steps = s.doc().unwrap().history.undo.len(); + let r = fold(&mut s, json!({})); + assert_eq!((r["ok"].as_bool(), r["blank"].as_u64(), r["blanks"].as_u64()), (Some(true), Some(0), Some(1)), "{r}"); + let panels = r["panels"].as_array().unwrap(); + assert_eq!(panels.len(), 5); + let base = r["base"].as_u64().unwrap() as usize; + let frame = &panels[base]["frame"]; + assert!( + near(vector(&frame["x"]), [1.0, 0.0, 0.0]) && near(vector(&frame["z"]), [0.0, 0.0, 1.0]) && near(vector(&frame["origin"]), [0.0; 3]), + "{frame}" + ); + assert!(panels[base]["parent"].is_null()); + assert!(panels[base]["outline"].as_str().unwrap().starts_with('M'), "SVG path data"); + for (i, p) in panels.iter().enumerate().filter(|(i, _)| *i != base) { + assert_eq!((p["parent"].as_u64(), p["depth"].as_u64()), (Some(base as u64), Some(1)), "{p}"); + // Each wall stands square to the base, below it (away from the print), its print facing out: + // away from the base's middle (190, 190), toward the side the wall lies on. + let [cx, cy] = middle(p["outline"].as_str().unwrap()); + let (x, y, o) = (vector(&p["frame"]["x"]), vector(&p["frame"]["y"]), vector(&p["frame"]["origin"])); + let placed: [f64; 3] = std::array::from_fn(|k| o[k] + x[k] * cx - y[k] * cy); + let (dx, dy) = (cx - 190.0, 190.0 - cy); + let out = if dx.abs() > dy.abs() { [dx.signum(), 0.0, 0.0] } else { [0.0, dy.signum(), 0.0] }; + assert!(near(vector(&p["frame"]["z"]), out), "wall {i}: {p}"); + assert!((placed[2] + 20.0).abs() < 1e-9, "wall {i}'s middle is 20 pt below the base: {placed:?}"); + } + let hinges = r["hinges"].as_array().unwrap(); + assert_eq!(hinges.len(), 4); + assert!(hinges.iter().all(|h| h["kind"] == "tree" && h["angle"] == 90.0 && h["closes"] == true), "{r}"); + assert_eq!(r["collisions"], json!([])); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "a fold records no undo step"); + + // Flat, every frame is the flat blank's own. + let r = fold(&mut s, json!({ "amount": 0 })); + for p in r["panels"].as_array().unwrap() { + assert!(near(vector(&p["frame"]["z"]), [0.0, 0.0, 1.0]) && near(vector(&p["frame"]["origin"]), [0.0; 3]), "{p}"); + } +} + +#[test] +fn the_base_is_the_panel_under_a_point() { + let mut s = session(); + tray(&mut s); + // The left wall: x 100 to 140, y 140 to 240. + let r = fold(&mut s, json!({ "base": [120, 190] })); + let base = r["base"].as_u64().unwrap() as usize; + let panels = r["panels"].as_array().unwrap(); + assert!(near(vector(&panels[base]["frame"]["z"]), [0.0, 0.0, 1.0])); + // The tray's base is now a child of the wall, and the other walls its children. + let depths: Vec = panels.iter().map(|p| p["depth"].as_u64().unwrap()).collect(); + let mut sorted = depths.clone(); + sorted.sort_unstable(); + assert_eq!(sorted, [0, 1, 2, 2, 2], "{depths:?}"); + let e = s.execute("addon.packaging.fold", &json!({ "base": [10, 10] })).unwrap_err().to_string(); + assert!(e.contains("`base` is in no panel"), "{e}"); +} + +#[test] +fn bad_values_are_refused() { + let mut s = session(); + tray(&mut s); + for (p, want) in [ + (json!({ "amount": 1.5 }), "`amount` must be from 0 to 1"), + (json!({ "amount": -0.1 }), "`amount` must be from 0 to 1"), + (json!({ "amount": "1" }), "`amount` must be a number"), + (json!({ "base": [1] }), "`base` must be a point"), + (json!({ "base": "middle" }), "`base` must be a point"), + (json!({ "tolerance": 50 }), "`tolerance` must be from"), + ] { + let e = s.execute("addon.packaging.fold", &p).unwrap_err().to_string(); + assert!(e.contains(want), "{p}: {e}"); + } +} + +#[test] +fn without_a_blank_nothing_is_folded_and_the_issues_say_why() { + let mut s = session(); + let r = fold(&mut s, json!({})); + assert_eq!((r["ok"].as_bool(), r["blank"].is_null(), r["blanks"].as_u64()), (Some(false), true, Some(0)), "{r}"); + assert_eq!(r["panels"], json!([])); + assert_eq!(r["issues"][0]["code"], "noCut"); +} + +#[test] +fn the_print_leaves_out_fold_lines_and_layers_that_do_not_print() { + let mut s = session(); + let (outline, creases) = tray(&mut s); + let art = path(&mut s, "M150 150 L200 150 L200 200 Z"); + let notes = s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("layer.setProps", &json!({"id": notes, "printable": false})).unwrap(); + let d = &s.doc().unwrap().doc; + let hidden: Vec = cmd::print_hidden(d, false).into_iter().map(|id| id.0).collect(); + for id in creases.iter().chain([&outline, ¬es]) { + assert!(hidden.contains(id), "{id} in {hidden:?}"); + } + assert!(!hidden.contains(&art)); + let shown: Vec = cmd::print_hidden(d, true).into_iter().map(|id| id.0).collect(); + assert_eq!(shown, vec![notes], "with the fold lines shown, only the layer is left out"); + let (blanks, issues) = cmd::fold_source(d); + assert_eq!((blanks.len(), blanks[0].panels.len()), (1, 5)); + assert!(issues.is_empty(), "{issues:?}"); +} diff --git a/crates/engine/src/cmd/addons/pathtools.rs b/crates/engine/src/cmd/addons/pathtools.rs index 1c730e02b4..2d1ded312f 100644 --- a/crates/engine/src/cmd/addons/pathtools.rs +++ b/crates/engine/src/cmd/addons/pathtools.rs @@ -3,11 +3,13 @@ //! anchor edits, Split / Add Points at Crossings, Slide Anchor Along Path, the Corner Tool's corners //! ([`corners`]), the Parametric Shape Tool's shapes ([`shape`]), the Shared Edge Merge Tool's //! merges with Keep Shared Points Together ([`shared_edge`]), Divide into Dashes, Expand Dashes -//! into Paths, Trim at Crossings ([`trim`]), Common Tangents ([`tangents`]) and Tangent Circle +//! into Paths, Trim at Crossings ([`trim`]), Smooth Bridge ([`bridge`]), Common Tangents +//! ([`tangents`]) and Tangent Circle //! ([`tangent_circle`]). //! Its tools, panels and submenu (Object › Plug-ins › Path Precision Tools) are the tools crate's //! and the UI's. +mod bridge; mod corners; #[cfg(test)] mod effect_tests; @@ -183,6 +185,7 @@ pub fn specs() -> Vec { v.extend(corners::specs()); v.extend(shared_edge::specs()); v.extend(trim::specs()); + v.extend(bridge::specs()); v.extend(tangent_circle::specs()); v.extend(tangents::specs()); v diff --git a/crates/engine/src/cmd/addons/pathtools/bridge.rs b/crates/engine/src/cmd/addons/pathtools/bridge.rs new file mode 100644 index 0000000000..2120b040e7 --- /dev/null +++ b/crates/engine/src/cmd/addons/pathtools/bridge.rs @@ -0,0 +1,95 @@ +//! Smooth Bridge: two selected circles joined into one outline by two concave arcs that touch both +//! circles, replacing the circles or added above them. + +use serde_json::{Value, json}; +use vectorcraft_doc::{NodeId, NodeKind}; +use vectorcraft_geom::PathData; +use vectorcraft_pathops::addons::pathtools as pt; + +use super::super::super::pathops::{Beside, remove_each}; +use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_selection, switch_or}; +use super::given; +use crate::{EngineError, Result, Session}; + +#[cfg(test)] +mod tests; + +/// The command, and its undo step's name. +const C: &str = "addon.pathtools.bridge"; +const LABEL: &str = "Smooth Bridge"; +/// The arcs' radius as a percentage of the smaller circle's radius: by default, and the range. +const RADIUS: f64 = 100.0; +const RADII: (f64, f64) = (1.0, 1000.0); + +pub(super) fn specs() -> Vec { + vec![cmd!( + "addon.pathtools.bridge", + "Smooth Bridge", + ["Object", "Plug-ins", "Path Precision Tools"], + None, + "{radius?: % 1..1000 (100; the radius of the bridge's two arcs as a percentage of the smaller circle's radius: larger makes a wider, gentler bridge), keepOriginals?: bool (false: the outline replaces the two circles, painted as the upper one; true: it goes directly above the upper one and the circles stay), ids?: [id, id] (default: the selection)} join two circles (paths whose outline is a circle, not hidden or locked) into one closed outline: around each circle on its side away from the other, and along two concave arcs, one on each side, that touch both circles so the outline runs on smoothly into them. Overlapping and touching circles are joined too; one circle inside the other, or circles too far apart for the radius (the arcs would not reach both, or would cross), is an error, which suggests a larger radius when one up to 1000% would bridge them. One undo step; the outline is selected → {id}", + has_selection, + bridge + )] +} + +fn bridge(s: &mut Session, p: &Value) -> Result { + let percent = given(p, "radius", Some(RADII), C)?.unwrap_or(RADIUS); + let keep = switch_or(p, "keepOriginals", false, C)?; + let roots = checked_ids_or_selection(s, p, C)?; + let circles: Vec<(NodeId, pt::Circle)> = { + let d = &s.doc()?.doc; + let editable = d.editable(); + d.paint_order(roots.iter().copied()) + .into_iter() + .filter_map(|id| match &d.node(id)?.kind { + NodeKind::Path { path, guide: false, clipping: false, .. } if editable(id) => Some((id, pt::circle_of(path)?)), + _ => None, + }) + .collect() + }; + let ([(below, a), (above, b)], 2) = (circles.as_slice(), roots.len()) else { + return Err(bad(C, "select two circles to bridge")); + }; + let (below, above) = (*below, *above); + let at = |percent: f64| pt::smooth_bridge(*a, *b, a.radius.min(b.radius) * percent / 100.0); + let outline = match at(percent) { + Ok(sp) => PathData::single(sp), + Err(pt::BridgeError::Inside) => return Err(bad(C, "one circle is inside the other")), + // A larger radius bridges circles a smaller one cannot, so only suggest one that is allowed. + Err(pt::BridgeError::TooFar) if at(RADII.1).is_ok() => { + return Err(bad(C, "the circles are too far apart for this radius: raise the radius")); + } + Err(pt::BridgeError::TooFar) => return Err(bad(C, "the circles are too far apart for this radius")), + Err(pt::BridgeError::Bad) => return Err(bad(C, "select two circles to bridge")), + }; + let id = s.edit(LABEL, |d, sel| { + let id = if keep { + // A copy of the upper circle (its appearance) with the outline as its path, right above + // it; the circles stay as they are, live shapes included. + // Fresh ids throughout, its opacity mask's art included. + let upper = d.node(above).cloned().ok_or(EngineError::NoNode(above))?; + let mut n = d.reid(&upper); + if let NodeKind::Path { path, live, .. } = &mut n.kind { + *path = outline; + *live = None; + } + let id = n.id; + let mut beside = Beside::above(d, &[above]); + beside.put(d, above, vec![n])?; + beside.finish(d)?; + id + } else { + // The upper circle becomes the outline (a plain path now) and the lower one goes. + if let Some(NodeKind::Path { path, live, .. }) = d.node_mut(above).map(|n| &mut n.kind) { + *path = outline; + *live = None; + } + remove_each(d, &[below])?; + above + }; + sel.set([id]); + Ok(id) + })?; + Ok(json!({ "id": id.0 })) +} diff --git a/crates/engine/src/cmd/addons/pathtools/bridge/tests.rs b/crates/engine/src/cmd/addons/pathtools/bridge/tests.rs new file mode 100644 index 0000000000..01320c07c1 --- /dev/null +++ b/crates/engine/src/cmd/addons/pathtools/bridge/tests.rs @@ -0,0 +1,184 @@ +//! Smooth Bridge: the outline in place of the circles or above them, one undo step, the radius, +//! and what it refuses. + +use serde_json::{Value, json}; +use vectorcraft_doc::{NodeId, NodeKind}; +use vectorcraft_geom::kurbo::Shape; + +use crate::Session; + +const BRIDGE: &str = "addon.pathtools.bridge"; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s +} + +/// A circle about (`x`, `y`) with radius `r`. +fn circle(s: &mut Session, x: f64, y: f64, r: f64) -> NodeId { + let id = s.execute("shape.ellipse", &json!({"x": x - r, "y": y - r, "width": 2.0 * r, "height": 2.0 * r})).unwrap()["id"].as_u64().unwrap(); + NodeId(id) +} + +fn select(s: &mut Session, ids: &[NodeId]) { + s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); +} + +fn top_level(s: &Session) -> Vec { + s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect() +} + +fn area(s: &Session, id: NodeId) -> f64 { + s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().to_bezpath().area().abs() +} + +fn err(s: &mut Session, p: Value) -> String { + s.execute(BRIDGE, &p).unwrap_err().to_string() +} + +#[test] +fn two_circles_become_one_outline_in_the_upper_ones_place() { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let b = circle(&mut s, 160.0, 100.0, 20.0); + select(&mut s, &[a, b]); + let steps = s.doc().unwrap().history.undo.len(); + let r = s.execute(BRIDGE, &json!({})).unwrap(); + assert_eq!(r["id"], json!(b.0)); + assert_eq!(top_level(&s), [b]); + let d = &s.doc().unwrap().doc; + let NodeKind::Path { path, live, .. } = &d.node(b).unwrap().kind else { panic!("a path") }; + assert!(live.is_none(), "a plain path now"); + assert!(path.subpaths.len() == 1 && path.subpaths[0].closed); + let bounds = path.bounds().unwrap(); + assert!((bounds.x0 - 80.0).abs() < 1e-2 && (bounds.x1 - 180.0).abs() < 1e-2 && (bounds.height() - 40.0).abs() < 1e-2, "{bounds:?}"); + // Both circles and the bridge between them: more than the two circles' area. + assert!(area(&s, b) > 2.0 * std::f64::consts::PI * 400.0); + assert_eq!(s.doc().unwrap().selection.objects.to_vec(), [b]); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "one undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(top_level(&s), [a, b]); + assert!(matches!(&s.doc().unwrap().doc.node(b).unwrap().kind, NodeKind::Path { live: Some(_), .. }), "the circle is back as it was"); +} + +#[test] +fn keep_originals_adds_the_outline_above_the_upper_circle() { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 30.0); + let b = circle(&mut s, 170.0, 100.0, 10.0); + let c = circle(&mut s, 300.0, 250.0, 5.0); + s.execute("paint.setFill", &json!({"ids": [b.0], "color": "#00ff00"})).unwrap(); + let steps = s.doc().unwrap().history.undo.len(); + let id = NodeId(s.execute(BRIDGE, &json!({"ids": [b.0, a.0], "keepOriginals": true, "radius": 400})).unwrap()["id"].as_u64().unwrap()); + assert_eq!(top_level(&s), [a, b, id, c]); + let d = &s.doc().unwrap().doc; + assert_eq!(d.node(id).unwrap().appearance, d.node(b).unwrap().appearance, "painted as the upper circle"); + assert!(matches!(&d.node(a).unwrap().kind, NodeKind::Path { live: Some(_), .. }), "the circles stay as they are"); + assert!(matches!(&d.node(b).unwrap().kind, NodeKind::Path { live: Some(_), .. })); + let bounds = d.node(id).unwrap().path_data().unwrap().bounds().unwrap(); + assert!((bounds.x0 - 70.0).abs() < 1e-2 && (bounds.x1 - 180.0).abs() < 1e-2 && (bounds.y0 - 70.0).abs() < 1e-2, "{bounds:?}"); + assert_eq!(s.doc().unwrap().selection.objects.to_vec(), [id]); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1); +} + +#[test] +fn a_kept_outline_gets_its_own_mask_art() { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let b = circle(&mut s, 150.0, 100.0, 20.0); + let m = NodeId(s.execute("shape.rectangle", &json!({"x": 130, "y": 80, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap()); + s.execute("transparency.makeOpacityMask", &json!({"ids": [b.0, m.0]})).unwrap(); + let id = NodeId(s.execute(BRIDGE, &json!({"ids": [a.0, b.0], "keepOriginals": true})).unwrap()["id"].as_u64().unwrap()); + let d = &s.doc().unwrap().doc; + let art = |n: NodeId| d.node(n).unwrap().extras().mask.as_deref().map(|m| m.art.id); + let (kept, copied) = (art(b).unwrap(), art(id).unwrap()); + assert_ne!(kept, copied, "the outline's mask art has ids of its own"); +} + +#[test] +fn a_larger_radius_makes_a_wider_bridge() { + let area_at = |radius: f64| { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let b = circle(&mut s, 150.0, 100.0, 15.0); + let id = NodeId(s.execute(BRIDGE, &json!({"ids": [a.0, b.0], "radius": radius})).unwrap()["id"].as_u64().unwrap()); + area(&s, id) + }; + let (default, wider, widest) = (area_at(100.0), area_at(200.0), area_at(400.0)); + assert!(default < wider && wider < widest, "{default} {wider} {widest}"); + let (narrow, default, wide) = (area_at(65.0), default, area_at(300.0)); + assert!(narrow < default && default < wide, "{narrow} {default} {wide}"); + // The default is 100%: the smaller circle's radius. + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let b = circle(&mut s, 150.0, 100.0, 15.0); + let id = NodeId(s.execute(BRIDGE, &json!({"ids": [a.0, b.0]})).unwrap()["id"].as_u64().unwrap()); + assert!((area(&s, id) - default).abs() < 1e-9); +} + +#[test] +fn overlapping_and_touching_circles_are_joined() { + for (gap, radius) in [(-15.0, 50.0), (0.0, 50.0), (0.0, 1.0)] { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let b = circle(&mut s, 140.0 + gap, 100.0, 20.0); + let id = NodeId(s.execute(BRIDGE, &json!({"ids": [a.0, b.0], "radius": radius})).unwrap()["id"].as_u64().unwrap()); + assert_eq!(top_level(&s), [id], "gap {gap}"); + } + // Unequal overlapping circles at every radius, the largest included. + for radius in [1.0, 100.0, 300.0, 1000.0] { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 10.0); + let b = circle(&mut s, 125.0, 100.0, 30.0); + let id = NodeId(s.execute(BRIDGE, &json!({"ids": [a.0, b.0], "radius": radius})).unwrap()["id"].as_u64().unwrap()); + assert_eq!(top_level(&s), [id], "radius {radius}"); + } +} + +#[test] +fn far_apart_nested_and_other_objects_are_refused() { + let mut s = session(); + let a = circle(&mut s, 50.0, 100.0, 10.0); + let far = circle(&mut s, 250.0, 100.0, 10.0); + let near = circle(&mut s, 110.0, 100.0, 10.0); + let inner = circle(&mut s, 52.0, 100.0, 4.0); + let square = NodeId(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap()); + let oval = NodeId(s.execute("shape.ellipse", &json!({"x": 300, "y": 0, "width": 40, "height": 20})).unwrap()["id"].as_u64().unwrap()); + let before = top_level(&s); + let steps = s.doc().unwrap().history.undo.len(); + // 60 pt apart: the default radius (10 pt) cannot reach, the largest (100 pt) can. + assert!(err(&mut s, json!({"ids": [a.0, near.0]})).ends_with("too far apart for this radius: raise the radius")); + assert!(s.execute(BRIDGE, &json!({"ids": [a.0, near.0], "radius": 1000})).is_ok()); + s.execute("edit.undo", &json!({})).unwrap(); + // 200 pt apart even the largest radius (1000%, 100 pt) closes the neck: it stays open only above + // ((200 / 2)² − 10²) / (2 × 10) = 495 pt. No larger radius is suggested. + for radius in [100, 1000] { + let e = err(&mut s, json!({"ids": [a.0, far.0], "radius": radius})); + assert!(e.ends_with("the circles are too far apart for this radius"), "{e}"); + } + assert!(err(&mut s, json!({"ids": [a.0, inner.0]})).contains("one circle is inside the other")); + for ids in [json!([a.0, square.0]), json!([a.0, oval.0]), json!([a.0]), json!([a.0, far.0, inner.0])] { + assert!(err(&mut s, json!({ "ids": ids })).contains("select two circles to bridge"), "{ids}"); + } + assert!(err(&mut s, json!({"ids": [a.0, far.0], "radius": 0.5})).contains("`radius` must be from 1 to 1000")); + assert!(err(&mut s, json!({"ids": [a.0, far.0], "radius": 1001})).contains("`radius`")); + assert!(err(&mut s, json!({"ids": [a.0, far.0], "radius": "big"})).contains("`radius` must be a number")); + assert!(err(&mut s, json!({"ids": [a.0, far.0], "keepOriginals": "yes"})).contains("`keepOriginals` must be true or false")); + assert_eq!(top_level(&s), before); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "nothing changed, no undo step"); +} + +#[test] +fn locked_and_hidden_circles_are_not_bridged() { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let b = circle(&mut s, 150.0, 100.0, 20.0); + select(&mut s, &[b]); + s.execute("object.lock", &json!({})).unwrap(); + assert!(err(&mut s, json!({"ids": [a.0, b.0]})).contains("select two circles to bridge")); + s.execute("object.unlockAll", &json!({})).unwrap(); + select(&mut s, &[a]); + s.execute("object.hide", &json!({})).unwrap(); + assert!(err(&mut s, json!({"ids": [a.0, b.0]})).contains("select two circles to bridge")); +} diff --git a/crates/engine/src/cmd/addons/units.rs b/crates/engine/src/cmd/addons/units.rs new file mode 100644 index 0000000000..b5d844709a --- /dev/null +++ b/crates/engine/src/cmd/addons/units.rs @@ -0,0 +1,124 @@ +//! Unit Converter (`addon.units.*`), a built-in add-on that shows one length in every unit at once. +//! `addon.units.convert` reads a length as a number field reads it ([`Unit::parse`]: units and +//! arithmetic) and gives it in each unit of Preferences › Units › East Asian Type +//! ([`Unit::EAST_ASIAN`]), written as the fields write it ([`Unit::number`], [`Unit::format`]). +//! `addon.units.selectionSize` gives the selection's width and height, measured as the Transform +//! panel measures them, in the same units. Its panel and its place in Object › Plug-ins are the +//! UI's; the panel applies a length to the selection with `object.setBounds`. + +#[cfg(test)] +mod tests; + +use serde_json::{Value, json}; +use vectorcraft_doc::{OrientedBox, Unit, decimal_point, finite_in_every_unit}; +use vectorcraft_render::effects; + +use super::super::{CommandSpec, always, bad, cmd, has_selection}; +use crate::{Result, Session}; + +const CONVERT: &str = "addon.units.convert"; +const SELECTION_SIZE: &str = "addon.units.selectionSize"; +/// The most characters of a refused value an error message shows. +const SHOWN_CHARS: usize = 64; +/// The longest `value` or `unit` text `addon.units.convert` reads, in bytes. +const MAX_TEXT_LEN: usize = 1024; +/// The most `+ - * /` signs `addon.units.convert` reads in one `value`: [`Unit::parse`] takes one +/// level of recursion per sign. +const MAX_OPERATORS: usize = 128; + +pub fn specs() -> Vec { + vec![ + cmd!( + query "addon.units.convert", + "Convert Units", + [], + None, + "{value: a length (a number, or text as a number field reads it, with a unit suffix and + - * / arithmetic: \"10mm\", \"1in/2\", \"2p6\", \"3cm*50%\"; a decimal comma reads as a point: \"0,5 mm\"; at most 1024 bytes and 128 operators), unit?: the unit of a number without a suffix (a unit's name, suffix or key: points, picas, inches, millimeters, centimeters, pixels, feetInches, meters, yards, feet, q, ha; default: points)} the length in every unit of Preferences › Units › East Asian Type, written as the number fields write it (rounded to 3 decimals in pt, px, picas, Q and Ha and to 4 in the others; pixels are points). Nothing in the document changes → {points, units: [{unit (its key), label, number (no suffix), text (with the suffix)}]}", + always, + convert + ), + cmd!( + query "addon.units.selectionSize", + "Selection Size in Units", + [], + None, + "{} the selection's width and height as the Transform panel shows them (its bounding box, rotated with rotated objects; with Use Preview Bounds, the visual bounds; with anchor points selected (Direct Selection), the box around those points), each as addon.units.convert gives it → {width: {points, units}, height: {points, units}}", + has_selection, + selection_size + ), + ] +} + +/// The length `pt` (points) in every unit of [`Unit::EAST_ASIAN`]: `{points, units: [{unit, +/// label, number, text}]}`. +pub fn in_every_unit(pt: f64) -> Value { + let units: Vec = + Unit::EAST_ASIAN.iter().map(|u| json!({"unit": u.key(), "label": u.label(), "number": u.number(pt), "text": u.format(pt)})).collect(); + json!({ "points": pt, "units": units }) +} + +/// The unit `p` gives for a number without a suffix (points when left out; null is an error). +fn unit_param(p: &Value) -> Result { + let Some(given) = p.get("unit") else { return Ok(Unit::Points) }; + let named = given.as_str().filter(|name| name.len() <= MAX_TEXT_LEN).and_then(Unit::named_east_asian); + named.ok_or_else(|| { + let u = match given { + Value::String(s) => clipped(s).escape_debug().to_string(), + other => shown(other), + }; + bad(CONVERT, format!("unknown units `{u}`")) + }) +} + +fn convert(_: &mut Session, p: &Value) -> Result { + let unit = unit_param(p)?; + let Some(v) = p.get("value").filter(|v| !v.is_null()) else { + return Err(bad(CONVERT, "missing `value`")); + }; + let pt = match v { + Value::String(s) if readable(s) => unit.parse(&decimal_point(s)), + Value::Number(n) => n.as_f64().map(|n| unit.to_pt(n)), + _ => None, + }; + let pt = pt.filter(|&pt| finite_in_every_unit(pt)); + pt.map(in_every_unit).ok_or_else(|| { + let v = shown(v); + bad(CONVERT, format!("`value` must be a number, not {v}")) + }) +} + +/// Is `s` short enough to read: at most [`MAX_TEXT_LEN`] bytes and [`MAX_OPERATORS`] `+ - * /` +/// signs? +fn readable(s: &str) -> bool { + s.len() <= MAX_TEXT_LEN && s.chars().filter(|c| matches!(c, '+' | '-' | '*' | '/')).count() <= MAX_OPERATORS +} + +/// `v` as an error message shows it: text cut at [`SHOWN_CHARS`] characters with "…", as JSON, +/// an array as `[…]` and an object as `{…}`. +fn shown(v: &Value) -> String { + match v { + Value::String(s) => Value::String(clipped(s)).to_string(), + Value::Array(_) => "[…]".into(), + Value::Object(_) => "{…}".into(), + other => other.to_string(), + } +} + +/// `s` cut at [`SHOWN_CHARS`] characters, with "…" when it is longer. +fn clipped(s: &str) -> String { + match s.char_indices().nth(SHOWN_CHARS) { + Some((at, _)) => format!("{}…", s.get(..at).unwrap_or_default()), + None => s.to_string(), + } +} + +fn selection_size(s: &mut Session, _: &Value) -> Result { + let st = s.doc()?; + let measure = s.bounds_measure(); + let b = match effects::preview::anchor_bounds_with(&st.selection, &st.doc, measure) { + Some(r) => Some(OrientedBox::aligned(r)), + None => s.transform_box(&st.selection.objects), + }; + let b = b.ok_or_else(|| bad(SELECTION_SIZE, "nothing selected"))?; + Ok(json!({ "width": in_every_unit(b.rect.width()), "height": in_every_unit(b.rect.height()) })) +} diff --git a/crates/engine/src/cmd/addons/units/tests.rs b/crates/engine/src/cmd/addons/units/tests.rs new file mode 100644 index 0000000000..f914c53092 --- /dev/null +++ b/crates/engine/src/cmd/addons/units/tests.rs @@ -0,0 +1,209 @@ +//! Unit Converter's commands: a length in every unit, read as number fields read it, the selection's +//! size as the Transform panel measures it, bad params refused, and nothing in the document changed. + +use serde_json::{Value, json}; +use vectorcraft_doc::Unit; + +use crate::{EngineError, Session}; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s +} + +fn convert(s: &mut Session, p: Value) -> Value { + s.execute("addon.units.convert", &p).unwrap() +} + +/// The row of `r` for the unit with key `key`. +fn row<'a>(r: &'a Value, key: &str) -> &'a Value { + r["units"].as_array().unwrap().iter().find(|u| u["unit"] == key).unwrap_or_else(|| panic!("{key} in {r}")) +} + +fn near(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-9 +} + +#[test] +fn a_length_comes_back_in_every_unit_in_order() { + let mut s = session(); + let r = convert(&mut s, json!({"value": "10mm"})); + assert!(near(r["points"].as_f64().unwrap(), 720.0 / 25.4)); + let keys: Vec<&str> = r["units"].as_array().unwrap().iter().map(|u| u["unit"].as_str().unwrap()).collect(); + assert_eq!(keys, Unit::EAST_ASIAN.map(Unit::key)); + assert_eq!(row(&r, "millimeters")["number"], "10"); + assert_eq!(row(&r, "millimeters")["text"], "10 mm"); + assert_eq!(row(&r, "centimeters")["text"], "1 cm"); + assert_eq!(row(&r, "inches")["text"], "0.3937 in"); + assert_eq!(row(&r, "points")["text"], "28.346 pt"); + assert_eq!(row(&r, "q")["text"], "40 Q"); + assert_eq!(row(&r, "ha")["text"], "40 H"); + assert_eq!(row(&r, "pixels")["number"], row(&r, "points")["number"], "pixels are points"); + assert_eq!(row(&r, "feetInches")["label"], "Feet & Inches"); + // Each row is what a field of that unit shows for the length. + for u in Unit::EAST_ASIAN { + let pt = 720.0 / 25.4; + assert_eq!(row(&r, u.key())["text"], u.format(pt), "{u:?}"); + assert_eq!(row(&r, u.key())["number"], u.number(pt), "{u:?}"); + } +} + +#[test] +fn values_read_as_number_fields_read_them() { + let mut s = session(); + let pt = |s: &mut Session, p: Value| convert(s, p)["points"].as_f64().unwrap(); + assert!(near(pt(&mut s, json!({"value": "1in/2"})), 36.0)); + assert!(near(pt(&mut s, json!({"value": "2p6"})), 30.0)); + assert!(near(pt(&mut s, json!({"value": "1080/2 px"})), 540.0)); + assert!(near(pt(&mut s, json!({"value": "3cm*50%"})), 1.5 * 72.0 / 2.54)); + assert!(near(pt(&mut s, json!({"value": "13q"})), 13.0 * 72.0 / 101.6)); + // A number without a unit is in `unit`, points by default. + assert!(near(pt(&mut s, json!({"value": 12})), 12.0)); + assert!(near(pt(&mut s, json!({"value": 2, "unit": "in"})), 144.0)); + assert!(near(pt(&mut s, json!({"value": "2", "unit": "Inches"})), 144.0)); + assert!(near(pt(&mut s, json!({"value": "3+1", "unit": "cm"})), 4.0 * 72.0 / 2.54)); + assert!(near(pt(&mut s, json!({"value": 6, "unit": "ha"})), 6.0 * 72.0 / 101.6)); + assert!(near(pt(&mut s, json!({"value": 1, "unit": "feetInches"})), 864.0)); + // A suffix wins over `unit`. + assert!(near(pt(&mut s, json!({"value": "1in", "unit": "mm"})), 72.0)); + // A decimal comma reads as a point, as in the number fields. + assert!(near(pt(&mut s, json!({"value": "0,5 in"})), 36.0)); + assert!(near(pt(&mut s, json!({"value": "1,5", "unit": "in"})), 108.0)); + // Each number of a sum reads its own separator. + assert!(near(pt(&mut s, json!({"value": "100.5 mm-0,5", "unit": "mm"})), 100.0 * 72.0 / 25.4)); + // A comma in a sum is a decimal comma, as in the number fields: 1,500+2 is 3.5. + assert!(near(pt(&mut s, json!({"value": "1,500+2", "unit": "mm"})), 3.5 * 72.0 / 25.4)); + // A sum of 128 signs still reads. + assert!(near(pt(&mut s, json!({"value": format!("1{}", "+1".repeat(128))})), 129.0)); +} + +#[test] +fn keys_the_commands_do_not_take_are_refused() { + let s = session(); + s.check_params("addon.units.convert", &json!({"value": 1, "unit": "mm"})).unwrap(); + s.check_params("addon.units.selectionSize", &json!({})).unwrap(); + for (id, p) in [ + ("addon.units.convert", json!({"value": 1, "units": "mm"})), + ("addon.units.convert", json!({"value": 1, "ids": [1]})), + ("addon.units.selectionSize", json!({"ids": [1]})), + ("addon.units.selectionSize", json!({"value": 1})), + ] { + match s.check_params(id, &p) { + Err(EngineError::BadParams { cmd, .. }) => assert_eq!(cmd, id, "{p}"), + other => panic!("{id} {p}: expected BadParams, got {other:?}"), + } + } +} + +#[test] +fn the_selection_size_follows_preview_bounds_and_selected_anchors() { + let mut s = session(); + let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 72, "height": 36})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [id], "color": "#000000"})).unwrap(); + s.execute("stroke.set", &json!({"ids": [id], "weight": 10})).unwrap(); + let wh = |s: &mut Session| { + let r = s.execute("addon.units.selectionSize", &json!({})).unwrap(); + (r["width"]["points"].as_f64().unwrap(), r["height"]["points"].as_f64().unwrap()) + }; + assert_eq!(wh(&mut s), (72.0, 36.0), "geometric bounds"); + // Use Preview Bounds: the stroke's outer half on every side. + s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": true})).unwrap(); + let (w, h) = wh(&mut s); + assert!(near(w, 82.0) && near(h, 46.0), "{w} × {h}"); + s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": false})).unwrap(); + // Two neighboring anchors selected (Direct Selection): the box around them, one edge of the + // rectangle. + s.execute("select.anchors", &json!({"id": id, "anchors": [[0, 0], [0, 1]], "mode": "set"})).unwrap(); + let (w, h) = wh(&mut s); + assert!((near(w, 72.0) && near(h, 0.0)) || (near(w, 0.0) && near(h, 36.0)), "{w} × {h}"); +} + +#[test] +fn it_needs_no_document_and_changes_nothing() { + let mut s = Session::new(); + assert!(near(convert(&mut s, json!({"value": "1in"}))["points"].as_f64().unwrap(), 72.0)); + let mut s = session(); + let (before, steps) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()); + convert(&mut s, json!({"value": "5mm"})); + assert_eq!(s.doc().unwrap().history.undo.len(), steps); + assert!(*s.doc().unwrap().doc == *before); +} + +#[test] +fn bad_values_and_units_are_refused() { + let mut s = session(); + for p in [ + json!({}), + json!({"value": null}), + json!({"value": "abc"}), + json!({"value": "10 furlongs"}), + json!({"value": "1in/0"}), + json!({"value": "1e400"}), + // Finite in points, too large in Q and Ha. + json!({"value": 1.5e308}), + json!({"value": "1.5e308"}), + // A thousands comma is refused, as the number fields refuse it. + json!({"value": "1,000 mm"}), + json!({"value": "1,000.5"}), + json!({"value": "+1,000"}), + json!({"value": "1,000\""}), + json!({"value": "1,000'"}), + // A long expression is refused instead of exhausting the stack. + json!({"value": format!("1{}", "+1".repeat(200_000))}), + json!({"value": format!("1{}", "+1".repeat(129))}), + json!({"value": true}), + json!({"value": [1]}), + json!({"value": 1, "unit": "furlongs"}), + json!({"value": 1, "unit": 5}), + json!({"value": 1, "unit": ["mm"]}), + // Only an omitted `unit` is points. + json!({"value": 1, "unit": null}), + ] { + match s.execute("addon.units.convert", &p) { + Err(EngineError::BadParams { cmd, .. }) => assert_eq!(cmd, "addon.units.convert", "{p}"), + other => panic!("{p}: expected BadParams, got {other:?}"), + } + } +} + +#[test] +fn a_long_value_or_unit_is_refused_with_a_short_message() { + let mut s = session(); + let long = "9".repeat(100_000); + for (p, says) in [ + (json!({"value": long.clone()}), format!("`value` must be a number, not \"{}…\"", "9".repeat(64))), + (json!({"value": [long.clone()]}), "`value` must be a number, not […]".to_string()), + (json!({"value": 1, "unit": long.clone()}), format!("unknown units `{}…`", "9".repeat(64))), + (json!({"value": 1, "unit": "furlongs"}), "unknown units `furlongs`".to_string()), + (json!({"value": "a\"b\nc"}), "`value` must be a number, not \"a\\\"b\\nc\"".to_string()), + ] { + match s.execute("addon.units.convert", &p) { + Err(e @ EngineError::BadParams { .. }) => assert!(e.to_string().ends_with(&says), "{e}"), + other => panic!("expected BadParams, got {other:?}"), + } + } +} + +#[test] +fn the_selection_size_is_the_transform_panels() { + let mut s = session(); + assert!(s.execute("addon.units.selectionSize", &json!({})).is_err(), "nothing selected"); + let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 72, "height": 36})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let steps = s.doc().unwrap().history.undo.len(); + let r = s.execute("addon.units.selectionSize", &json!({})).unwrap(); + assert!(near(r["width"]["points"].as_f64().unwrap(), 72.0)); + assert!(near(r["height"]["points"].as_f64().unwrap(), 36.0)); + assert_eq!(row(&r["width"], "inches")["text"], "1 in"); + assert_eq!(row(&r["height"], "picas")["text"], "3 p"); + // A turned object keeps its own sides, as the Transform panel's W and H show them. + s.execute("object.rotate", &json!({"angle": 30})).unwrap(); + let r = s.execute("addon.units.selectionSize", &json!({})).unwrap(); + let b = s.transform_box(&s.doc().unwrap().selection.objects).unwrap(); + assert!(near(r["width"]["points"].as_f64().unwrap(), b.rect.width())); + assert!(near(r["width"]["points"].as_f64().unwrap(), 72.0)); + assert!(near(r["height"]["points"].as_f64().unwrap(), 36.0)); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "only the rotation is a step"); +} diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index c4f35dfc3f..c026a1086e 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -36,8 +36,8 @@ mod symbols; pub(crate) use brushes::{apply_brush, brush_targets, stroke_paint}; use brushes::{ - brush_apply, brush_delete, brush_duplicate, brush_freehand, brush_get, brush_list, brush_move, brush_new, brush_options, brush_place_art, - brush_remove, brush_replace_art, brush_selection_art, brush_set_current, brush_unused, expand_brush, + brush_apply, brush_delete, brush_duplicate, brush_freehand, brush_get, brush_list, brush_move, brush_new, brush_object_options, brush_options, + brush_place_art, brush_remove, brush_replace_art, brush_selection_art, brush_set_current, brush_unused, expand_brush, }; pub(crate) use dynamic::{edit_part, fit_parts, part_only, selected_part}; use dynamic::{symbol_instance_reset, symbol_instance_select_part, symbol_instance_set_appearance}; @@ -165,10 +165,19 @@ pub fn specs() -> Vec { "Brush Options…", [], None, - "{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180° (counter-clockwise from level), roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180° (counter-clockwise), modes: [fixed|random|pressure|tilt|bearing|rotation for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°), rotation_relative_to_path. art: width 1..1000%, width_mode: null (fixed)|pressure|tilt|bearing|rotation, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest; tilt: width with the pen lying flat to width_max upright; bearing and rotation: width at −180° to width_max at 180°; half way on a stroke drawn without that input), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art (drawn as the corner that joins a side tile on its right to one below it) or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}", + "{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180° (counter-clockwise from level), roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180° (counter-clockwise), modes: [fixed|random|pressure|tilt|bearing|rotation for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°), rotation_relative_to_path, hue_jitter 0..180° (each copy turns the hue of its solid colors, after the colorization, by its own amount up to this far either way, the same on every redraw; colors without a hue stay; 0: off). art: width 1..1000%, width_mode: null (fixed)|pressure|tilt|bearing|rotation, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest; tilt: width with the pen lying flat to width_max upright; bearing and rotation: width at −180° to width_max at 180°; half way on a stroke drawn without that input), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art (drawn as the corner that joins a side tile on its right to one below it) or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}", has_doc, brush_options ), + cmd!( + "brush.objectOptions", + "Options of Selected Object…", + [], + None, + "{ids?|id?, params?: {…the fields brush.options takes that a path can set for itself: calligraphic angle (counter-clockwise from level), roundness, size, variation, modes; scatter size, spacing, scatter, rotation (counter-clockwise), modes, rotation_relative_to_path, colorization; art width, width_mode, width_max, flip_along, flip_across, overlap, colorization; pattern scale, spacing, fit, flip_along, flip_across, colorization (values outside their ranges are clamped; a colorization object changes only the fields it gives; a null item of an array such as size: [40, null] keeps each stroke's own item, else the brush's)}, reset?: bool} set the brush settings of the brushed strokes of the selected paths on those strokes only, leaving the brush and its other strokes as they are (the Brushes panel's Options of Selected Object); params add to each stroke's own settings, a mode params does not set (no modes, or a null item) stays the one each stroke draws with when a changed variation or range would change it, a setting equal to the brush's own value is dropped, and reset: true clears them so the strokes draw the brush again; without params or reset nothing changes; one undo step, none when nothing changes. The brushes' own edits (brush.options) still reach the settings a stroke does not set, applying a brush (brush.apply, stroke.setAdvanced or a brush.freehand extend with another brush) or removing it clears them, and a renamed brush keeps them. Refused with nothing painted with a brush selected, for paths painted with brushes of different types, for a bristle brush, for a field the type does not take and for a value of the wrong kind → {ids: the brushed paths, changed: the paths whose settings changed, options: the first stroke's own settings}", + has_doc, + brush_object_options + ), cmd!( "object.expandBrush", "Expand Brush Strokes", @@ -202,7 +211,7 @@ pub fn specs() -> Vec { "New Symbol…", [], None, - "{name?, ids?|id?, registration?: 0..8 (9-point grid, 4 = centre; Symbol Options › Registration), exportType?: movieClip (default)|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static (default)|dynamic (Symbol Options › Symbol Type), alignToPixelGrid?: bool (default false; Symbol Options › Align to Pixel Grid)} make a symbol from the selection and replace it with an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds; nineSlice is Symbol Options › Enable Guides for 9-Slice Scaling, nineSliceGuides [left, top, right, bottom] as fractions of the natural size in from each edge, each -16..16 (below 0 or above 1 puts a guide outside the art), with left + right < 1 and top + bottom < 1 (default a quarter each); an instance of a symbol with guides keeps its corners' size when scaled, its edges stretch along their length and its center in both directions; alignToPixelGrid keeps the symbol's instances on the pixel grid as symbol.options describes → {name, id, registration, exportType, nineSlice, type, alignToPixelGrid}", + "{name?, ids?|id?, registration?: 0..8 (9-point grid, 4 = centre; Symbol Options › Registration), exportType?: movieClip (default)|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static (default)|dynamic (Symbol Options › Symbol Type), alignToPixelGrid?: bool (default false; Symbol Options › Align to Pixel Grid), keepArt?: false} make a symbol from the selection and replace it with an instance, or with keepArt: true leave the selection as ordinary art where it is, still selected, with id null; a frame of threaded text in the selection that becomes an instance leaves its thread with the text it shows, which the symbol's art holds; nineSlice is Symbol Options › Enable Guides for 9-Slice Scaling, nineSliceGuides [left, top, right, bottom] as fractions of the natural size in from each edge, each -16..16 (below 0 or above 1 puts a guide outside the art), with left + right < 1 and top + bottom < 1 (default a quarter each); an instance of a symbol with guides keeps its corners' size when scaled, its edges stretch along their length and its center in both directions; alignToPixelGrid keeps the symbol's instances on the pixel grid as symbol.options describes → {name, id, registration, exportType, nineSlice, type, alignToPixelGrid}", has_selection, symbol_new ), @@ -256,7 +265,7 @@ pub fn specs() -> Vec { "Redefine Symbol", [], None, - "{name, ids?|id?} replace the symbol's art with the selection (instances update, keeping their appearance changes to the objects at paths the new art still has; the selection becomes an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds) → {name, id}", + "{name, ids?|id?, keepArt?: false} replace the symbol's art with the selection (instances update, keeping their appearance changes to the objects at paths the new art still has; the selection becomes an instance, or with keepArt: true stays ordinary art where it is, still selected, and id is null; a frame of threaded text in the selection that becomes an instance leaves its thread with the text it shows, which the symbol's art holds; art that holds an instance of the symbol (opacity masks included), directly or through the symbols it nests, is refused) → {name, id}", has_selection, symbol_update ), diff --git a/crates/engine/src/cmd/brushsym/brushes.rs b/crates/engine/src/cmd/brushsym/brushes.rs index 7a92ff130a..b0ab4366d2 100644 --- a/crates/engine/src/cmd/brushsym/brushes.rs +++ b/crates/engine/src/cmd/brushsym/brushes.rs @@ -1,6 +1,7 @@ use super::{ AppearanceItem, Arc, BTreeSet, Bristle, Brush, BrushKind, Color, Document, EngineError, Node, NodeId, NodeKind, Paint, Result, Session, Value, anchor, bad, brush, check_numbers, find_command, ids_json, json, name_param, names_param, ok, roots, selection_art, set_unknown, str_param, + switch_or, }; // ---------- brushes ---------- @@ -31,7 +32,12 @@ pub(super) fn brush_list(s: &mut Session, _: &Value) -> Result { pub(super) fn brush_get(s: &mut Session, p: &Value) -> Result { let name = name_param(p, "brush.get")?; let b = brush::find(&s.doc()?.doc, name).ok_or_else(|| EngineError::Other(format!("no brush named `{name}`")))?; - Ok(serde_json::to_value(b).unwrap_or_default()) + let mut v = serde_json::to_value(&b).unwrap_or_default(); + // A scatter brush saves its hue jitter only when it is not 0; brush.get shows it either way. + if let (BrushKind::Scatter(sc), Some(o)) = (&b.kind, v.as_object_mut()) { + o.entry("hue_jitter").or_insert(json!(sc.hue_jitter)); + } + Ok(v) } /// The art `brush.new` takes from `ids` or `id`, else from the selection ([`selection_art`]). @@ -57,6 +63,8 @@ pub(crate) fn apply_brush(d: &mut Document, ids: &[NodeId], name: &str, stroke: st.width = 1.0; } st.brush = Some(name.to_string()); + // The path's own brush settings (Options of Selected Object) go with the brush they set. + st.brush_options.clear(); } } } @@ -85,6 +93,7 @@ pub(super) fn brush_remove(s: &mut Session, p: &Value) -> Result { for it in &mut n.appearance.items { if let AppearanceItem::Stroke(st) = it { st.brush = None; + st.brush_options.clear(); } } } @@ -129,13 +138,17 @@ fn merge(base: &mut Value, patch: &Value) { } } -/// Sets brush `to` on the strokes in `items` that paint with brush `from`. +/// Sets brush `to` on the strokes in `items` that paint with brush `from`. A renamed brush keeps +/// each stroke's own settings for it; a stroke left without a brush loses them. fn set_stroke_brush(items: &mut [AppearanceItem], from: &str, to: Option<&str>) { for it in items { if let AppearanceItem::Stroke(st) = it && st.brush.as_deref() == Some(from) { st.brush = to.map(str::to_string); + if to.is_none() { + st.brush_options.clear(); + } } } } @@ -494,6 +507,166 @@ pub(super) fn brush_options(s: &mut Session, p: &Value) -> Result { Ok(json!({ "name": out })) } +/// Options of Selected Object: set the brush settings of the brushed strokes of the selected paths +/// (or `ids`) on those strokes only, leaving the brush as it is. `params` adds to each stroke's +/// own settings, `reset` clears them; without either, nothing changes and the settings are given. +pub(super) fn brush_object_options(s: &mut Session, p: &Value) -> Result { + const C: &str = "brush.objectOptions"; + let params = match p.get("params") { + None | Some(Value::Null) => serde_json::Map::new(), + Some(Value::Object(o)) => o.clone(), + Some(_) => { + let key = "params"; + return Err(bad(C, format!("`{key}` must be an object"))); + } + }; + let reset = switch_or(p, "reset", false, C)?; + if reset && !params.is_empty() { + return Err(bad(C, "give `params` or `reset`, not both")); + } + let d = &s.doc()?.doc; + let lib = brush::library(d); + let ids = brush_targets(d, &roots(s, p)?); + // Each brushed stroke: its path, its place in the appearance, its brush and its settings now. + let mut strokes = vec![]; + for id in &ids { + let Some(n) = d.node(*id) else { continue }; + for (i, it) in n.appearance.items.iter().enumerate() { + let AppearanceItem::Stroke(st) = it else { continue }; + if let Some(b) = st.brush.as_deref().and_then(|name| lib.iter().find(|b| b.name == name)) { + strokes.push((*id, i, b, &st.brush_options)); + } + } + } + let Some(&(_, _, first, _)) = strokes.first() else { return Err(bad(C, "no path painted with a brush is selected")) }; + if strokes.iter().any(|(_, _, b, _)| b.kind.type_id() != first.kind.type_id()) { + return Err(bad(C, "the selected paths are painted with brushes of different types")); + } + // Only a bristle brush has none. + if first.kind.stroke_option_keys().is_empty() { + return Err(bad(C, "a bristle brush has no options of its own on a path")); + } + let out: Vec = ids.iter().copied().filter(|id| strokes.iter().any(|(s, ..)| s == id)).collect(); + // Without params or reset the settings are only given: nothing is normalized or changed. + if !reset && params.is_empty() { + let keys = first.kind.stroke_option_keys(); + let own: serde_json::Map = + strokes[0].3.iter().filter(|(k, _)| keys.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone())).collect(); + return Ok(json!({ "ids": ids_json(&out), "changed": [], "options": own })); + } + let mut changes = vec![]; + let mut options = None; + for (id, i, b, own) in &strokes { + let next = if reset { + serde_json::Map::new() + } else { + // Settings saved for another type of brush are left out. + let keys = b.kind.stroke_option_keys(); + let mut merged: serde_json::Map = + own.iter().filter(|(k, _)| keys.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone())).collect(); + let was = merged.clone(); + // A colorization object changes only the fields it gives, and a null item of an + // array keeps the stroke's own item (else the brush's). + for (k, v) in ¶ms { + let next = match (merged.get(k), v) { + (Some(Value::Object(mine)), Value::Object(fields)) if k == "colorization" => { + let mut c = mine.clone(); + c.extend(fields.clone()); + Value::Object(c) + } + (Some(mine), _) => brush::keep_items(v, mine), + (None, _) => v.clone(), + }; + merged.insert(k.clone(), next); + } + keep_drawn_modes(b, &was, ¶ms, &mut merged); + keep_largest_width(b, &was, ¶ms, &mut merged); + b.stroke_options_that_differ(&merged).map_err(|e| bad(C, e))? + }; + options.get_or_insert_with(|| next.clone()); + if &next != *own { + changes.push((*id, *i, next)); + } + } + let changed: Vec = ids.iter().copied().filter(|id| changes.iter().any(|(c, ..)| c == id)).collect(); + if !changes.is_empty() { + s.edit("Options of Selected Object", |d, _| { + for (id, i, next) in changes { + if let Some(AppearanceItem::Stroke(st)) = d.node_mut(id).and_then(|n| n.appearance.items.get_mut(i)) { + st.brush_options = next; + } + } + Ok(()) + })?; + } + Ok(json!({ "ids": ids_json(&out), "changed": ids_json(&changed), "options": options.unwrap_or_default() })) +} + +/// The modes brush `b` draws with, for a Calligraphic or a Scatter brush. +fn drawn_modes(b: &Brush) -> Option> { + let modes = match &b.kind { + BrushKind::Calligraphic(c) => serde_json::to_value(c.modes()), + BrushKind::Scatter(s) => serde_json::to_value(s.modes()), + _ => return None, + }; + match modes { + Ok(Value::Array(m)) => Some(m), + _ => None, + } +} + +/// Keep each mode a stroke of brush `b` draws with (with its own settings `was`) that `params` +/// does not set (no `modes`, or a `null` item) and that `merged`, its settings with `params`, +/// would change. A mode the stroke leaves to its values follows them, so without this a changed +/// variation or range would also change the mode. +fn keep_drawn_modes( + b: &Brush, + was: &serde_json::Map, + params: &serde_json::Map, + merged: &mut serde_json::Map, +) { + let given = match params.get("modes") { + None | Some(Value::Null) => vec![], + Some(Value::Array(m)) => m.clone(), + // A value of the wrong kind is refused when the settings are checked. + Some(_) => return, + }; + let (Some(before), Some(after)) = + (b.with_stroke_options(was).ok().as_ref().and_then(drawn_modes), b.with_stroke_options(merged).ok().as_ref().and_then(drawn_modes)) + else { + return; + }; + if before == after { + return; + } + let kept = before.into_iter().zip(after).enumerate().map(|(j, (w, a))| if given.get(j).is_some_and(|g| !g.is_null()) { a } else { w }).collect(); + merged.insert("modes".into(), Value::Array(kept)); +} + +/// Keep the largest width a stroke of art brush `b` draws with (with its own settings `was`) when +/// `params` sets `width` and no `width_max`. Without a `width_max` of its own the largest width is +/// the width, so without this a changed width would also change the largest width. +fn keep_largest_width( + b: &Brush, + was: &serde_json::Map, + params: &serde_json::Map, + merged: &mut serde_json::Map, +) { + if params.get("width").is_none_or(Value::is_null) || params.get("width_max").is_some_and(|m| !m.is_null()) { + return; + } + let art = |o: &serde_json::Map| match b.with_stroke_options(o).ok().map(|b| b.kind) { + Some(BrushKind::Art(a)) => Some(a), + _ => None, + }; + let (Some(before), Some(after)) = (art(was), art(merged)) else { return }; + let follows_pen = |a: &brush::ArtBrush| a.width_mode.is_some_and(|m| m.follows_pen()); + // Only a width that followed the pen has a largest width, and only one that still does uses it. + if before.width_max.is_none() && follows_pen(&before) && follows_pen(&after) && after.width != before.width { + merged.insert("width_max".into(), json!(before.width)); + } +} + /// The name `brush.placeArt` gives each pattern brush tile it places, by tile, in the order it /// places them; `brush.replaceArt` reads a group of that name as that tile. const TILE_NAMES: [&str; 5] = ["Side Tile", "Outer Corner Tile", "Inner Corner Tile", "Start Tile", "End Tile"]; diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index cecd314858..f5245bc9af 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -253,6 +253,9 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result { let nine = nine_slice_param(p, C, None)?.flatten(); let dynamic = type_param(p, C)?.unwrap_or(false); let pixel = pixel_grid_param(p, C)?.unwrap_or(false); + // `keepArt` leaves the art as ordinary art instead of replacing it with an instance. + let keep_art = switch_or(p, "keepArt", false, C)?; + let iso = s.doc()?.isolation; // Keep the art where it was: the geometric centre stays at `c`, whatever the registration is. let place = place_xf(c + reg.offset_from_center(size.0, size.1), size, reg); let id = s.edit("New Symbol", |d, sel| { @@ -264,13 +267,20 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result { d.set_symbol_export_type(&name, export); d.set_symbol_nine_slice(&name, nine); d.set_symbol_pixel_aligned(&name, pixel); + if keep_art { + // The art stays where it is and stays selected, apart from art that is hidden or + // locked, in a hidden or locked group or layer, or on a locked artboard. + let locks = d.locked_artboards(); + sel.set(ids.iter().copied().filter(|i| crate::cmd::select::is_selectable(d, iso, &locks, *i))); + return Ok(None); + } let id = instance_in_place(d, &ids, &name, place)?; sel.set([id]); - Ok(id) + Ok(Some(id)) })?; Ok(json!({ "name": name, - "id": id.0, + "id": id.map(|i| i.0), "registration": reg.0, "exportType": export.id(), "nineSlice": nine.map_or(Value::Null, SymbolNineSlice::to_value), @@ -612,6 +622,8 @@ pub(super) fn symbol_update(s: &mut Session, p: &Value) -> Result { } // Redefining the symbol being edited leaves symbol editing mode in the same step. let session = s.doc()?.doc.symbol_edit.clone().filter(|e| e.symbol == name); + // `keepArt` leaves the art as ordinary art instead of replacing it with an instance. + let keep_art = switch_or(p, "keepArt", false, C)?; if session.is_some() { crate::cmd::settle_interaction(s)?; s.end_text_edit(); @@ -625,10 +637,20 @@ pub(super) fn symbol_update(s: &mut Session, p: &Value) -> Result { } } let mut art = selection_art(s, p)?.ok_or_else(|| EngineError::Other("nothing selected".into()))?; + // Nor can art that holds an instance of it, directly or through the symbols it nests. + if crate::cmd::symboledit::holds_symbol(&s.doc()?.doc, &art, &name, &mut Default::default()) { + return Err(EngineError::Other("a symbol can't hold an instance of itself".into())); + } crate::cmd::threads::keep_shown_text(&s.doc()?.doc, &mut art); let (art, size, c) = normalize(art)?; let old = natural_size(&s.doc()?.doc, &name); let editing = session.is_some(); + // The isolation the kept art is selected in: the one from before symbol editing mode when + // the step leaves it. + let iso = match &session { + Some(se) => se.back_isolation, + None => s.doc()?.isolation, + }; let id = s.edit("Redefine Symbol", |d, sel| { if editing { crate::cmd::symboledit::finish(d, sel); @@ -647,15 +669,22 @@ pub(super) fn symbol_update(s: &mut Session, p: &Value) -> Result { } // Each instance keeps its appearance changes to the objects the new art still has. fit_overrides(d, &instances); + if keep_art { + // The art stays where it is and stays selected, apart from art that is hidden or + // locked, in a hidden or locked group or layer, or on a locked artboard. + let locks = d.locked_artboards(); + sel.set(ids.iter().copied().filter(|i| crate::cmd::select::is_selectable(d, iso, &locks, *i))); + return Ok(None); + } let reg = d.symbol_registration(&name); let id = instance_in_place(d, &ids, &name, place_xf(c + reg.offset_from_center(size.0, size.1), size, reg))?; sel.set([id]); - Ok(id) + Ok(Some(id)) })?; if let Some(se) = &session { crate::cmd::symboledit::leave_editing(s, se)?; } - Ok(json!({ "name": name, "id": id.0 })) + Ok(json!({ "name": name, "id": id.map(|i| i.0) })) } /// How many levels of nested instances Delete Symbol expands before it gives up. diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index a15af16360..739759afe6 100644 --- a/crates/engine/src/cmd/buildcmds.rs +++ b/crates/engine/src/cmd/buildcmds.rs @@ -659,6 +659,7 @@ fn fit_to_edge(row: &mut AppearanceItem, run: Option<(f64, bool, bool, bool)>) { } s.profile = None; s.brush = None; + s.brush_options.clear(); } if !starts { s.start_arrow = None; diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index f912fce7ae..0a98ddd9bc 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -579,6 +579,11 @@ impl SwatchChoices { Some(v) => Ok(Self { all: one(v)?, by_name: BTreeMap::new() }), } } + /// Add for every conflict: each pasted swatch whose name the document gives another color + /// comes in renamed. + pub(crate) fn add_all() -> Self { + Self { all: SwatchChoice::Add, by_name: BTreeMap::new() } + } fn of(&self, name: &str) -> SwatchChoice { self.by_name.get(name).copied().unwrap_or(self.all) } diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index a529a3bea9..18374f8302 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -121,7 +121,7 @@ pub fn specs() -> Vec { "Separations Preview", [], None, - "{on?: bool, plates?: [names], toggle?: plate, only?: plate} Separations Preview: show the chosen plates (one plate = greyscale ink coverage) → {on, plates: [{name, spot, visible, rgb}]}", + "{on?: bool, plates?: [names], toggle?: plate, only?: plate, soloToggle?: plate (only that plate, or every plate when it is the only one shown)} Separations Preview: show the chosen plates (one plate = grayscale ink coverage) → {on, plates: [{name, spot, visible, rgb}]}", always, separations ), @@ -754,10 +754,12 @@ fn map_art_colors(n: &mut vectorcraft_doc::Node, f: &mut dyn FnMut(&Color, proof } /// `f` applied to the colors in `n`'s subtree that [`proof::map_node_colors`] does not visit: the -/// effect colors ([`map_effect_colors`]), the series paints and label styles a graph keeps +/// effect colors ([`map_effect_colors`]), the Hue Shift key colors of strokes' own brush settings +/// ([`map_stroke_brush_keys`]), the series paints and label styles a graph keeps /// ([`map_graph_colors`]) and the art of every opacity mask. fn map_more_colors(n: &mut vectorcraft_doc::Node, f: &mut dyn FnMut(&Color, proof::Link) -> Color) { map_effect_colors(&mut n.appearance, f); + map_stroke_brush_keys(&mut n.appearance, f); if let Some(e) = n.extras_if_any() { if let Some(g) = e.graph.as_deref_mut() { map_graph_colors(g, f); @@ -773,6 +775,23 @@ fn map_more_colors(n: &mut vectorcraft_doc::Node, f: &mut dyn FnMut(&Color, proo } } +/// `f` applied to the Hue Shift key color of each stroke's own brush settings in appearance `a` +/// (Options of Selected Object, `colorization.key` of [`StrokeLayer::brush_options`]); a key +/// that does not read is left as it is. +/// +/// [`StrokeLayer::brush_options`]: vectorcraft_doc::StrokeLayer::brush_options +fn map_stroke_brush_keys(a: &mut vectorcraft_doc::Appearance, f: &mut dyn FnMut(&Color, proof::Link) -> Color) { + for it in &mut a.items { + let vectorcraft_doc::AppearanceItem::Stroke(st) = it else { continue }; + let Some(c) = st.brush_options.get_mut("colorization").and_then(Value::as_object_mut) else { continue }; + let Some(key) = c.get("key").and_then(|k| serde_json::from_value::(k.clone()).ok()) else { continue }; + let n = f(&key, None); + if n != key { + c.insert("key".into(), json!(n)); + } + } +} + /// Whether art color `c` is the Hue Shift key color `key`, with the tolerance the brush's /// colorization matches it with. fn matches_key(c: &Color, key: &Color) -> bool { @@ -1036,6 +1055,13 @@ fn separations(s: &mut Session, p: &Value) -> Result { if let Some(n) = text_param(p, "only", C)? { v.separations = Some(vec![check(n)?]); } + // The panel's Alt-click on a plate's eye: that plate alone, or every plate when it already + // shows alone among the active document's plates. + if let Some(n) = text_param(p, "soloToggle", C)? { + let n = check(n)?; + let alone = v.separations.as_ref().is_some_and(|vis| all.iter().filter(|a| vis.contains(a)).eq([&n])); + v.separations = Some(if alone { all.clone() } else { vec![n] }); + } if let Some(n) = text_param(p, "toggle", C)? { let n = check(n)?; let vis = v.separations.get_or_insert_with(|| all.clone()); diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 013b373d19..803057885a 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -62,7 +62,7 @@ pub fn specs() -> Vec { "Circle Through Points", [], None, - "{points?: [[x, y], [x, y], [x, y]] (left out: the three selected anchor points, where a path selected whole counts all its anchors and selected segments' ends do not count)} → {id, cx, cy, radius}: a circle with the current paint whose edge passes through the three points, not pixel-aligned even while Align New Objects to Pixel Grid is on; two points that are the same or three on one line are an error, and nothing is drawn", + "{points?: [[x, y], [x, y]] or [[x, y], [x, y], [x, y]] (two: the ends of a diameter; left out: the two or three selected anchor points, where a path selected whole counts all its anchors and selected segments' ends do not count)} → {id, cx, cy, radius}: a circle with the current paint whose edge passes through the points, not pixel-aligned even while Align New Objects to Pixel Grid is on; two points that are the same, three on one line, or a circle reaching past the canvas are an error, and nothing is drawn", has_doc, circle_through_points ), @@ -126,7 +126,7 @@ pub fn specs() -> Vec { "Create Text", [], None, - "{x, y, text, rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt 0.1..1296 (outside it: an error, and no type is made), font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (as text.areaOptions)}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on", + "{x, y, text, rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt 0.1..1296 (outside it: an error, and no type is made), font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused; size, font, style and color left out come from [Normal Character Style], the defaults unless the document redefined it), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (as text.areaOptions)}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on", has_doc, text_create ), @@ -413,16 +413,16 @@ fn ellipse(s: &mut Session, p: &Value) -> Result { add_art_turned(s, "Ellipse", path_kind(live.to_path(), Some(live)), rotation) } -/// A live ellipse whose edge passes through three points: `points`, or the three selected anchor -/// points ([`selected_anchor_points`]). One undo step, named as an Ellipse tool drag is. +/// A live ellipse whose edge passes through two or three points: `points`, or the two or three +/// selected anchor points ([`selected_anchor_points`]). Two points are the ends of a diameter. One +/// undo step, named as an Ellipse tool drag is. fn circle_through_points(s: &mut Session, p: &Value) -> Result { const C: &str = "shape.circleThroughPoints"; let points = match p.get("points").filter(|v| !v.is_null()) { - Some(v) => three_points(v).ok_or_else(|| bad(C, "`points` must be three [x, y] pairs of numbers"))?, - None => selected_anchor_points(s)?.ok_or_else(|| bad(C, "direct-select three anchor points, or give `points`"))?, + Some(v) => two_or_three_points(v).ok_or_else(|| bad(C, "`points` must be two or three [x, y] pairs of numbers"))?, + None => selected_anchor_points(s)?.ok_or_else(|| bad(C, "direct-select two or three anchor points, or give `points`"))?, }; - let [a, b, c] = points; - let (center, radius) = shapes::circle_through(a, b, c) + let (center, radius) = shapes::circle_through_points(&points) .ok_or_else(|| bad(C, "no circle passes through these points: two are the same or all three lie on one line"))?; let r = Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius); let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) }; @@ -434,24 +434,25 @@ fn circle_through_points(s: &mut Session, p: &Value) -> Result { Ok(out) } -/// The three points `[[x, y], [x, y], [x, y]]` holds, each pair two finite numbers. -fn three_points(v: &Value) -> Option<[Point; 3]> { +/// The two or three points `[[x, y], [x, y]]` or `[[x, y], [x, y], [x, y]]` holds, each pair two +/// finite numbers. +fn two_or_three_points(v: &Value) -> Option> { let pair = |v: &Value| match v.as_array().map(Vec::as_slice) { Some([x, y]) => x.as_f64().zip(y.as_f64()).filter(|(x, y)| x.is_finite() && y.is_finite()).map(|(x, y)| Point::new(x, y)), _ => None, }; - match v.as_array().map(Vec::as_slice) { - Some([a, b, c]) => Some([pair(a)?, pair(b)?, pair(c)?]), + match v.as_array() { + Some(pairs) if matches!(pairs.len(), 2 | 3) => pairs.iter().map(pair).collect(), _ => None, } } -/// The positions of the selected anchor points, when there are exactly three. They are counted as +/// The positions of the selected anchor points, when there are two or three. They are counted as /// the other anchor commands count them ([`super::path::anchor_targets`]): a selected path with /// anchors picked by Direct Selection gives those, and a path selected whole gives all of its own. /// A selected segment's ends are not selected anchor points, so a selection with segments gives /// none; so does a selection holding an object that is not a path, or an anchor that is gone. -fn selected_anchor_points(s: &Session) -> Result> { +fn selected_anchor_points(s: &Session) -> Result>> { let st = s.doc()?; if st.selection.segments.values().any(|set| !set.is_empty()) { return Ok(None); @@ -472,10 +473,7 @@ fn selected_anchor_points(s: &Session) -> Result> { return Ok(None); } } - Ok(match points.as_slice() { - &[a, b, c] => Some([a, b, c]), - _ => None, - }) + Ok(matches!(points.len(), 2 | 3).then_some(points)) } /// The whole-number count `p` gives for `key` (`5` or `5.0`), or `default` when it is left out or @@ -942,7 +940,13 @@ fn text_create(s: &mut Session, p: &Value) -> Result { let id = made.get("id").and_then(Value::as_u64).map(NodeId); let made = super::typecmd::with_bounds(s, id, made); let mut made = super::typecmd::with_overflow(s, id.as_slice(), made); - if p.get("font").is_some() || p.get("style").is_some() { + // A face from a redefined [Normal Character Style] is checked too, as one given here is. + let normal_face = s + .doc() + .ok() + .and_then(|d| super::textstyles::style_attrs(&d.doc, false, super::textstyles::NORMAL_CHAR)) + .is_some_and(|m| m.contains_key("font_family") || m.contains_key("font_style")); + if p.get("font").is_some() || p.get("style").is_some() || normal_face { let runs = match id.and_then(|i| s.doc().ok()?.doc.node(i)).map(|n| &n.kind) { Some(NodeKind::Text(t)) => t.runs.iter().flat_map(super::fonts::run_fonts).collect(), _ => Default::default(), @@ -970,8 +974,9 @@ pub(crate) fn new_type_para() -> vectorcraft_doc::ParaStyle { /// The paragraph alignment, leading model and character alignment new type starts with (`t`'s /// paragraph and runs): `justify` from `p` (else as [`new_type_para`] left it), `leadingModel` -/// and `charAlign` from `p`, else em box top to top and em box centre while the -/// interface is in Japanese (#432), else the Roman baseline for both. Noted in the journal, so a +/// and `charAlign` from `p` (`charAlign` else from a redefined `[Normal Character Style]` that +/// sets it), else em box top to top and em box centre while the interface is in Japanese (#432), +/// else the Roman baseline for both. Noted in the journal, so a /// replay sets the same whatever the interface. pub(crate) fn new_type_alignment(s: &mut Session, p: &Value, cmd: &str, t: &mut TextObject) -> Result<()> { use vectorcraft_doc::{CharAlign, LeadingModel}; @@ -991,7 +996,14 @@ pub(crate) fn new_type_alignment(s: &mut Session, p: &Value, cmd: &str, t: &mut l } }; - let align = match super::textedit::char_align_param(p, cmd)? { + // A redefined [Normal Character Style] that sets Character Alignment gives it to new type. + let normal_align = s + .doc() + .ok() + .and_then(|d| super::textstyles::style_attrs(&d.doc, false, super::textstyles::NORMAL_CHAR)) + .filter(|m| m.contains_key("charAlign")) + .and(t.runs.first().map(|r| r.style.char_align)); + let align = match super::textedit::char_align_param(p, cmd)?.or(normal_align) { Some(a) => a, None => { let a = if japanese { CharAlign::EmBoxCenter } else { CharAlign::RomanBaseline }; @@ -1019,17 +1031,25 @@ pub(crate) fn new_area_fit(s: &Session, p: &Value, c: &str, t: &mut TextObject) } /// The character style new type gets: `size`, `font`, `style` and `color` from `p` (an RGB -/// `color` in a CMYK document as [`super::paint::new_color`] stores it), else the defaults, -/// filled as `[Normal Character Style]` is (black unless redefined; never the current fill, -/// #7975), in the document's -/// language. A `size` outside [`super::typecmd::TYPE_SIZES`] is an error. +/// `color` in a CMYK document as [`super::paint::new_color`] stores it), else +/// `[Normal Character Style]`'s (the default font, size and black fill unless redefined; +/// never the current fill, #7975), in the style's language, else the document's. A `size` outside +/// [`super::typecmd::TYPE_SIZES`] is an error. pub(crate) fn new_type_style(s: &Session, p: &Value, cmd: &str) -> Result { - let mut style = CharStyle::default(); + let mut style = s.doc().map_or_else(|_| CharStyle::default(), |d| super::textstyles::normal_char_style(&d.doc)); if let Some(sz) = p.get("size").and_then(Value::as_f64) { style.size = super::typecmd::given_type_size(sz, cmd)?; } + if str_param(p, "font").is_some() || str_param(p, "style").is_some() { + // A face given to the command takes its own version and axis settings, as a font change + // does, not those [Normal Character Style] gave another face. + style.font_version = None; + style.font_axes.clear(); + } if let Some(f) = str_param(p, "font") { style.font_family = f.to_string(); + // A family alone starts in Regular, whatever style [Normal Character Style] has. + style.font_style = CharStyle::default().font_style; } if let Some(f) = str_param(p, "style") { style.font_style = f.to_string(); @@ -1039,12 +1059,15 @@ pub(crate) fn new_type_style(s: &Session, p: &Value, cmd: &str) -> Result vectorcraft_color::Paint::solid(super::paint::new_color(s, p, c)), - None => s.doc().map_or_else(|_| CharStyle::default().fill, |d| super::textstyles::normal_char_fill(&d.doc)), + None => style.fill, }; - // In the language Document Setup chose, else Preferences › Hyphenation › Default Language; none - // for the default. Type already in a document keeps its own. - let chosen = |name: &str| vectorcraft_doc::setup::char_language(name).ok().flatten(); - let document = s.doc().ok().and_then(|d| chosen(&d.doc.setup.language)); - style.language = document.or_else(|| chosen(&s.prefs.hyphenation_language)).map(str::to_string); + // In the language a redefined [Normal Character Style] gives, else the one Document Setup chose, + // else Preferences › Hyphenation › Default Language; none for the default. Type already in a + // document keeps its own. + if style.language.is_none() { + let chosen = |name: &str| vectorcraft_doc::setup::char_language(name).ok().flatten(); + let document = s.doc().ok().and_then(|d| chosen(&d.doc.setup.language)); + style.language = document.or_else(|| chosen(&s.prefs.hyphenation_language)).map(str::to_string); + } Ok(style) } diff --git a/crates/engine/src/cmd/dimension.rs b/crates/engine/src/cmd/dimension.rs index 183cbd3746..955401b923 100644 --- a/crates/engine/src/cmd/dimension.rs +++ b/crates/engine/src/cmd/dimension.rs @@ -3,10 +3,8 @@ use super::{CommandSpec, EngineError, Result, Session, cmd, has_doc}; use serde_json::{Value, json}; use std::sync::Arc; use vectorcraft_color::{Color, Paint}; -use vectorcraft_doc::dimension::{ - ArrowStyle, Dimension, DimensionMode, DimensionOptions, DimensionSource, LineType, Orientation, TextAlignment, TextPosition, -}; -use vectorcraft_doc::{Appearance, Arrowhead, CharStyle, ColorMode, Dash, Document, Node, NodeId, NodeKind, TextObject}; +use vectorcraft_doc::dimension::{Dimension, DimensionMode, DimensionOptions, DimensionSource, LineType, Orientation, TextAlignment, TextPosition}; +use vectorcraft_doc::{Appearance, CharStyle, ColorMode, Dash, Document, Node, NodeId, NodeKind, TextObject}; use vectorcraft_geom::{Affine, BezPath, PathData, Point, Vec2}; pub fn specs() -> Vec { @@ -567,12 +565,7 @@ fn appearance(o: &DimensionOptions, mode: ColorMode, ext: bool, arrows: bool) -> LineType::Solid => None, }; if arrows { - let head = match o.arrow_style { - ArrowStyle::Filled => Some(Arrowhead::Triangle), - ArrowStyle::Open => Some(Arrowhead::TriangleOpen), - ArrowStyle::Tick => Some(Arrowhead::Slash), - ArrowStyle::None => None, - }; + let head = o.arrow_style.arrowhead(); st.start_arrow = head.clone(); st.end_arrow = head; st.arrow_scale = (o.arrow_scale, o.arrow_scale); diff --git a/crates/engine/src/cmd/distortcmds.rs b/crates/engine/src/cmd/distortcmds.rs index 1e78f210e6..dc36e24380 100644 --- a/crates/engine/src/cmd/distortcmds.rs +++ b/crates/engine/src/cmd/distortcmds.rs @@ -16,7 +16,7 @@ use vectorcraft_tools::distort::{PinSet, arap, collect_points, mesh_for, project use super::edit::{duplicate_in, outermost, refuse_symbol_part, selected_roots}; use super::{ CommandSpec, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, f64_req, finite_numbers, has_doc, has_selection, matrix_param, - named_id, named_ids, number_or, object_param, ok, point_indices, point_param, str_param, switch_or, targets, + named_id, named_ids, number_or, object_param, ok, point_indices, point_param, str_param, switch_or, targets, text_param, u64_req, }; use crate::EngineError; @@ -35,7 +35,7 @@ pub fn specs() -> Vec { "Width Point", [], None, - "{id, t: 0..1 (fraction of the path length), left, right: side widths in pt, index?: width point to edit or move, adjustAdjoining?: bool (the nearest points either side change their widths in proportion, using the sampled widths for a new point)} → {index}. Without index a point already at t is replaced; a point moved onto another one's t joins it as a discontinuous point (on the side it came from), so the width steps there. Creates a uniform profile first if needed", + "{id, t: 0..1 (fraction of the path length), left, right: side widths in pt, index?: width point to edit or move, adjustAdjoining?: bool (the nearest points either side change their widths in proportion, using the sampled widths for a new point), outIndex?, outLeft, outRight: the outgoing half of the discontinuous point whose incoming half is index, single?: \"incoming\" | \"outgoing\"} → {index}. Without index a point already at t is replaced; a point moved onto another one's t joins it as a discontinuous point (on the side it came from), so the width steps there. With outIndex both halves change in one step and keep their place (t must be theirs); adjustAdjoining then changes the nearest point before from the incoming half and the nearest point after from the outgoing half. single keeps only that half's widths, leaving one continuous point. Creates a uniform profile first if needed", has_doc, width_point_set ), @@ -214,6 +214,15 @@ fn uniform() -> WidthProfile { /// Width points closer than this (in t) are at the same place: a discontinuous point. const SAME_T: f64 = 1e-6; +/// The outgoing half of the discontinuous width point whose incoming half is point `a`: point `a` +/// and the next one are the two halves when they are the only points within 1e-6 (in t) of `a`'s +/// place. None when `a` is out of range or not such an incoming half. +pub fn width_point_pair(points: &[(f64, f64, f64)], a: usize) -> Option { + let t = points.get(a)?.0; + let at: Vec = (0..points.len()).filter(|i| (points[*i].0 - t).abs() <= SAME_T).collect(); + (at == [a, a + 1]).then_some(a + 1) +} + /// The stroke of `id` that width point commands edit (a compound path's for its members). fn stroke_mut(d: &mut Document, id: NodeId) -> Result<&mut vectorcraft_doc::StrokeLayer> { let id = stroke_owner(d, id); @@ -265,9 +274,9 @@ fn place(points: &mut Vec<(f64, f64, f64)>, mut pt: (f64, f64, f64), from_below: } /// Adjust Adjoining Width Points: point `i` changes from `old` to `new` widths, and the nearest -/// points at other positions either side change in proportion (by the same amount from zero). -fn adjust_adjoining(points: &mut [(f64, f64, f64)], i: usize, old: (f64, f64, f64), new: (f64, f64, f64)) { - let t = points[i].0; +/// points farther than [`SAME_T`] from place `t` on the sides `sides` names (before, after) +/// change in proportion (by the same amount from zero). +fn adjust_adjoining(points: &mut [(f64, f64, f64)], i: usize, t: f64, old: (f64, f64, f64), new: (f64, f64, f64), sides: [bool; 2]) { let scale = |v: f64, o: f64, n: f64| { let width = if o > 1e-9 { let product = v * n; @@ -284,8 +293,8 @@ fn adjust_adjoining(points: &mut [(f64, f64, f64)], i: usize, old: (f64, f64, f6 }; width.max(0.0) }; - let before = (0..i).rev().find(|j| (points[*j].0 - t).abs() > SAME_T); - let after = (i + 1..points.len()).find(|j| (points[*j].0 - t).abs() > SAME_T); + let before = (0..i).rev().find(|j| (points[*j].0 - t).abs() > SAME_T).filter(|_| sides[0]); + let after = (i + 1..points.len()).find(|j| (points[*j].0 - t).abs() > SAME_T).filter(|_| sides[1]); for j in before.into_iter().chain(after) { let q = &mut points[j]; (q.1, q.2) = (scale(q.1, old.1, new.1), scale(q.2, old.2, new.2)); @@ -303,6 +312,46 @@ fn same_points(a: Option<&WidthProfile>, b: Option<&WidthProfile>) -> bool { } } +/// Set both halves of the discontinuous point whose incoming half is `i` and outgoing half `j` to +/// the widths of `inc` and `out` (their places are ignored: the point keeps its place). With +/// `single` (`true` for the outgoing half) only that half's widths remain, as one continuous point. +/// With `adjust`, the nearest point before changes with the incoming half and the nearest point after +/// with the outgoing half, once each. → the index of the point (its incoming half). +fn set_pair( + points: &mut Vec<(f64, f64, f64)>, + (i, inc): (usize, (f64, f64, f64)), + (j, out): (usize, (f64, f64, f64)), + adjust: bool, + single: Option, +) -> Result { + const C: &str = "stroke.widthPoint.set"; + if width_point_pair(points, i) != Some(j) { + return Err(bad(C, "`index` and `outIndex` must be the two halves of one discontinuous width point")); + } + let at = points[i].0; + let (old_in, old_out) = (points[i], points[j]); + if (old_in.0 - inc.0).abs() > SAME_T { + return Err(bad(C, "a discontinuous width point keeps its place")); + } + let (new_in, new_out) = match single { + None => ((old_in.0, inc.1, inc.2), (old_out.0, out.1, out.2)), + Some(false) => ((old_in.0, inc.1, inc.2), (old_in.0, inc.1, inc.2)), + Some(true) => ((old_in.0, out.1, out.2), (old_in.0, out.1, out.2)), + }; + // Both halves measure their neighbors from the point's place, so a point within SAME_T of the + // outgoing half but not of that place is the point after the pair. + if adjust { + adjust_adjoining(points, i, at, old_in, new_in, [true, false]); + adjust_adjoining(points, j, at, old_out, new_out, [false, true]); + } + points[i] = new_in; + points[j] = new_out; + if single.is_some() { + points.remove(j); + } + Ok(i) +} + fn width_point_set(s: &mut Session, p: &Value) -> Result { const C: &str = "stroke.widthPoint.set"; let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?; @@ -312,6 +361,25 @@ fn width_point_set(s: &mut Session, p: &Value) -> Result { return Err(bad(C, "left/right must be non-negative widths")); } let adjust = switch_or(p, "adjustAdjoining", false, C)?; + let single = match text_param(p, "single", C)? { + None => None, + Some(side @ ("incoming" | "outgoing")) => Some(side == "outgoing"), + Some(_) => return Err(bad(C, "`single` must be `incoming` or `outgoing`")), + }; + // The outgoing half of a discontinuous point: its index and side widths (points). + // `single`, `outLeft` or `outRight` without `outIndex` is refused as a missing `outIndex`. + let out_widths = ["outLeft", "outRight"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())); + let out = match p.get("outIndex") { + None | Some(Value::Null) if single.is_none() && !out_widths => None, + _ => { + let j = usize::try_from(u64_req(p, "outIndex", C)?).map_err(|_| bad(C, "no such width point"))?; + let (l, r) = (f64_req(p, "outLeft", C)?, f64_req(p, "outRight", C)?); + if !(l.is_finite() && r.is_finite()) || l < 0.0 || r < 0.0 || l.max(r) > 1.0e5 { + return Err(bad(C, "left/right must be non-negative widths")); + } + Some((j, l, r)) + } + }; // When the profile comes out as it was, within a rounding error (1e-9), the document and its undo // history stay as they are. let mut pos = 0; @@ -324,11 +392,19 @@ fn width_point_set(s: &mut Session, p: &Value) -> Result { return Err(bad(C, "width factors must be finite")); } let mut prof = st.profile.take().unwrap_or_else(uniform); - pos = match point_index(p, &prof, C)? { - Some(i) => { + pos = match (point_index(p, &prof, C)?, out) { + (None, Some(_)) => return Err(bad(C, "missing index")), + (Some(i), Some((j, l, r))) => { + let out = (t, l / half, r / half); + if !out.1.is_finite() || !out.2.is_finite() { + return Err(bad(C, "width factors must be finite")); + } + set_pair(&mut prof.points, (i, pt), (j, out), adjust, single)? + } + (Some(i), None) => { let old = prof.points[i]; if adjust { - adjust_adjoining(&mut prof.points, i, old, pt); + adjust_adjoining(&mut prof.points, i, old.0, old, pt, [true, true]); } if (old.0 - t).abs() <= SAME_T { // Widths only: it keeps its place (and its side of a discontinuous point). @@ -339,12 +415,12 @@ fn width_point_set(s: &mut Session, p: &Value) -> Result { place(&mut prof.points, pt, old.0 < t) } } - None => { + (None, None) => { let old = adjust.then(|| prof.at(t)); prof.points.retain(|q| (q.0 - t).abs() > SAME_T); let i = place(&mut prof.points, pt, true); if let Some((left, right)) = old { - adjust_adjoining(&mut prof.points, i, (t, left, right), pt); + adjust_adjoining(&mut prof.points, i, pt.0, (t, left, right), pt, [true, true]); } i } diff --git a/crates/engine/src/cmd/docinfo.rs b/crates/engine/src/cmd/docinfo.rs index c7421ac391..0456a09321 100644 --- a/crates/engine/src/cmd/docinfo.rs +++ b/crates/engine/src/cmd/docinfo.rs @@ -18,7 +18,7 @@ pub fn specs() -> Vec { "Document Info", ["Window", "Document Info"], None, - "{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document: {…, units (English), unitId: the units' Preferences › Units id (points, millimeters, feetInches, …), rasterEffectsPpi}, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts (the type in opacity masks and in the art of symbols and patterns included; with selectionOnly: the selected type's), fontDetails: [{font, match: exact|style|missingWithFallback|missing, family, style, file, embedding: allowed|editing|previewPrint|forbidden|null}] (each font of fonts, in order: how it was found, the face shown (null when none), that face's file name (null for a built-in face) and what its license allows), images, imageObjects: [{name, width, height, linked, file}] (the image objects in the order Linked Images and Embedded Images list them; file: what a linked image's row shows, null for an embedded one), swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient that color a part of it above opacity 0 (a stop at opacity 0 counts only where it mixes with a stop above opacity 0 over a stretch of some width), at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients, kinds}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else its kind's name, such as Linear gradient; kinds gives each one's kind, linear|radial|conic|diamond|freeform, when it is named by its kind, else null; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}. An image linked to a file outside the automation read roots has link null, and its Linked Images row names the file alone. brushNames, brushes, spotObjects, patternObjects and gradientObjects leave out hidden objects, objects at an opacity of 0 and the objects inside a hidden group or layer or one at an opacity of 0 (with selectionOnly too), their characters' paints and colorized images included; objects still counts them as paths, groups and the other kinds", + "{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document: {…, units (English), unitId: the units' Preferences › Units id (points, millimeters, feetInches, …), rasterEffectsPpi, transparency: {gridSize: small|medium|large, gridColors: [#rrggbb, #rrggbb], gridColorsName (a preset's name or Custom), simulatePaper, flattenerPreset} (File › Document Setup's transparency settings, which the document category lists), selectedArtboards: [{index, name, width, height, x, y}] (while the Artboard tool is the current tool, the artboards it has selected, in the document's units, x and y those of the top-left corner from the ruler origin of its active artboard, which the document category lists after the artboards; else empty)}, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts (the type in opacity masks and in the art of symbols and patterns included; with selectionOnly: the selected type's), fontDetails: [{font, match: exact|style|missingWithFallback|missing, family, style, file, embedding: allowed|editing|previewPrint|forbidden|null}] (each font of fonts, in order: how it was found, the face shown (null when none), that face's file name (null for a built-in face) and what its license allows), images, imageObjects: [{name, width, height, linked, file}] (the image objects in the order Linked Images and Embedded Images list them; file: what a linked image's row shows, null for an embedded one), swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient that color a part of it above opacity 0 (a stop at opacity 0 counts only where it mixes with a stop above opacity 0 over a stretch of some width), at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients, kinds}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else its kind's name, such as Linear gradient; kinds gives each one's kind, linear|radial|conic|diamond|freeform, when it is named by its kind, else null; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}. An image linked to a file outside the automation read roots has link null, and its Linked Images row names the file alone. brushNames, brushes, spotObjects, patternObjects and gradientObjects leave out hidden objects, objects at an opacity of 0 and the objects inside a hidden group or layer or one at an opacity of 0 (with selectionOnly too), their characters' paints and colorized images included; objects still counts them as paths, groups and the other kinds", has_doc, info ), @@ -178,14 +178,58 @@ fn repeat_entry(d: &Document, n: &Node, spec: &RepeatSpec) -> (Value, (String, S (entry, (name, format!("{}, {detail}", kind.label()))) } +/// The artboards the Artboard tool has selected while it is the current tool, in artboard order, +/// with the index of its active artboard; none with another tool or when it has none of the +/// document's artboards selected. Indices the document does not have are left out. +fn artboard_tool_selection(s: &Session) -> Option<(Vec, usize)> { + if s.tool_id() != "artboard" { + return None; + } + let n = s.active().map_or(0, |d| d.doc.artboards.len()); + let t = s.tool_options_of("artboard"); + let index = |v: &Value| v.as_u64().and_then(|i| usize::try_from(i).ok()).filter(|i| *i < n); + let mut picked: Vec = t["selected"].as_array().into_iter().flatten().filter_map(index).collect(); + picked.sort_unstable(); + picked.dedup(); + let first = *picked.first()?; + let active = index(&t["active"]).filter(|a| picked.contains(a)).unwrap_or(first); + Some((picked, active)) +} + +/// The artboards `picked` as Document Info › Document lists them while the Artboard tool is the +/// current tool: their `selectedArtboards` entries (in the document's units), and for each its +/// rows: its name, width, height and the X and Y of its top-left corner from the ruler origin of +/// artboard `active`. +fn selected_artboard_rows(d: &Document, picked: &[usize], active: usize) -> (Vec, Vec<(String, String)>) { + let (u, per) = (d.units, d.units.points()); + let origin = d.ruler_origin_for(active); + let mut entries = vec![]; + let mut rows = vec![]; + for &i in picked { + let Some(a) = d.artboards.get(i) else { continue }; + let (w, h, x, y) = (a.rect.width(), a.rect.height(), a.rect.x0 - origin.x, a.rect.y0 - origin.y); + entries.push(json!({ "index": i, "name": a.name, "width": w / per, "height": h / per, "x": x / per, "y": y / per })); + rows.extend([ + ("Artboard".to_string(), a.name.clone()), + ("Width".into(), u.format(w)), + ("Height".into(), u.format(h)), + ("X".into(), u.format(x)), + ("Y".into(), u.format(y)), + ]); + } + (entries, rows) +} + /// The Document Info categories of `d` (only `category` when given) from `info` (what -/// `document.info` reports), its fonts and their Font Details rows, its image objects, the rows of -/// the brushes its art uses, the rows of its Repeat objects and the rows of its objects filled or -/// stroked with a spot color, with a pattern and with a gradient. +/// `document.info` reports), the rows of the artboards the Artboard tool has selected, its fonts +/// and their Font Details rows, its image objects, the rows of the brushes its art uses, the rows +/// of its Repeat objects and the rows of its objects filled or stroked with a spot color, with a +/// pattern and with a gradient. #[allow(clippy::too_many_arguments)] fn sections( d: &Document, info: &Value, + selected_artboards: &[(String, String)], fonts: &BTreeSet, font_details: &[(String, String)], images: &[ImageRow], @@ -215,7 +259,19 @@ fn sections( rows.extend( d.artboards.iter().map(|a| (a.name.clone(), format!("{} × {}", u.format(a.rect.width()), u.format(a.rect.height())))), ); + rows.extend(selected_artboards.iter().cloned()); rows.push(("Raster Effects".into(), format!("{} ppi", d.raster_effects_ppi))); + let setup = &d.setup; + let colors = match setup.grid_colors_name() { + "Custom" => setup.grid_colors.map(|c| c.to_hex()).join(", "), + name => name.to_string(), + }; + rows.extend([ + ("Grid Size".to_string(), setup.grid_size.label().to_string()), + ("Grid Colors".into(), colors), + ("Simulate Colored Paper".into(), if setup.simulate_paper { "On" } else { "Off" }.into()), + ("Flattener Preset".into(), setup.flattener().to_string()), + ]); let counts = [ ("Swatches", "swatches"), ("Character Styles", "characterStyles"), @@ -556,6 +612,7 @@ fn info(s: &mut Session, p: &Value) -> Result { Some("text") => true, Some(f) => return Err(bad(C, format!("format `{f}`: text or json"))), }; + let artboard_tool = artboard_tool_selection(s); let st = s.doc()?; let d = &st.doc; let selection_only = bool_or(p, "selectionOnly", false); @@ -787,7 +844,22 @@ fn info(s: &mut Session, p: &Value) -> Result { }); // The document's name: its file's, else its title. out["document"]["name"] = json!(st.title()); - let sections = sections(d, &out, &fonts, &font_rows, &image_rows, &brush_rows, &repeat_rows, &spot_rows, &pattern_rows, &gradient_rows, category); + let (selected_entries, selected_rows) = artboard_tool.map(|(picked, active)| selected_artboard_rows(d, &picked, active)).unwrap_or_default(); + out["document"]["selectedArtboards"] = json!(selected_entries); + let sections = sections( + d, + &out, + &selected_rows, + &fonts, + &font_rows, + &image_rows, + &brush_rows, + &repeat_rows, + &spot_rows, + &pattern_rows, + &gradient_rows, + category, + ); if text { return Ok(json!({ "text": report_text(&st.title(), selection_only, §ions) })); } @@ -804,6 +876,13 @@ fn document_summary(d: &Document) -> Value { "unitId": d.units.key(), "artboards": d.artboards.iter().map(|a| json!({ "name": a.name, "width": a.rect.width() / u, "height": a.rect.height() / u })).collect::>(), "rasterEffectsPpi": d.raster_effects_ppi, + "transparency": { + "gridSize": d.setup.grid_size.id(), + "gridColors": d.setup.grid_colors.map(|c| c.to_hex()), + "gridColorsName": d.setup.grid_colors_name(), + "simulatePaper": d.setup.simulate_paper, + "flattenerPreset": d.setup.flattener(), + }, }) } @@ -875,6 +954,101 @@ mod tests { assert!(i["objects"]["textObjects"].is_null() && i["objects"]["paths"] == 1); } + /// The Document category's rows from `info`, as (label, value) pairs. + fn document_rows(i: &Value) -> Vec<(String, String)> { + let doc = i["sections"].as_array().unwrap().iter().find(|s| s["id"] == "document").unwrap(); + doc["rows"].as_array().unwrap().iter().map(|r| (r[0].as_str().unwrap().to_string(), r[1].as_str().unwrap().to_string())).collect() + } + + /// Document lists File › Document Setup's transparency settings: the grid's size and colors + /// (a preset's name, else both colors), Simulate Colored Paper and the flattener preset. + #[test] + fn info_lists_the_transparency_settings() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + let i = s.execute("document.info", &json!({})).unwrap(); + let t = &i["document"]["transparency"]; + assert_eq!( + (t["gridSize"].clone(), t["gridColorsName"].clone(), t["simulatePaper"].clone(), t["flattenerPreset"].clone()), + (json!("medium"), json!("Light"), json!(false), json!("Medium Resolution")) + ); + let rows = document_rows(&i); + let at = rows.iter().position(|(l, _)| l == "Raster Effects").unwrap(); + let expected = + [("Grid Size", "Medium"), ("Grid Colors", "Light"), ("Simulate Colored Paper", "Off"), ("Flattener Preset", "Medium Resolution")]; + assert_eq!(rows[at + 1..at + 5], expected.map(|(l, v)| (l.to_string(), v.to_string())), "{rows:?}"); + s.execute( + "document.setup", + &json!({"gridSize": "large", "gridColors": ["#ff0000", "#00ff00"], "simulatePaper": true, "flattenerPreset": "High Resolution"}), + ) + .unwrap(); + let i = s.execute("document.info", &json!({})).unwrap(); + assert_eq!(i["document"]["transparency"]["gridColors"], json!(["#ff0000", "#00ff00"])); + assert_eq!(i["document"]["transparency"]["gridColorsName"], "Custom"); + let rows = document_rows(&i); + let expected = + [("Grid Size", "Large"), ("Grid Colors", "#ff0000, #00ff00"), ("Simulate Colored Paper", "On"), ("Flattener Preset", "High Resolution")]; + assert_eq!(rows[at + 1..at + 5], expected.map(|(l, v)| (l.to_string(), v.to_string())), "{rows:?}"); + let report = s.execute("document.info", &json!({"category": "document", "format": "text"})).unwrap()["text"].as_str().unwrap().to_string(); + assert!(report.contains("Grid Colors: #ff0000, #00ff00\nSimulate Colored Paper: On\nFlattener Preset: High Resolution\n"), "{report}"); + } + + /// While the Artboard tool is the current tool, Document lists each artboard it has selected + /// after the artboards: its name, width, height and the X and Y of its top-left corner from the + /// ruler origin of the tool's active artboard. With another tool it lists none. + #[test] + fn info_lists_the_artboards_the_artboard_tool_selected() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("artboard.new", &json!({"x": 150, "y": 40, "width": 60, "height": 80})).unwrap(); + s.execute("artboard.new", &json!({"x": 400, "y": 10, "width": 100, "height": 50})).unwrap(); + s.execute("artboard.setProps", &json!({"index": 2, "name": "Back"})).unwrap(); + let before = s.execute("document.info", &json!({})).unwrap(); + assert_eq!(before["document"]["selectedArtboards"], json!([])); + s.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap(); + s.set_tool_option("selected", &json!([2, 1, 7])); + let i = s.execute("document.info", &json!({})).unwrap(); + // Artboard 2 is active: positions are measured from its top-left corner. + assert_eq!( + i["document"]["selectedArtboards"], + json!([ + {"index": 1, "name": "Artboard 2", "width": 60.0, "height": 80.0, "x": -250.0, "y": 30.0}, + {"index": 2, "name": "Back", "width": 100.0, "height": 50.0, "x": 0.0, "y": 0.0}, + ]) + ); + let rows = document_rows(&i); + let at = rows.iter().position(|(l, _)| l == "Artboards").unwrap() + 4; + let expected = [ + ("Artboard", "Artboard 2"), + ("Width", "60 pt"), + ("Height", "80 pt"), + ("X", "-250 pt"), + ("Y", "30 pt"), + ("Artboard", "Back"), + ("Width", "100 pt"), + ("Height", "50 pt"), + ("X", "0 pt"), + ("Y", "0 pt"), + ("Raster Effects", "72 ppi"), + ]; + assert_eq!(rows[at..at + 11], expected.map(|(l, v)| (l.to_string(), v.to_string())), "{rows:?}"); + // The rows follow the document's units and its ruler origin. + s.execute("document.setup", &json!({"units": "Millimeters"})).unwrap(); + s.execute("document.setRulerOrigin", &json!({"x": 390, "y": 0, "artboard": 2})).unwrap(); + s.set_tool_option("selected", &json!([2])); + let i = s.execute("document.info", &json!({"category": "document"})).unwrap(); + let entry = &i["document"]["selectedArtboards"]; + assert_eq!((entry.as_array().unwrap().len(), entry[0]["index"].clone()), (1, json!(2))); + assert!((entry[0]["x"].as_f64().unwrap() - 10.0 * 25.4 / 72.0).abs() < 1e-9, "{entry}"); + let rows = document_rows(&i); + assert!(rows.contains(&("X".into(), "3.5278 mm".into())) && rows.contains(&("Y".into(), "3.5278 mm".into())), "{rows:?}"); + // Another tool: no artboard rows. + s.select_tool("selection", crate::tooling::ViewInfo::default()).unwrap(); + let i = s.execute("document.info", &json!({})).unwrap(); + assert_eq!(i["document"]["selectedArtboards"], json!([])); + assert!(!document_rows(&i).iter().any(|(l, _)| l == "X"), "{:?}", document_rows(&i)); + } + /// Document Info's fonts include the type in an opacity mask, in a symbol's art and in a /// pattern swatch that nothing paints with; with `selectionOnly`, only the selected type's. #[test] diff --git a/crates/engine/src/cmd/docmenu.rs b/crates/engine/src/cmd/docmenu.rs index 709b4cda65..717c9cdc14 100644 --- a/crates/engine/src/cmd/docmenu.rs +++ b/crates/engine/src/cmd/docmenu.rs @@ -238,7 +238,7 @@ pub fn specs() -> Vec { "Move Guide", [], None, - "{index, pos: pt} | {dx?, dy?: pt, copy?: bool} put ruler guide `index` at `pos`, or move the selected guides (vertical ones by dx, horizontal ones by dy); copy leaves them and selects the moved copies", + "{index, pos: pt} | {dx?, dy?: pt, copy?: bool, interpolate?: bool (with art selected too: as object.move's)} put ruler guide `index` at `pos`, or move the selected guides (vertical ones by dx, horizontal ones by dy); copy leaves them and selects the moved copies", guides_unlocked, guide_move ), @@ -990,6 +990,7 @@ pub(crate) fn guide_move(s: &mut Session, p: &Value) -> Result { let dx = number_or(p, "dx", 0.0, "guide.move")?; let dy = number_or(p, "dy", 0.0, "guide.move")?; let copy = switch_or(p, "copy", false, "guide.move")?; + switch_or(p, "interpolate", false, "guide.move")?; if !s.doc()?.selection.is_empty() { let ids = super::edit::selected_roots(s)?; return super::object::apply_transform( diff --git a/crates/engine/src/cmd/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs index c852d3b205..4e753ce00c 100644 --- a/crates/engine/src/cmd/draw2/commands.rs +++ b/crates/engine/src/cmd/draw2/commands.rs @@ -11,7 +11,7 @@ pub fn specs() -> Vec { "Pencil", [], None, - "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise, 0..360: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks. A pressure, tilt or rotation outside its range, or a point array of more than six numbers, is an error), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\" (default) | \"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end?: \"end\" (default) | \"start\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it. Any other style, extend end or connect end is an error, and nothing changes", + "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise, 0..360: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks. A pressure, tilt or rotation outside its range, or a point array of more than six numbers, is an error), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\" (default) | \"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end?: \"end\" (default) | \"start\"}, connect?: {id, end: \"start\"|\"end\"} (only with extend), redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it. Any other style, extend end or connect end, connect without extend, and a connect that names no other path with an open end are errors, a stroke of one point included, and nothing changes", has_doc, freehand ), @@ -101,7 +101,7 @@ pub fn specs() -> Vec { "Path Eraser", [], None, - "{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change what is erased), width?: pt (8)} erase the parts of selected paths under the drag → {ids}", + "{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change what is erased), width?: pt (8; from 0.001 to 1000)} erase the parts of selected paths under the drag → {ids}. A width outside 0.001 to 1000 is refused with an error, and nothing changes", has_selection, erase_segments ), diff --git a/crates/engine/src/cmd/draw2/cut.rs b/crates/engine/src/cmd/draw2/cut.rs index cbf0b8e333..d97c18305c 100644 --- a/crates/engine/src/cmd/draw2/cut.rs +++ b/crates/engine/src/cmd/draw2/cut.rs @@ -580,13 +580,13 @@ fn apply_plan(s: &mut Session, label: &str, plan: Vec<(NodeId, Vec)>) Ok(ids_json(&ids)) } +/// The Path Eraser's band width, in points (VectorCraft's own range). +const PATH_ERASER_WIDTHS: (f64, f64) = (0.001, 1000.0); + pub(super) fn erase_segments(s: &mut Session, p: &Value) -> Result { const C: &str = "path.eraseSegments"; let pts = points_param(p, "points", C)?; - let w = number_or(p, "width", 8.0, C)?; - if !(w.is_finite() && w > 0.0) { - return Err(bad(C, "width must be positive")); - } + let w = ranged(p, "width", 8.0, PATH_ERASER_WIDTHS, C)?; let st = s.doc()?; let mut plan = vec![]; for id in target_paths(&st.doc, &st.selection, poly_bounds(&pts, w)) { diff --git a/crates/engine/src/cmd/draw2/freehand.rs b/crates/engine/src/cmd/draw2/freehand.rs index 241d252816..607abf8f03 100644 --- a/crates/engine/src/cmd/draw2/freehand.rs +++ b/crates/engine/src/cmd/draw2/freehand.rs @@ -174,9 +174,13 @@ fn no_stroke(name: &str) -> EngineError { bad("brush.freehand", format!("cannot apply brush `{name}`: path has no stroke")) } -/// Sets brush `name` on the stroke of object `id` of `d`. +/// Sets brush `name` on the stroke of object `id` of `d`. The stroke's own settings for another +/// brush (Options of Selected Object) are cleared. fn set_brush(d: &mut Document, id: NodeId, name: &str) { if let Some(st) = d.node_mut(id).and_then(|n| n.appearance.stroke_mut()) { + if st.brush.as_deref() != Some(name) { + st.brush_options.clear(); + } st.brush = Some(name.to_string()); } } @@ -209,7 +213,11 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s let label = if brush || brush_name.is_some() { "Paintbrush" } else { "Pencil" }; let keep_selected = switch_or(p, "keepSelected", true, C)?; let filled = switch_or(p, "fill", false, C)?; - if let Some(ext) = p.get("extend").filter(|v| !v.is_null()) { + let extend = p.get("extend").filter(|v| !v.is_null()); + if extend.is_none() && p.get("connect").is_some_and(|v| !v.is_null()) { + return Err(bad(C, "connect needs extend")); + } + if let Some(ext) = extend { let id = object_param(ext, "id", C)?.ok_or_else(|| bad(C, "extend needs id"))?; let at_start = match ext.get("end").filter(|v| !v.is_null()).map(Value::as_str) { None | Some(Some("end")) => false, @@ -234,26 +242,9 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s }; let Some(p0) = pts.first_mut() else { return Err(bad(C, "needs points")) }; *p0 = end; - if pts.len() < 2 { - // No stroke to add: the brush alone changes, when it is not the path's already, and the - // path is selected or deselected as a longer continuation leaves it. - if let Some(name) = brush_name - && s.doc()?.doc.node(target).and_then(|n| n.appearance.stroke()).is_some_and(|st| st.brush.as_deref() != Some(name)) - { - s.edit("Paintbrush", |d, sel| { - set_brush(d, target, name); - if keep_selected { - sel.set([id]); - } else { - sel.remove(id); - } - Ok(()) - })?; - } - return Ok(json!({ "id": id.0 })); - } // A stroke that ends on an open end of another path connects the two: (that path, its last // open subpath, that subpath starting at the end the stroke ends on, it ends at its end). + // It is checked before a stroke of one point returns, so a bad `connect` is refused there too. let connect = match p.get("connect").filter(|v| !v.is_null()) { Some(cn) => { let other = object_param(cn, "id", C)?.ok_or_else(|| bad(C, "connect needs id"))?; @@ -276,6 +267,24 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s } None => None, }; + if pts.len() < 2 { + // No stroke to add: the brush alone changes, when it is not the path's already, and the + // path is selected or deselected as a longer continuation leaves it. + if let Some(name) = brush_name + && s.doc()?.doc.node(target).and_then(|n| n.appearance.stroke()).is_some_and(|st| st.brush.as_deref() != Some(name)) + { + s.edit("Paintbrush", |d, sel| { + set_brush(d, target, name); + if keep_selected { + sel.set([id]); + } else { + sel.remove(id); + } + Ok(()) + })?; + } + return Ok(json!({ "id": id.0 })); + } // `closed`, when given, says whether the stroke closes the path: the Pencil and the // Paintbrush send it, by their Close Paths When Ends Are Within and Alt at the release. // Left out, an extending stroke that ends within four Fidelities of the path's other end diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index fbf5deb568..3b47fedb41 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -6,6 +6,7 @@ use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_doc::{Document, Node, NodeId, NodeKind, RulerMode, Unit}; use vectorcraft_geom::{Affine, Point, Vec2}; +use vectorcraft_tools::distort::perspective::{PerspectiveGrid, Plane}; use super::clipboard::SwatchChoices; use super::{ @@ -713,6 +714,85 @@ pub(crate) fn settle_interaction(s: &mut Session) -> Result<()> { Ok(()) } +/// The document state that commands also change without an undo step: the perspective grid's view +/// options (whether it shows, Lock Grid, Lock Station Point, Snap to Grid and Show Rulers), its +/// active plane, the grid preferences, the export settings, and the current brush and symbol. Each +/// undo and redo step keeps it as the document on its other side had it +/// ([`crate::HistoryEntry::unrecorded`]). +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct Unrecorded { + grid: vectorcraft_doc::GridPrefs, + export_settings: serde_json::Map, + brush: Option, + symbol: Option, + options: [bool; 5], + plane: Plane, +} + +impl Unrecorded { + pub(crate) fn of(d: &Document) -> Self { + let g = PerspectiveGrid::current(d); + Unrecorded { + grid: d.grid.clone(), + export_settings: d.export_settings.clone(), + brush: d.unknown.get(vectorcraft_brush::CURRENT_KEY).cloned(), + symbol: d.unknown.get(super::brushsym::CURRENT_SYMBOL).cloned(), + options: [g.visible, g.locked, g.lock_station, g.snap, g.rulers], + plane: g.plane, + } + } +} + +/// Undo and redo bring back `d`; `step` is that state as the document on the step's other side had +/// it. A part the step did not change (`d` has it as `step` does) stays as it is in `now`, the +/// document before the undo or redo, since it changed after the step without an undo step. A part +/// the step changed comes back with `d`. A current brush or symbol that `d` does not hold also +/// comes back with `d`. The point Automatic Plane Positioning holds comes back with `d`, and is let go when the +/// active plane kept is not the one it holds. +fn keep_unrecorded(now: &Document, step: &Unrecorded, d: &mut Arc) { + fn pick(back: &T, step: &T, now: &T) -> T { + if back == step { now.clone() } else { back.clone() } + } + let back = Unrecorded::of(d); + let cur = Unrecorded::of(now); + let mut want = Unrecorded { + grid: pick(&back.grid, &step.grid, &cur.grid), + export_settings: pick(&back.export_settings, &step.export_settings, &cur.export_settings), + brush: pick(&back.brush, &step.brush, &cur.brush), + symbol: pick(&back.symbol, &step.symbol, &cur.symbol), + options: std::array::from_fn(|i| pick(&back.options[i], &step.options[i], &cur.options[i])), + plane: pick(&back.plane, &step.plane, &cur.plane), + }; + if want.brush != back.brush && want.brush.as_ref().and_then(Value::as_str).is_some_and(|n| vectorcraft_brush::find(d, n).is_none()) { + want.brush = back.brush.clone(); + } + if want.symbol != back.symbol && want.symbol.as_ref().and_then(Value::as_str).is_some_and(|n| !d.symbols.iter().any(|s| s.name == n)) { + want.symbol = back.symbol.clone(); + } + if want == back { + return; + } + let m = Arc::make_mut(d); + for (key, v) in [(vectorcraft_brush::CURRENT_KEY, &want.brush), (super::brushsym::CURRENT_SYMBOL, &want.symbol)] { + match v { + Some(v) => m.unknown.insert(key.into(), v.clone()), + None => m.unknown.remove(key), + }; + } + if (want.options, want.plane) != (back.options, back.plane) { + let mut g = PerspectiveGrid::current(m); + [g.visible, g.locked, g.lock_station, g.snap, g.rulers] = want.options; + if g.plane != want.plane { + g.plane = want.plane; + g.inferred = None; + } + g.keep_positioning_valid(); + super::distortcmds::store_grid(m, &g); + } + m.grid = want.grid; + m.export_settings = want.export_settings; +} + fn undo(s: &mut Session, _: &Value) -> Result { settle_interaction(s)?; let menu = s.menu.clone(); @@ -723,6 +803,7 @@ fn undo(s: &mut Session, _: &Value) -> Result { let editing = st.doc.mask_edit.map(|m| m.layer); let editing_symbol = st.doc.symbol_edit.clone(); let doc = std::mem::replace(&mut st.doc, e.doc); + keep_unrecorded(&doc, &e.unrecorded, &mut st.doc); let selection = std::mem::replace(&mut st.selection, Arc::unwrap_or_clone(e.selection)); let selection = shared_selection(selection, st.history.redo.last()); let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs); @@ -758,6 +839,7 @@ fn redo(s: &mut Session, _: &Value) -> Result { let editing = st.doc.mask_edit.map(|m| m.layer); let editing_symbol = st.doc.symbol_edit.clone(); let doc = std::mem::replace(&mut st.doc, e.doc); + keep_unrecorded(&doc, &e.unrecorded, &mut st.doc); let selection = std::mem::replace(&mut st.selection, Arc::unwrap_or_clone(e.selection)); let selection = shared_selection(selection, st.history.undo.last()); let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs); @@ -1076,8 +1158,10 @@ fn cut(s: &mut Session, p: &Value) -> Result { /// Select every surviving piece while retaining intentional compound-path structure. /// `roots` contains the copied targets: whole-object roots are removed in full, while partial paths /// lose only the copied geometry. An exhausted partial path is removed, along with its compound -/// parent if now empty; layers remain. Returns JSON `null` on success, replacing direct-selection -/// references with surviving object IDs. +/// parent if now empty; a compound left with one member stays a compound path, as after Clear; +/// layers remain. Removed and replaced roots go through one [`super::pathops::Beside`], which +/// rebuilds each parent's children once when the roots are separate. Returns JSON `null` on +/// success, replacing direct-selection references with surviving object IDs. fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result { let st = s.doc()?; let sel = st.selection.clone(); @@ -1085,13 +1169,18 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result { // The selected ruler guides were copied too (#3226): they go in the same undo step. let gone = selection.guides.clone(); d.retain_guides(selection, |g| !g.id.is_some_and(|id| gone.contains(&id))); + // The compound paths that hold a root; one left with no members goes too. + let compounds: BTreeSet = roots + .iter() + .filter_map(|id| d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })))) + .collect(); let mut survivors = vec![]; let mut pieces = super::pathops::Beside::replacing(d, roots); for id in roots { let Some(node) = d.node(*id) else { continue }; let has_direct = sel.anchors.contains_key(id) || sel.segments.contains_key(id); if !has_direct || node.path_data().is_none() { - remove_leaving_no_empty_compound(d, *id)?; + pieces.put(d, *id, vec![])?; continue; } let original = super::path::deletion_source(d, *id)?; @@ -1114,12 +1203,14 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result { } subpaths.retain(|sp| sp.anchors.len() >= 2); if subpaths.is_empty() { - remove_leaving_no_empty_compound(d, *id)?; + pieces.put(d, *id, vec![])?; } else { survivors.extend(super::path::replace_deleted_pieces(d, &mut pieces, original, subpaths)?); } } pieces.finish(d)?; + let emptied: Vec = compounds.into_iter().filter(|p| d.node(*p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty()))).collect(); + super::pathops::remove_each(d, &emptied)?; selection.set(survivors); selection.anchors.clear(); selection.segments.clear(); @@ -1128,19 +1219,6 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result { ok() } -/// Remove object `id`, and the compound path that held it when it was the compound's last member. -/// A compound left with one member stays a compound path, as after Clear. -fn remove_leaving_no_empty_compound(d: &mut Document, id: NodeId) -> Result<()> { - let parent = d.parent_of(id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. }))); - d.remove(id)?; - if let Some(p) = parent - && d.node(p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())) - { - d.remove(p)?; - } - Ok(()) -} - fn clear(s: &mut Session, p: &Value) -> Result { let guides = switch_or(p, "guides", false, "edit.clear")?; let explicit = if p.get("ids").is_some() { Some(checked_ids_param(s, p, "ids", "edit.clear")?) } else { None }; @@ -1751,3 +1829,6 @@ pub(crate) fn copy_above(d: &mut Document, roots: &[NodeId], mut change: impl Fn pub(crate) fn arc_nodes(v: Vec) -> Vec> { v.into_iter().map(Arc::new).collect() } + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/edit/tests.rs b/crates/engine/src/cmd/edit/tests.rs new file mode 100644 index 0000000000..8146bec6c2 --- /dev/null +++ b/crates/engine/src/cmd/edit/tests.rs @@ -0,0 +1,343 @@ +//! Cut with direct-selected anchors removes the objects selected whole and the paths it empties +//! through one [`Beside`](super::super::pathops::Beside), and leaves the document, the selection, +//! the clipboard and the undo history exactly as removing each of them on its own does. + +use std::collections::BTreeSet; +use std::time::{Duration, Instant}; + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, NodeId, NodeKind, tree_walks}; + +use super::*; +use crate::tests_large_edits::{session, square}; + +/// Cut's removal with every root selected whole or emptied taken out by its own +/// [`Document::remove`], and its compound path removed right after when that left it empty. The +/// tests compare [`cut_direct_selection`] with it. +fn cut_one_at_a_time(s: &mut Session, roots: &[NodeId]) -> Result { + let st = s.doc()?; + let sel = st.selection.clone(); + s.edit("Cut", |d, selection| { + let gone = selection.guides.clone(); + d.retain_guides(selection, |g| !g.id.is_some_and(|id| gone.contains(&id))); + let mut survivors = vec![]; + let mut pieces = super::super::pathops::Beside::replacing(d, roots); + for id in roots { + let Some(node) = d.node(*id) else { continue }; + let has_direct = sel.anchors.contains_key(id) || sel.segments.contains_key(id); + if !has_direct || node.path_data().is_none() { + remove_one(d, *id)?; + continue; + } + let original = super::super::path::deletion_source(d, *id)?; + let seg_refs = sel.segments.get(id); + let anchor_refs = sel.anchors.get(id); + let mut subpaths = Vec::new(); + let owned = std::mem::take(&mut super::super::path::path_mut(d, *id)?.subpaths); + for (si, sp) in owned.into_iter().enumerate() { + let cuts = super::super::clipboard::subpath_selected_segments(&sp, si, seg_refs, anchor_refs); + if cuts.is_empty() { + subpaths.push(sp); + } else if seg_refs.is_some_and(|segments| !segments.is_empty()) { + subpaths.extend(super::super::path::without_segments(sp, &cuts)); + } else { + let gone: BTreeSet = anchor_refs.into_iter().flat_map(|refs| super::super::path::subpath_refs(refs, si)).collect(); + subpaths.extend(super::super::path::without_anchors(sp, &gone)); + } + } + subpaths.retain(|sp| sp.anchors.len() >= 2); + if subpaths.is_empty() { + remove_one(d, *id)?; + } else { + survivors.extend(super::super::path::replace_deleted_pieces(d, &mut pieces, original, subpaths)?); + } + } + pieces.finish(d)?; + selection.set(survivors); + selection.anchors.clear(); + selection.segments.clear(); + Ok(()) + })?; + ok() +} + +/// Removes object `id`, and the compound path that held it when it was the compound's last member. +fn remove_one(d: &mut Document, id: NodeId) -> Result<()> { + let parent = d.parent_of(id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. }))); + d.remove(id)?; + if let Some(p) = parent + && d.node(p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())) + { + d.remove(p)?; + } + Ok(()) +} + +/// Cut as `edit.cut` runs it for a direct selection, with [`cut_one_at_a_time`] in place of +/// [`cut_direct_selection`]. +fn reference_cut(s: &mut Session) { + let (direct, roots) = copy_cut_targets(s).unwrap(); + assert!(direct, "the selection is a direct selection"); + copy(s, &json!({})).unwrap(); + cut_one_at_a_time(s, &roots).unwrap(); +} + +fn run(s: &mut Session, cmd: &str, p: Value) -> Value { + s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}")) +} + +/// Selects `whole` as objects, then anchors `anchors` of each path in `partial`. +fn select_direct(s: &mut Session, whole: &[NodeId], partial: &[(NodeId, Value)]) { + run(s, "select.set", json!({"ids": whole.iter().map(|id| id.0).collect::>()})); + for (id, anchors) in partial { + run(s, "select.anchors", json!({"id": id.0, "anchors": anchors, "mode": "add"})); + } +} + +/// The ids of every node of the document, depth first, with the depth of each. +fn tree(d: &Document) -> Vec<(usize, NodeId)> { + fn walk(n: &vectorcraft_doc::Node, depth: usize, out: &mut Vec<(usize, NodeId)>) { + out.push((depth, n.id)); + for c in n.children().into_iter().flatten() { + walk(c, depth + 1, out); + } + } + let mut out = vec![]; + for l in &d.layers { + walk(l, 0, &mut out); + } + out +} + +/// Whether `a` and `b` hold the same document, selection, clipboard and number of undo and redo +/// steps. +fn assert_same(a: &Session, b: &Session, when: &str) { + let (x, y) = (a.doc().unwrap(), b.doc().unwrap()); + assert_eq!(tree(&x.doc), tree(&y.doc), "{when}: the tree"); + assert!(*x.doc == *y.doc, "{when}: the document"); + assert_eq!(x.selection, y.selection, "{when}: the selection"); + // Each session's document has its own uid; the clipboard names the one it came from. + assert_eq!(a.clipboard.source_doc.is_some(), b.clipboard.source_doc.is_some(), "{when}: the clipboard's source"); + let unsourced = |c: &Clipboard| Clipboard { source_doc: None, ..c.clone() }; + assert!(unsourced(&a.clipboard) == unsourced(&b.clipboard), "{when}: the clipboard"); + assert_eq!(x.history.undo.len(), y.history.undo.len(), "{when}: the undo steps"); + assert_eq!(x.history.redo.len(), y.history.redo.len(), "{when}: the redo steps"); +} + +/// Runs `edit.cut` on one session that `make` builds and [`reference_cut`] on another, and checks +/// that both hold the same after the Cut, after Undo and after Redo. Returns the first session after +/// the Cut. +fn same_as_one_at_a_time(make: impl Fn() -> Session) -> Session { + let (mut a, mut b) = (make(), make()); + let before = a.doc().unwrap().doc.clone(); + assert_same(&a, &b, "before"); + run(&mut a, "edit.cut", json!({})); + reference_cut(&mut b); + assert_same(&a, &b, "Cut"); + let after = a.doc().unwrap().doc.clone(); + run(&mut a, "edit.undo", json!({})); + run(&mut b, "edit.undo", json!({})); + assert_same(&a, &b, "Undo"); + assert!(*a.doc().unwrap().doc == *before, "Undo gives back the document"); + run(&mut a, "edit.redo", json!({})); + run(&mut b, "edit.redo", json!({})); + assert_same(&a, &b, "Redo"); + assert!(*a.doc().unwrap().doc == *after, "Redo gives back the Cut"); + run(&mut a, "edit.undo", json!({})); + run(&mut a, "edit.redo", json!({})); + a +} + +/// A new document; [`rect`] adds squares to it. +fn new_doc() -> Session { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 800, "height": 600})); + s +} + +/// Adds a 10 pt square to the current layer, 20 pt right of the last one. +fn rect(s: &mut Session) -> NodeId { + let x = 20.0 * s.doc().unwrap().doc.node_count() as f64; + NodeId(run(s, "shape.rectangle", json!({"x": x, "y": 10, "width": 10, "height": 10}))["id"].as_u64().unwrap()) +} + +/// Makes a compound path of `ids` and returns it with its members in order. +fn compound(s: &mut Session, ids: &[NodeId]) -> (NodeId, Vec) { + run(s, "select.set", json!({"ids": ids.iter().map(|id| id.0).collect::>()})); + let c = NodeId(run(s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap()); + let members = s.doc().unwrap().doc.node(c).unwrap().children().unwrap().iter().map(|m| m.id).collect(); + (c, members) +} + +/// Anchors 0 to 2 of a square: Cut leaves it no segment, so it is removed. +fn three_anchors() -> Value { + json!([[0, 0], [0, 1], [0, 2]]) +} + +/// Anchors 0 and 1 of a square: Cut keeps its other three sides. +fn two_anchors() -> Value { + json!([[0, 0], [0, 1]]) +} + +/// The compound path whose members are cut one whole and one emptied goes with them; the other +/// compound path keeps its one member left, as a compound path. +#[test] +fn cut_removes_a_compound_whose_members_all_go_and_keeps_one_with_one_member_left() { + let make = || { + let mut s = new_doc(); + let first = [(); 2].map(|()| rect(&mut s)); + let (gone, gone_members) = compound(&mut s, &first); + let second = [(); 3].map(|()| rect(&mut s)); + let (kept, kept_members) = compound(&mut s, &second); + let other = rect(&mut s); + select_direct( + &mut s, + &[gone_members[0], kept_members[0]], + &[(gone_members[1], three_anchors()), (kept_members[1], three_anchors()), (other, two_anchors())], + ); + (s, gone, kept, kept_members[2], other) + }; + let s = same_as_one_at_a_time(|| make().0); + let (_, gone, kept, left, other) = make(); + let d = &s.doc().unwrap().doc; + assert!(d.node(gone).is_none(), "the compound path whose members all went is removed"); + let kept = d.node(kept).expect("the compound path with a member left stays"); + assert!(matches!(kept.kind, NodeKind::Compound { .. })); + assert_eq!(kept.children().unwrap().iter().map(|m| m.id).collect::>(), [left]); + assert_eq!(s.doc().unwrap().selection.objects, [other], "the cut square's other sides stay selected"); +} + +/// Objects inside two groups and on the layer, removed whole, emptied or cut apart between kept +/// siblings, keep the order and ids that removing them one at a time leaves. +#[test] +fn cut_inside_groups_keeps_the_order_and_ids_of_removing_one_at_a_time() { + let make = || { + let mut s = new_doc(); + let a = [(); 4].map(|()| rect(&mut s)); + run(&mut s, "select.set", json!({"ids": a.iter().map(|id| id.0).collect::>()})); + run(&mut s, "object.group", json!({})); + let b = [(); 4].map(|()| rect(&mut s)); + run(&mut s, "select.set", json!({"ids": b.iter().map(|id| id.0).collect::>()})); + run(&mut s, "object.group", json!({})); + let c = [(); 4].map(|()| rect(&mut s)); + select_direct( + &mut s, + &[a[0], a[2], b[3], c[1]], + &[(a[1], two_anchors()), (b[0], three_anchors()), (b[2], two_anchors()), (c[3], three_anchors())], + ); + s + }; + let s = same_as_one_at_a_time(make); + assert_eq!(s.doc().unwrap().selection.objects.len(), 2, "the two squares cut apart stay selected"); +} + +/// Selected ruler guides go with the objects, in the Cut's undo step. +#[test] +fn cut_removes_the_selected_guides_with_the_objects() { + let make = || { + let mut s = new_doc(); + let [a, b, c] = [(); 3].map(|()| rect(&mut s)); + run(&mut s, "guide.add", json!({"vertical": true, "pos": 30})); + run(&mut s, "guide.add", json!({"vertical": false, "pos": 40})); + select_direct(&mut s, &[a, c], &[(b, two_anchors())]); + run(&mut s, "guide.select", json!({"indexes": [1], "toggle": true})); + s + }; + let s = same_as_one_at_a_time(make); + assert_eq!(s.doc().unwrap().doc.ruler_guides().len(), 1, "the selected guide is removed"); + assert_eq!(s.clipboard.guides.len(), 1, "the selected guide is on the clipboard"); +} + +/// Roots that are not separate (one inside another) are removed one at a time, as before. +#[test] +fn cut_of_roots_inside_another_root_matches_removing_one_at_a_time() { + let make = || { + let mut s = new_doc(); + let a = [(); 3].map(|()| rect(&mut s)); + run(&mut s, "select.set", json!({"ids": a.iter().map(|id| id.0).collect::>()})); + let group = NodeId(run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap()); + let b = rect(&mut s); + select_direct(&mut s, &[group, b], &[(a[1], two_anchors())]); + (s, vec![a[1], group, b]) + }; + let (mut x, roots) = make(); + let (mut y, _) = make(); + copy(&mut x, &json!({})).unwrap(); + copy(&mut y, &json!({})).unwrap(); + cut_direct_selection(&mut x, &roots).unwrap(); + cut_one_at_a_time(&mut y, &roots).unwrap(); + assert_same(&x, &y, "Cut"); +} + +/// One layer of 10,000 squares with every fifth of the first 10,000 selected whole (2,000) and +/// anchors 0 and 1 of the square after them picked. +fn many() -> Session { + let mut s = session(10_001, square); + let ids = crate::tests_large_edits::layer(&s, 0); + let whole: Vec = ids.iter().take(10_000).step_by(5).copied().collect(); + select_direct(&mut s, &whole, &[(ids[10_000], two_anchors())]); + s +} + +/// The tree walks [`tree_walks`] counts while `f` runs on `s`. +fn walks(s: &mut Session, f: impl FnOnce(&mut Session)) -> u64 { + let before = tree_walks(); + f(s); + tree_walks() - before +} + +/// Cut of 2,000 objects selected whole among 10,000, with a direct selection, walks the document's +/// tree a few times, where removing them one at a time walks it several times for each object. +#[test] +fn direct_selection_cut_of_2000_of_10000_objects_takes_few_tree_walks() { + let s = same_as_one_at_a_time(many); + assert_eq!(crate::tests_large_edits::layer(&s, 0).len(), 8_001); + let (mut a, mut b) = (many(), many()); + let batched = walks(&mut a, |s| { + run(s, "edit.cut", json!({})); + }); + let one_at_a_time = walks(&mut b, reference_cut); + println!("tree walks: Cut {batched}, one at a time {one_at_a_time}"); + assert!(batched <= 64, "Cut walked the document's tree {batched} times"); + assert!(one_at_a_time >= 4 * batched.max(1), "one at a time walked it {one_at_a_time} times, Cut {batched}"); +} + +/// This thread's CPU time, where the system reports it (`/proc/thread-self/schedstat` on Linux). +fn cpu_time() -> Option { + let stat = std::fs::read_to_string("/proc/thread-self/schedstat").ok()?; + stat.split_whitespace().next()?.parse().ok().map(Duration::from_nanos) +} + +/// The middle of `v`. +fn median(mut v: Vec) -> Duration { + v.sort_unstable(); + v[v.len() / 2] +} + +/// Times Cut of [`many`] and [`reference_cut`] seven times each, in turn, and prints every run's +/// CPU and wall-clock time with the medians. Run it with +/// `cargo test --release -p vectorcraft-engine --lib -- --ignored --nocapture direct_selection_cut_timing`. +#[test] +#[ignore = "timing; prints the numbers"] +fn direct_selection_cut_timing() { + let mut runs: [(Vec, Vec); 2] = Default::default(); + for round in 0..7 { + for (k, (cpu, wall)) in runs.iter_mut().enumerate() { + let mut s = many(); + let (c0, w0) = (cpu_time(), Instant::now()); + if k == 0 { + reference_cut(&mut s); + } else { + run(&mut s, "edit.cut", json!({})); + } + let w = w0.elapsed(); + let c = c0.zip(cpu_time()).map(|(a, b)| b.saturating_sub(a)).unwrap_or(w); + println!("round {round} {}: cpu {c:?}, wall {w:?}", ["one at a time", "Cut"][k]); + cpu.push(c); + wall.push(w); + } + } + for (k, (cpu, wall)) in runs.into_iter().enumerate() { + println!("median {}: cpu {:?}, wall {:?}", ["one at a time", "Cut"][k], median(cpu), median(wall)); + } +} diff --git a/crates/engine/src/cmd/effectcmd/graphics.rs b/crates/engine/src/cmd/effectcmd/graphics.rs index e80c1b2d36..868f6f5c5c 100644 --- a/crates/engine/src/cmd/effectcmd/graphics.rs +++ b/crates/engine/src/cmd/effectcmd/graphics.rs @@ -28,7 +28,7 @@ pub(super) fn specs() -> Vec { "Map Graphic", [], None, - "{symbol: name of a document symbol, face?: front|back (front; Plane has only a front; the back reads left to right as seen from behind; on Revolve the front is its swept side, which is the only face), x?: pt, y?: pt (0, 0: the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on Revolve from the middle of the side unrolled flat, x around the axis and y along the profile), scale?: % (1..10000; default 100, or less so the graphic fits inside the object, on Revolve inside the half of the side seen from the front), rotation?: degrees (-360..360, 0; counterclockwise), index?: int (the 3D effect's position; default: each object's first 3D effect, its own before its fills' and strokes'), item?: appearance item index|null (refused without index; as effect.setParams), ids?|id?} add a graphic to the 3D effect of each selected object, drawn on that face turned, foreshortened and shaded with it and clipped to it (on Revolve wrapped around the side, and drawn only where its outside faces the viewer); every object's 3D effect must be Extrude & Bevel (on a solid cap), Rotate (the Plane type) or Revolve; one undo step → {ids, graphic}", + "{symbol: name of a document symbol, face?: front|back|side (front; Plane has only a front; the back reads left to right as seen from behind; side is Extrude & Bevel's walls and bevels; on Revolve the front is its swept side, which is the only face), x?: pt, y?: pt (0, 0: the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on a side from the middle of the side unrolled flat: on Extrude & Bevel x along the outline, clockwise from its top, and y from the front toward the back; on Revolve x around the axis and y along the profile), scale?: % (1..10000; default 100, or less so the graphic fits inside the object, on Extrude & Bevel's side inside the side unrolled about x = 0, short of its cut, on Revolve inside the half of the side seen from the front), rotation?: degrees (-360..360, 0; counterclockwise), index?: int (the 3D effect's position; default: each object's first 3D effect, its own before its fills' and strokes'), item?: appearance item index|null (refused without index; as effect.setParams), ids?|id?} add a graphic to the 3D effect of each selected object, drawn on that face turned, foreshortened and shaded with it and clipped to it (on a side wrapped around it, and drawn only where its outside faces the viewer); every object's 3D effect must be Extrude & Bevel (on a solid cap, or on the side, hollow or not), Rotate (the Plane type) or Revolve; one undo step → {ids, graphic}", has_doc, map_graphic ), @@ -113,22 +113,32 @@ fn map_graphic(s: &mut Session, p: &Value) -> Result { if !effects::takes_graphics(&effect.id) { return Err(bad(C, format!("object {}: {}", id.0, effects::GRAPHICS_NOT_TAKEN))); } - // A hollow Extrude & Bevel keeps the graphics it has, to show when Cap is turned on again, - // but has no cap to show a new one on. + // A hollow Extrude & Bevel keeps the graphics it has on its caps, to show when Cap is turned + // on again, but has no cap to show a new one on. Its side takes graphics. let merged = effects::merged_params(&effect.id, &effect.params); let extrude = (effect.id == effects::EXTRUDE).then(|| effects::extrude_options(&merged)); - if extrude.is_some_and(|o| o.depth > 0.0 && !o.cap) { + let side = base.face == effects::PlanarFace::Side; + if !side && extrude.is_some_and(|o| o.depth > 0.0 && !o.cap) { return Err(bad(C, format!("object {}: a hollow Extrude & Bevel has no caps: turn on Cap to map a graphic", id.0))); } // With a depth of 0 the art is a plane, which has only a front. - if base.face == effects::PlanarFace::Back && extrude.is_some_and(|o| o.depth <= 0.0) { + if base.face != effects::PlanarFace::Front && extrude.is_some_and(|o| o.depth <= 0.0) { return Err(bad(C, format!("object {}: with a depth of 0 the object has one face: map its graphics onto the front", id.0))); } let mut graphic = base.clone(); if p.get("scale").is_none() - && let (Some(frame), Some(art)) = (effects::graphic_frame_at(Some(d), n, item, index), effects::graphic_bounds(d, &graphic.symbol)) + && let Some(art) = effects::graphic_bounds(d, &graphic.symbol) { - graphic.scale = frame.fitting_scale(art); + // A graphic on the side starts fitting inside the side unrolled about x = 0, short of + // its cut; one on a cap inside the object's bounds. + let fit = if side { + effects::graphic_side_size(Some(d), n, item, index).map(|(w, h)| effects::graphic_fitting_scale(w, h, art)) + } else { + effects::graphic_frame_at(Some(d), n, item, index).map(|frame| frame.fitting_scale(art)) + }; + if let Some(fit) = fit { + graphic.scale = fit; + } } let params = effects::with_graphic(&effects::merged_params(&effect.id, &effect.params), &graphic); effects::validate_three_d_at_in(Some(d), n, &effect.id, ¶ms, (item, index)).map_err(|e| bad(C, e))?; diff --git a/crates/engine/src/cmd/effectcmd/graphics_tests.rs b/crates/engine/src/cmd/effectcmd/graphics_tests.rs index a9d3a754ce..35fd4cc893 100644 --- a/crates/engine/src/cmd/effectcmd/graphics_tests.rs +++ b/crates/engine/src/cmd/effectcmd/graphics_tests.rs @@ -135,6 +135,47 @@ fn map_graphic_refuses_what_cannot_take_it_and_changes_nothing() { assert!(s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [id.0]})).is_ok()); } +#[test] +fn map_graphic_puts_a_graphic_on_the_side_of_an_extrude() { + let (mut s, id) = setup("threeD.extrude"); + // A hollow Extrude & Bevel takes a graphic on its side. + s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"cap": false}})).unwrap(); + s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "side", "y": 4.0, "ids": [id.0]})).unwrap(); + assert_eq!(graphics(&s, id), json!([{"symbol": "Mark", "face": "side", "x": 0.0, "y": 4.0, "scale": 100.0, "rotation": 0.0}])); + // A plane, and a depth of 0, have no side. + let (mut s, plane) = setup("threeD.rotate"); + let history = undo_len(&s); + let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "side", "ids": [plane.0]})).unwrap_err().to_string(); + assert!(e.contains("one face"), "{e}"); + assert_eq!(undo_len(&s), history); + let (mut s, flat) = setup("threeD.extrude"); + s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"depth": 0.0}})).unwrap(); + let history = undo_len(&s); + let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "side", "ids": [flat.0]})).unwrap_err().to_string(); + assert!(e.contains("one face"), "{e}"); + assert_eq!(undo_len(&s), history); + // A graphic taller than the side starts scaled to fit it: the side of the 100 × 100 square is + // about 300 pt wide short of its cut and 10 pt deep here, and the graphic with its stroke is + // 11 × 21. + let (mut s, id) = setup("threeD.extrude"); + s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"depth": 10.0}})).unwrap(); + s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "side", "ids": [id.0]})).unwrap(); + let scale = graphics(&s, id)[0]["scale"].as_f64().unwrap(); + assert!((scale - 1000.0 / 21.0).abs() < 1e-9, "{scale}"); + // A graphic wider than the side is kept short of the cut, at a bottom corner of the square: the + // part about x = 0 is three quarters of the outline. + let (mut s, id) = setup("threeD.extrude"); + let wide = s.execute("path.create", &json!({"d":"M0 380L400 380L400 390L0 390Z"})).unwrap()["id"].clone(); + s.execute("threeD.addGraphic", &json!({"name": "Wide", "ids": [wide]})).unwrap(); + s.execute("threeD.mapGraphic", &json!({"symbol": "Wide", "face": "side", "ids": [id.0]})).unwrap(); + let d = &s.doc().unwrap().doc; + let (span, _) = vectorcraft_render::effects::graphic_side_size(Some(d), d.node(id).unwrap(), None, 0).unwrap(); + let art = vectorcraft_render::effects::graphic_bounds(d, "Wide").unwrap(); + assert!((span - 300.0).abs() < 1e-6 || (span - 303.0).abs() < 1e-6, "{span}"); + let scale = graphics(&s, id)[0]["scale"].as_f64().unwrap(); + assert!((scale - 100.0 * span / art.width()).abs() < 1e-9, "{scale}"); +} + #[test] fn set_params_edits_graphics_and_checks_them() { let (mut s, id) = setup("threeD.extrude"); diff --git a/crates/engine/src/cmd/expand.rs b/crates/engine/src/cmd/expand.rs index a17a02ed15..7117899baf 100644 --- a/crates/engine/src/cmd/expand.rs +++ b/crates/engine/src/cmd/expand.rs @@ -1150,21 +1150,27 @@ fn random_brushes_baked<'a>( std::borrow::Cow::Owned(def) } -/// Does brush `name` of `brushes` draw different art for different points: a calligraphic or -/// scatter brush with Random variation, or a bristle brush? -fn draws_random_art(brushes: &[vectorcraft_brush::Brush], name: &str) -> bool { +/// Does brush `name` of `brushes`, with the stroke's own brush settings `options`, draw different +/// art for different points: a calligraphic or scatter brush with Random variation, or a bristle +/// brush? +fn draws_random_art(brushes: &[vectorcraft_brush::Brush], name: &str, options: &serde_json::Map) -> bool { use vectorcraft_brush::{BrushKind, Variation}; - brushes.iter().find(|b| b.name == name).is_some_and(|b| match &b.kind { + let Some(brush) = brushes.iter().find(|b| b.name == name) else { return false }; + let edited = if options.is_empty() { None } else { brush.with_stroke_options(options).ok() }; + let b = edited.as_ref().unwrap_or(brush); + match &b.kind { BrushKind::Calligraphic(c) => c.modes().contains(&Variation::Random), BrushKind::Scatter(s) => s.modes().contains(&Variation::Random), BrushKind::Bristle(_) => true, BrushKind::Art(_) | BrushKind::Pattern(_) => false, - }) + } } /// Is `n` a path with a visible stroke whose brush varies at random ([`draws_random_art`])? fn random_brushed(brushes: &[vectorcraft_brush::Brush], n: &Node) -> bool { - let random = |st: &vectorcraft_doc::appearance::StrokeLayer| st.visible && st.brush.as_deref().is_some_and(|b| draws_random_art(brushes, b)); + let random = |st: &vectorcraft_doc::appearance::StrokeLayer| { + st.visible && st.brush.as_deref().is_some_and(|b| draws_random_art(brushes, b, &st.brush_options)) + }; matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) && n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(st) if random(st))) } diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index a6e913f9f6..cd6ec30f0d 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -65,6 +65,7 @@ pub mod zip; use serde_json::{Value, json}; +pub(crate) use action_batch::action_step; pub use action_batch::batch_overwrites_one_file; pub use dxf::{UNSUPPORTED, Unsupported, unsupported}; pub use encode::{ @@ -95,7 +96,7 @@ pub use naming::{NameParts as FileNameParts, parse_date as parse_file_date, rend pub(crate) use native::preview_png; pub use native::with_compression_pref; pub(crate) use pdfimport::opened_page_document; -pub use pdfimport::{LoadOptions, page_document}; +pub use pdfimport::{LoadOptions, page_document, pages_can_link}; pub(crate) use psdlayers::import_active as psd_layers; pub use psdlayers::{PsdInfo, info as psd_info}; pub(crate) use psdslices::over as psd_slices; @@ -133,7 +134,7 @@ mod formats; #[cfg(not(target_arch = "wasm32"))] pub(crate) use access::list_dir; -pub(crate) use access::{check_images_in, check_scripts_of}; +pub(crate) use access::{check_images_in, check_scripts_of, with_readable_settings_folder}; pub use access::{check_linked_images, check_linked_scripts, write_file_with, write_save_file, write_save_file_with}; #[cfg(all(test, not(target_arch = "wasm32")))] diff --git a/crates/engine/src/cmd/fileio/access.rs b/crates/engine/src/cmd/fileio/access.rs index 9d2d9a4a33..bd55624b32 100644 --- a/crates/engine/src/cmd/fileio/access.rs +++ b/crates/engine/src/cmd/fileio/access.rs @@ -144,8 +144,9 @@ pub(crate) fn check_scripts_of(cmd: &str, doc: &vectorcraft_doc::Document, doc_p } /// Does a file of a document with `artboards` artboards, written in format `format` with options -/// `p`, name the JavaScript files the document links? SVG, SVGZ, native files, native templates and -/// EPS files always do. A `.ai` or `.ait` file does unless it is a legacy version 7 `.ai` file or `p` +/// `p`, name the JavaScript files the document links? SVG, SVGZ, native files, native templates, +/// EPS files and the files of an exporter plug-in's format (`plugin.`, whose plug-in is given +/// the native document's JSON) always do. A `.ai` or `.ait` file does unless it is a legacy version 7 `.ai` file or `p` /// picks only some of the artboards; a PDF does with Preserve Editing on (as its preset, standard and /// options leave it) unless `p` picks only some of the artboards. Neither a `.ai` file nor a PDF /// does when `useArtboards` is false in `p` (one page, the bounds of the art). Options the encoder @@ -159,6 +160,7 @@ pub(crate) fn names_linked_scripts(cmd: &str, format: &str, p: &Value, artboards let art_page = || super::encode::use_artboards(cmd, p).is_ok_and(|u| u == Some(false)); match format { "svg" | "svgz" | "vectorcraft" | "template" | "eps" => true, + _ if vectorcraft_plugins::export::plugin_id(format).is_some() => true, "ai" | "ait" => { let legacy = super::format(format).is_some_and(|f| super::legacy_ai::wanted(cmd, f, p).unwrap_or(false)); !legacy && !(format == "ai" && art_page()) && every_artboard() @@ -171,13 +173,14 @@ pub(crate) fn names_linked_scripts(cmd: &str, format: &str, p: &Value, artboards } } -/// The error for an SVG that would name a linked image's file outside the read roots. +/// The error for a file that would name a linked image's file outside the read roots. pub(crate) const IMAGE_OUTSIDE: &str = "a linked image file is outside the read roots"; /// `cmd` may write `d`, the document an output of `st` writes (all of it, or the objects it -/// exports), in format `format` (a format id) with options `p`: any format but SVG and SVGZ, and -/// those too unless read roots are in force and the file would name a linked image's file outside -/// them (a relative path taken from `st`'s folder; a URL is not checked). An `` names the +/// exports), in format `format` (a format id) with options `p`: always, unless read roots are in +/// force and the file would name a linked image's file outside them (a relative path taken from +/// `st`'s folder; a URL is not checked). In any format but SVG and SVGZ, the file names them when it +/// carries the native document ([`check_native_images`]). An `` names the /// file with SVG Options › Images set to Link, and with Embed when the document holds no pixels for /// the image, for the images of the art each file draws (with chosen artboards, the art over each /// one; hidden layers and objects only with `hiddenLayers`, template layers and the opacity-mask @@ -193,9 +196,12 @@ pub fn check_linked_images(cmd: &str, format: &str, st: &crate::DocState, d: &ve /// [`check_linked_images`] for `d`, a document whose links are looked for from `base` (the /// objects on the clipboard, looked for from the document they came from). pub(crate) fn check_images_in(cmd: &str, format: &str, d: &vectorcraft_doc::Document, base: crate::cmd::links::LinkBase, p: &Value) -> Result<()> { - if !matches!(format, "svg" | "svgz") || crate::file_access::current().is_none() { + if crate::file_access::current().is_none() { return Ok(()); } + if !matches!(format, "svg" | "svgz") { + return check_native_images(cmd, format, d, base, p); + } // Options that don't read as the encoder's choices count as Link, Preserve Editing, hidden // layers kept and SVG 1.1: the encoder refuses them anyway. let (link, preserve, hidden, tiny) = match super::svg::options_map(p) { @@ -222,6 +228,39 @@ pub(crate) fn check_images_in(cmd: &str, format: &str, d: &vectorcraft_doc::Docu Ok(()) } +/// `cmd` may write `d` in format `format` (a format id other than SVG and SVGZ) with options `p`: +/// always, unless read roots are in force, the file carries the native document (a native file or +/// template, an EPS file, a `.ai` or `.ait` file, a PDF with Preserve Editing or an exporter +/// plug-in's file, as +/// [`names_linked_scripts`] counts them with `d`'s artboards) and that document names a file +/// outside them ([`crate::cmd::links::names_hidden_file`]: a linked image or placed file, the +/// relative path kept of one taken from `base`, a data set's image, or stored brushes that can't be +/// read). The error names no file or folder. +pub(crate) fn check_native_images( + cmd: &str, + format: &str, + d: &vectorcraft_doc::Document, + base: crate::cmd::links::LinkBase, + p: &Value, +) -> Result<()> { + let carried = + crate::file_access::current().is_some() && !matches!(format, "svg" | "svgz") && names_linked_scripts(cmd, format, p, d.artboards.len()); + if carried && crate::cmd::links::names_hidden_file(d, base) { Err(bad(cmd, IMAGE_OUTSIDE)) } else { Ok(()) } +} + +/// `doc` as a file written for the request being served carries it: without an Export for Screens +/// `folder` outside the read roots ([`super::screens::leave_out_unreadable_settings_folder`]). The +/// open document keeps it. +pub(crate) fn with_readable_settings_folder(doc: &vectorcraft_doc::Document) -> std::borrow::Cow<'_, vectorcraft_doc::Document> { + let settings = super::screens::leave_out_unreadable_settings_folder(doc.export_settings.clone()); + if settings.len() == doc.export_settings.len() { + return std::borrow::Cow::Borrowed(doc); + } + let mut kept = doc.clone(); + kept.export_settings = settings; + std::borrow::Cow::Owned(kept) +} + /// `path` checked for writing against the automation roots in force. #[cfg(not(target_arch = "wasm32"))] pub(crate) fn may_write(path: &str) -> Result<()> { diff --git a/crates/engine/src/cmd/fileio/action_batch.rs b/crates/engine/src/cmd/fileio/action_batch.rs index 4e99f4ee3e..aa3be78e2a 100644 --- a/crates/engine/src/cmd/fileio/action_batch.rs +++ b/crates/engine/src/cmd/fileio/action_batch.rs @@ -54,24 +54,19 @@ pub(super) fn action_batch(s: &mut Session, p: &Value) -> Result { } for (i, c) in cmds.iter().enumerate() { let id = c.get("command").and_then(Value::as_str).unwrap_or(""); + let refuse = |reason: &str| bad(C, action_step(i, id, reason)); if id.is_empty() { - return Err(bad(C, format!("commands[{i}]: missing `command`"))); + return Err(refuse("missing `command`")); } if id == "command.batch" || id == "action.batch" { - return Err(bad(C, "batches cannot nest")); + return Err(refuse("batches cannot nest")); } // `command.batch` refuses the batch when it reaches this step, which would fail every file or data set it plays. if id == "prefs.import" { - return Err(bad(C, format!("commands[{i}]: `prefs.import` runs on its own, not as a batch step"))); + return Err(refuse("`prefs.import` runs on its own, not as a batch step")); } if find_command(id).is_none() { - return Err(bad( - C, - match super::super::params::nearest_command(id) { - Some(near) => format!("commands[{i}]: unknown command `{id}`; did you mean `{near}`?"), - None => format!("commands[{i}]: unknown command `{id}`"), - }, - )); + return Err(refuse(&super::super::params::unknown_command(id).to_string())); } } // Every option is checked before the destination folder is made. @@ -160,7 +155,7 @@ pub fn batch_overwrites_one_file(s: &Session, p: &Value) -> bool { Some(f) => own_format.is_some_and(|own| super::format(f).is_some_and(|f| f.id == own)), }; match c.get("command").and_then(Value::as_str).unwrap_or("") { - "document.save" | "file.save" => !save && (path || own_file()), + "document.save" => !save && (path || own_file()), "file.saveAs" => !save && path, "file.saveCopy" | "file.saveAsTemplate" => path, "document.export" | "document.exportSelection" => !export && path, @@ -184,7 +179,7 @@ fn saves_move_to_each_file(steps: &[Value], redirected: bool) -> bool { /// in the destination folder when `redirected`) and makes that file the document's own: a save in /// the native template format writes a copy and leaves the document's file as it was. fn retargeting_save(c: &Value, redirected: bool) -> bool { - if !matches!(c.get("command").and_then(Value::as_str), Some("document.save" | "file.save" | "file.saveAs")) { + if !matches!(c.get("command").and_then(Value::as_str), Some("document.save" | "file.saveAs")) { return false; } let params = c.get("params"); @@ -219,7 +214,7 @@ fn batch_folder(s: &mut Session, cmd: &str, p: &Value, override_open: bool, run: // open, so its artboard files count ([`dataset_output_paths`]). No output takes the name of a // source file in the destination folder, other than that file's own output, or of a subfolder // of the destination folder that holds source files. - let (steps, places) = filter_steps(run.steps, override_open, false); + let (steps, places) = filter_steps(run.steps, override_open); let run = Run { steps: &steps, ..*run }; let in_dest: Vec> = files.iter().map(|path| name_in_folder(path, run.dest_folder)).collect(); let mut picker = @@ -272,7 +267,7 @@ fn batch_datasets(s: &mut Session, cmd: &str, run: &Run<'_>) -> Result { } let doc_stem = st.path.as_deref().and_then(|p| std::path::Path::new(p).file_stem().and_then(|s| s.to_str())).unwrap_or("Untitled").to_string(); let stems = dataset_stems(&names, &doc_stem, run.dataset_file_naming, run, &st.doc)?; - let (steps, places) = filter_steps(run.steps, true, false); + let (steps, places) = filter_steps(run.steps, true); let run = Run { steps: &steps, ..*run }; let mut processed = Vec::new(); let mut failed = 0usize; @@ -353,22 +348,13 @@ impl StemPicker { } } -/// Drop Open (and optionally Close) steps when the batch supplies the file itself → the steps that -/// stay, and the index of each in `cmds`. +/// Drop the `document.open` steps when `drop_open` (the batch opens each source file itself) → the +/// steps that stay, and the index of each in `cmds`. #[cfg(not(target_arch = "wasm32"))] -fn filter_steps(cmds: &[Value], drop_open: bool, drop_close: bool) -> (Vec, Vec) { +fn filter_steps(cmds: &[Value], drop_open: bool) -> (Vec, Vec) { cmds.iter() .enumerate() - .filter(|(_, c)| { - let id = c.get("command").and_then(Value::as_str).unwrap_or(""); - if drop_open && matches!(id, "document.open" | "file.open") { - return false; - } - if drop_close && matches!(id, "file.close" | "document.close") { - return false; - } - true - }) + .filter(|(_, c)| !(drop_open && c.get("command").and_then(Value::as_str) == Some("document.open"))) .map(|(i, c)| (c.clone(), i)) .unzip() } @@ -385,12 +371,24 @@ fn play_steps(s: &mut Session, run: &Run<'_>, places: &[usize], commands: Vec EngineError::Other(format!("action step {} (`{id}`) failed: {reason}", place + 1)), + Some(&place) if same => EngineError::Other(action_step(place, id, reason)), _ => e, } }) } +/// The text naming the member at `index` of an `action.batch`'s `commands`, counted from 1, with +/// its command id when it has one, and `reason`: ``action step 2 (`object.move`) failed: …``. The +/// checks before a batch runs and the errors of its steps as they run give the same text. +pub(crate) fn action_step(index: usize, id: &str, reason: &str) -> String { + let n = index.saturating_add(1); + if id.is_empty() { + format!("action step {n} failed: {reason}") + } else { + format!("action step {n} (`{}`) failed: {reason}", vectorcraft_apischema::shown_key(id)) + } +} + /// The step number, command id and reason in the error `command.batch` gives when one of its steps /// fails (``batch step 2 (`object.move`) failed: …``); none for any other error. #[cfg(not(target_arch = "wasm32"))] @@ -540,7 +538,7 @@ fn dataset_output_extensions(run: &Run<'_>, doc: &vectorcraft_doc::Document, def outputs.push(DatasetOutput { ext: String::new(), artboards: false, joiner: "-", folder: true }); continue; } - let writes = (run.override_save && matches!(id, "document.save" | "file.save" | "file.saveAs")) + let writes = (run.override_save && matches!(id, "document.save" | "file.saveAs")) || (run.override_export && matches!(id, "document.export" | "document.exportSelection")); if writes { let format = step.get("params").and_then(|p| p.get("format")).and_then(Value::as_str).filter(|f| !f.is_empty()); @@ -551,7 +549,7 @@ fn dataset_output_extensions(run: &Run<'_>, doc: &vectorcraft_doc::Document, def }; if safe_extension(&ext) { let format_id = super::format(format.unwrap_or(default_ext)).map(|f| f.id).unwrap_or("vectorcraft"); - let is_save = matches!(id, "document.save" | "file.save" | "file.saveAs"); + let is_save = matches!(id, "document.save" | "file.saveAs"); let artboards = if is_save { !doc.artboards.is_empty() && matches!(format_id, "vectorcraft" | "template" | "ai" | "ait") } else { @@ -693,7 +691,7 @@ fn rewrite_paths( .map(|c| { let id = c.get("command").and_then(Value::as_str).unwrap_or(""); let mut c = c.clone(); - let rewrite = (override_save && matches!(id, "document.save" | "file.save" | "file.saveAs")) + let rewrite = (override_save && matches!(id, "document.save" | "file.saveAs")) || (override_export && matches!(id, "document.export" | "document.exportForScreens" | "document.exportSelection" | "assets.export")); if !rewrite { return c; @@ -2385,10 +2383,97 @@ mod tests { let mut s = Session::new(); let p = json!({"folder": src.to_string_lossy(), "commands": [{"command": "object.unlockAll"}, {"command": "prefs.import", "params": {}}]}); let e = s.execute("action.batch", &p).unwrap_err().to_string(); - assert!(e.contains("commands[1]: `prefs.import` runs on its own, not as a batch step"), "{e}"); + assert!(e.contains("action step 2 (`prefs.import`) failed: `prefs.import` runs on its own, not as a batch step"), "{e}"); assert!(s.active().is_none(), "no file was opened"); } + /// Each step the checks before the batch refuse is named by its place in `commands`, from 1, + /// as a step that fails as it runs is, and no source file is opened. + #[test] + fn a_refused_step_is_named_by_its_place_from_1() { + let src = tmp("step-number-refused-src"); + write_svg(&src, "a.svg", "#f00"); + let prefix = "invalid parameters for `action.batch`: "; + let cases = [ + (json!({"params": {}}), "action step 2 failed: missing `command`"), + (json!({"command": "select.al"}), "action step 2 (`select.al`) failed: unknown command `select.al`; did you mean `select.all`?"), + (json!({"command": "command.batch", "params": {"commands": []}}), "action step 2 (`command.batch`) failed: batches cannot nest"), + (json!({"command": "action.batch", "params": {}}), "action step 2 (`action.batch`) failed: batches cannot nest"), + ( + json!({"command": "view.saved.new", "params": {"center": [0, 0], "zoom": 0}}), + "action step 2 (`view.saved.new`) failed: invalid parameters for `view.saved.new`: `zoom` must be a number > 0, not 0", + ), + ]; + for (step, want) in cases { + let mut s = Session::new(); + let p = json!({"folder": src.to_string_lossy(), "commands": [{"command": "object.unlockAll"}, step]}); + let e = s.execute("action.batch", &p).unwrap_err().to_string(); + assert_eq!(e, format!("{prefix}{want}"), "{step}"); + assert!(s.active().is_none(), "{step}: a file was opened"); + assert!(s.journal.is_empty(), "{step}: a step ran"); + } + } + + /// The parameter check of an `action.batch` names the step whose params it refuses, from 1; + /// that of a `command.batch` passes the step's error on as it is. + #[test] + fn the_parameter_check_names_the_refused_step() { + let bad_view = json!({"command": "view.saved.new", "params": {"center": [0, 0], "zoom": 0}}); + let commands = json!([{"command": "object.unlockAll"}, {"command": "select.all"}, bad_view]); + let own = "invalid parameters for `view.saved.new`: `zoom` must be a number > 0, not 0"; + let e = crate::cmd::params::check_params("action.batch", &json!({"commands": commands})).unwrap_err().to_string(); + assert_eq!(e, format!("invalid parameters for `action.batch`: action step 3 (`view.saved.new`) failed: {own}")); + let e = crate::cmd::params::check_params("command.batch", &json!({"commands": commands})).unwrap_err().to_string(); + assert_eq!(e, own); + } + + /// The ids of the File menu's Open… and Save in the app (`file.open`, `file.save`) and + /// `document.close` are not engine commands, so a step with one is refused before the batch + /// starts, with Override Open and Override Save on or off. + #[test] + fn steps_with_ids_that_are_not_engine_commands_are_refused() { + let src = tmp("step-number-aliases-src"); + write_svg(&src, "a.svg", "#f00"); + for id in ["file.open", "file.save", "document.close"] { + for overrides in [true, false] { + let mut s = Session::new(); + let p = json!({ + "folder": src.to_string_lossy(), + "overrideOpen": overrides, + "overrideSave": overrides, + "commands": [{"command": "object.unlockAll"}, {"command": id, "params": {}}], + }); + let e = s.execute("action.batch", &p).unwrap_err().to_string(); + assert!( + e.starts_with(&format!("invalid parameters for `action.batch`: action step 2 (`{id}`) failed: unknown command `{id}`")), + "{e}" + ); + assert!(s.active().is_none(), "{id}: a file was opened"); + } + } + } + + /// `command.batch` keeps its own numbering, from 0, for a step that fails. + #[test] + fn command_batch_keeps_its_own_step_numbers() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let e = s + .execute("command.batch", &json!({"commands": [{"command": "object.unlockAll"}, {"command": "object.align", "params": {}}]})) + .unwrap_err(); + assert!(e.to_string().starts_with("batch step 1 (`object.align`) failed: "), "{e}"); + } + + /// A step's id in the error is cut short, as an unknown key's is. + #[test] + fn a_long_step_id_is_cut_short() { + let id = "x".repeat(10_000); + let shown = action_step(0, &id, "why"); + assert!(shown.len() < 1_000, "{}", shown.len()); + assert!(shown.starts_with("action step 1 (`xxx") && shown.ends_with("…`) failed: why"), "{shown}"); + assert_eq!(action_step(usize::MAX, "", "why"), format!("action step {} failed: why", usize::MAX)); + } + /// Only the error `command.batch` gives for a failed step is read as one. #[test] fn batch_step_failure_reads_only_a_step_error() { diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index adc73c2c85..0969adb5a2 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -117,7 +117,7 @@ pub fn specs() -> Vec { "Batch…", [], None, - "{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close; for source datasets, save the open document over its own file after each data set, and refuse a document that was never saved, was converted from an older version or was restored by Data Recovery, unless a recorded Save or Save As step writes a file first; a Save or Save As step that overrideSave points into destinationFolder makes each data set's file the document's own) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), datasetFileNaming?: fileNumber | fileDataSetName (default) | dataSetName (used only for source datasets; ignored for folder), overrideOpen?: true (skip document.open / file.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportSelection the same way, and give document.exportForScreens / assets.export the folder destinationFolder/{stem}, one for each source file or data set, in which the export names its files as it does outside Batch), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs; {stem} is the file's name without its extension and without trailing periods and spaces, with `-2`, `-3`… added to a name an earlier file used or whose file or folder has the name of one an earlier file wrote or of another source file or a folder of source files in destinationFolder), or on every data set of the open document. Data set names use the document stem plus a three-digit ordinal, the document stem and an underscore plus the data set name, or the data set name alone. Invalid file name characters become `-` and trailing periods and spaces are dropped; a name already used in the batch or whose output file or folder already exists in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix before the format-derived extension. Caps: 500 files or data sets, 8 folder levels, 256 steps. Batches cannot nest, and a prefs.import step is refused (commands[i], from 0) before any file is opened. A switch (includeSubdirs, overrideOpen, overrideSave, overrideExport, stopOnError) that is not true or false, or a source, folder, destination, destinationFolder, datasetFileNaming or label that is not a string, is an error before any folder is made or file opened; null reads as left out. A step that fails is named in the error by its place in commands, from 1, counting the Open steps the batch skips (action step 3 (`object.align`) failed: …); the batch's own opening of a file, choosing of a data set and destination save, export or close give their errors without a step number. → {processed: [{path|dataset, result|error}…], count, failed, stopped, warning?} (warning: for source datasets, when Save and Close without such a step, or a Save, Save a Copy, Save as Template or export step (document.export, exportSelection, exportForScreens, exportPdf, exportEps, exportDxf, exportForWeb, exportForOffice) that writes a file and is not pointed into destinationFolder, saves every data set over the same file)", + "{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close; for source datasets, save the open document over its own file after each data set, and refuse a document that was never saved, was converted from an older version or was restored by Data Recovery, unless a recorded Save or Save As step writes a file first; a Save or Save As step that overrideSave points into destinationFolder makes each data set's file the document's own) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), datasetFileNaming?: fileNumber | fileDataSetName (default) | dataSetName (used only for source datasets; ignored for folder), overrideOpen?: true (skip document.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportSelection the same way, and give document.exportForScreens / assets.export the folder destinationFolder/{stem}, one for each source file or data set, in which the export names its files as it does outside Batch), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs; {stem} is the file's name without its extension and without trailing periods and spaces, with `-2`, `-3`… added to a name an earlier file used or whose file or folder has the name of one an earlier file wrote or of another source file or a folder of source files in destinationFolder), or on every data set of the open document. Data set names use the document stem plus a three-digit ordinal, the document stem and an underscore plus the data set name, or the data set name alone. Invalid file name characters become `-` and trailing periods and spaces are dropped; a name already used in the batch or whose output file or folder already exists in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix before the format-derived extension. Caps: 500 files or data sets, 8 folder levels, 256 steps. A step without a command, with a command the engine doesn't have, with params its command refuses, or with command.batch, action.batch or prefs.import (batches cannot nest) is refused before any file is opened, named by its place in commands, from 1 (action step 2 (`select.al`) failed: unknown command `select.al`; did you mean `select.all`?). A switch (includeSubdirs, overrideOpen, overrideSave, overrideExport, stopOnError) that is not true or false, or a source, folder, destination, destinationFolder, datasetFileNaming or label that is not a string, is an error before any folder is made or file opened; null reads as left out. A step that fails as it runs is named the same way, counting the Open steps the batch skips (action step 3 (`object.align`) failed: …); the batch's own opening of a file, choosing of a data set and destination save, export or close give their errors without a step number. → {processed: [{path|dataset, result|error}…], count, failed, stopped, warning?} (warning: for source datasets, when Save and Close without such a step, or a Save, Save a Copy, Save as Template or export step (document.export, exportSelection, exportForScreens, exportPdf, exportEps, exportDxf, exportForWeb, exportForOffice) that writes a file and is not pointed into destinationFolder, saves every data set over the same file)", always, action_batch::action_batch ), diff --git a/crates/engine/src/cmd/fileio/dxf.rs b/crates/engine/src/cmd/fileio/dxf.rs index 8486cd2226..8004234c07 100644 --- a/crates/engine/src/cmd/fileio/dxf.rs +++ b/crates/engine/src/cmd/fileio/dxf.rs @@ -226,9 +226,10 @@ pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option) -> vec![(Some(b), rect(b)?, false)] } }; + let regions: Vec<(Rect, bool)> = drawings.iter().map(|&(_, region, crop)| (region, crop)).collect(); + let outs = vectorcraft_cad::export_drawings(doc, &opts, ®ions).map_err(|e| bad(C, e))?; let mut enc = Encoded::default(); - for (board, region, crop) in drawings { - let out = vectorcraft_cad::export(doc, &DxfOptions { region, crop, ..opts.clone() }).map_err(|e| bad(C, e))?; + for ((board, _, _), out) in drawings.into_iter().zip(outs) { enc.files.push((board, out.bytes)); for w in out.warnings { if !enc.warnings.contains(&w) { diff --git a/crates/engine/src/cmd/fileio/encode.rs b/crates/engine/src/cmd/fileio/encode.rs index 3e34dae7f2..8b5cd9fe6f 100644 --- a/crates/engine/src/cmd/fileio/encode.rs +++ b/crates/engine/src/cmd/fileio/encode.rs @@ -1053,12 +1053,14 @@ fn encode_all_of(doc: &Document, format: &str, p: &Value) -> Result { /// The file exporter plug-in `plugin` writes of `doc` in its format `f` /// ([`vectorcraft_plugins::export`]). The plug-in is given the native file's JSON -/// ([`vectorcraft_format::json_part`]) and `p`'s `params`, for the file `p`'s `path` names (else -/// one named after the document) with that path's extension when the plug-in lists it, else its -/// first. Its warnings come back with the file, as losses (the plug-in gives them no kind). +/// ([`vectorcraft_format::json_part`]), without an Export for Screens folder outside the read roots +/// ([`super::access::with_readable_settings_folder`]), and `p`'s `params`, for the file `p`'s `path` +/// names (else one named after the document) with that path's extension when the plug-in lists it, +/// else its first. Its warnings come back with the file, as losses (the plug-in gives them no kind). fn plugin_file(doc: &Document, plugin: &vectorcraft_plugins::Plugin, f: &Format, p: &Value) -> Result { use vectorcraft_plugins::{Error, export}; - let doc = &*doc.without_edit_modes(); + let doc = doc.without_edit_modes(); + let doc = &*super::access::with_readable_settings_folder(&doc); let file = vectorcraft_format::save_with(doc, &vectorcraft_format::SaveOptions::default()).map_err(|e| EngineError::Other(e.to_string()))?; let path = p.get("path").and_then(Value::as_str); let listed = path.map(super::extension).and_then(|e| f.extensions.iter().copied().find(|x| *x == e)); diff --git a/crates/engine/src/cmd/fileio/eps.rs b/crates/engine/src/cmd/fileio/eps.rs index 3acd23e854..5067b1c6d5 100644 --- a/crates/engine/src/cmd/fileio/eps.rs +++ b/crates/engine/src/cmd/fileio/eps.rs @@ -280,8 +280,10 @@ fn thumbnail_of(preview: &Rendered, rect: Rect) -> Result { } /// What the file carries to reopen: `doc` (with only artboard `board` when the file is one of -/// several artboards), with linked images whole when `include_linked`. +/// several artboards), with linked images whole when `include_linked`, and without an Export for +/// Screens folder outside the read roots ([`super::access::with_readable_settings_folder`]). fn native(doc: &Document, board: Option, include_linked: bool) -> Vec { + let doc = &*super::access::with_readable_settings_folder(doc); let several = board.filter(|_| doc.artboards.len() > 1); if several.is_none() && !include_linked { return vectorcraft_format::save(doc, false); diff --git a/crates/engine/src/cmd/fileio/formats.rs b/crates/engine/src/cmd/fileio/formats.rs index c53822868c..2cc57144fb 100644 --- a/crates/engine/src/cmd/fileio/formats.rs +++ b/crates/engine/src/cmd/fileio/formats.rs @@ -838,13 +838,13 @@ fn other_open_filters() -> impl Iterator impl Iterator { - std::iter::once((library_label, library_exts)).chain(builtin_open_filters().filter(move |f| *f != (library_label, library_exts))) + std::iter::once((library_label, library_exts)).chain(builtin_open_filters().filter(move |f| f.0 != library_label)) } /// File → Place dialog filters: "All placeable files", then one per placeable format, then text, diff --git a/crates/engine/src/cmd/fileio/metafile.rs b/crates/engine/src/cmd/fileio/metafile.rs index d987d82757..e9e1e882a7 100644 --- a/crates/engine/src/cmd/fileio/metafile.rs +++ b/crates/engine/src/cmd/fileio/metafile.rs @@ -26,13 +26,16 @@ pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option, kin Some(true) => pick.resolve(n).map_err(|e| bad(C, e))?.unwrap_or_else(|| (0..n).collect()), _ => vec![pick.one(n).map_err(|e| bad(C, e))?], }; + let rects = boards + .iter() + .map(|&b| doc.artboards.get(b).map(|a| a.rect).ok_or_else(|| bad(C, format!("no artboard {}", b + 1)))) + .collect::>>()?; // Raster effects (shadows, glows, blurs) as images, as PDF export does. let flat = crate::flatten_raster_effects(doc); let src = flat.as_ref().unwrap_or(doc); + let outs = vectorcraft_metafile::export_regions(src, &rects, kind).map_err(|e| bad(C, e))?; let mut enc = Encoded::default(); - for b in boards { - let region = doc.artboards.get(b).ok_or_else(|| bad(C, format!("no artboard {}", b + 1)))?.rect; - let out = vectorcraft_metafile::export(src, region, kind).map_err(|e| bad(C, e))?; + for (b, out) in boards.into_iter().zip(outs) { enc.files.push((Some(b), out.bytes)); for w in out.warnings { if !enc.warnings.contains(&w) { diff --git a/crates/engine/src/cmd/fileio/native.rs b/crates/engine/src/cmd/fileio/native.rs index cbf46c97c0..a4e0e4d24c 100644 --- a/crates/engine/src/cmd/fileio/native.rs +++ b/crates/engine/src/cmd/fileio/native.rs @@ -231,6 +231,8 @@ pub(super) fn encode_to(cmd: &str, f: &Format, doc: &Document, p: &Value, w: imp } other => other, }; + // Without an Export for Screens folder outside the read roots. + let native = super::access::with_readable_settings_folder(&native); so.pretty = so.pretty_fits(&native); vectorcraft_format::save_to(&native, &so, w).map_err(|e| bad(cmd, e.to_string())) } @@ -308,6 +310,8 @@ pub(super) fn ai_native(cmd: &str, doc: &Document, so: &SaveOptions) -> Result Vec { "Export PDF", [], None, - "{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, and with destination and an sRGB destination a gray or RGB image tagged with an ICC profile is converted from it and written untagged; with destination and a CMYK destination, or another RGB one images are converted to (not when colours are ICC-tagged), an RGB image tagged with one is converted from it through sRGB; with preserveNumbers (and pdfX1a) only untagged images keep their numbers: an RGB image tagged with one is converted from it to sRGB or through sRGB to the destination, and a gray one is converted from it in an sRGB destination; any other image whose colors are converted (a CMYK image, an RGB one going to a CMYK destination, or with destination to an RGB one other than sRGB) but whose pixels can't be decoded or written that way is left out with a warning; printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours; images are written without the ICC profiles they carry, a JPEG without its ICC_PROFILE segments, but in PDF/A, pdfX3 and pdfX4)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile)|default (not set, the default; \"default\" unsets a preset's value, null keeps it: device colours, and gray and RGB images keep the profiles they carry, but in pdfX1a) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says; a CMYK image that keeps its numbers carries the CMYK profile it embeds with all and taggedSource, and in PDF/A, pdfX3 and pdfX4 unless destination, never in pdfX1a), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out), format?: \"pdf\"} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet come back as warnings; a standard with a PDF version it doesn't allow and a password with a standard are refused, and so is a PDF/X file that would still break its standard (transparency the flattener left, RGB in pdfX1a, a font not embedded) or a PDF 1.3 file with transparency left. document.export {format: pdf} takes the same options. A key PDF doesn't take, and an unknown key inside one of the option objects, are refused. Under automation read roots, a PDF that carries the native document (preserveEditing on, every artboard, useArtboards not false) is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked)", + "{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, and with destination and an sRGB destination a gray or RGB image tagged with an ICC profile is converted from it and written untagged; with destination and a CMYK destination, or another RGB one images are converted to (not when colours are ICC-tagged), an RGB image tagged with one is converted from it through sRGB; with preserveNumbers (and pdfX1a) only untagged images keep their numbers: an RGB image tagged with one is converted from it to sRGB or through sRGB to the destination, and a gray one is converted from it in an sRGB destination; any other image whose colors are converted (a CMYK image, an RGB one going to a CMYK destination, or with destination to an RGB one other than sRGB) but whose pixels can't be decoded or written that way is left out with a warning; printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours; images are written without the ICC profiles they carry, a JPEG without its ICC_PROFILE segments, but in PDF/A, pdfX3 and pdfX4)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile)|default (not set, the default; \"default\" unsets a preset's value, null keeps it: device colours, and gray and RGB images keep the profiles they carry, but in pdfX1a) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says, but in pdfX3 and pdfX4 CMYK colors in the profile of a CMYK output intent are DeviceCMYK, and with none and a CMYK output intent pdfX3 and pdfX4 write every CMYK color as DeviceCMYK, unless colors are converted to a CMYK destination of another profile; a CMYK image that keeps its numbers carries the CMYK profile it embeds with all and taggedSource, and in PDF/A, pdfX3 and pdfX4 unless destination, never in pdfX1a, nor when CMYK colors are DeviceCMYK and either its profile is the output intent's or profiles is none), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out), format?: \"pdf\"} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet come back as warnings; a standard with a PDF version it doesn't allow and a password with a standard are refused, and so is a PDF/X file that would still break its standard (transparency the flattener left, RGB in pdfX1a, a font not embedded) or a PDF 1.3 file with transparency left. document.export {format: pdf} takes the same options. A key PDF doesn't take, and an unknown key inside one of the option objects, are refused. Under automation read roots, a PDF that carries the native document (preserveEditing on, every artboard, useArtboards not false) is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked)", has_doc, export_pdf ), @@ -338,7 +338,9 @@ pub(super) fn encode_at(cmd: &str, doc: &Document, p: &Value, modified: Option = placed.into_iter().map(Note::loss).collect(); - let (bytes, drawn) = encode_carrying_at(cmd, &full, p, modified, || Ok(vectorcraft_format::save(doc, false)), || Ok(None))?; + // The editing data leaves out an Export for Screens folder outside the read roots. + let native = || Ok(vectorcraft_format::save(&super::access::with_readable_settings_folder(doc), false)); + let (bytes, drawn) = encode_carrying_at(cmd, &full, p, modified, native, || Ok(None))?; notes.extend(drawn); if notes.iter().any(|n| n.text.ends_with(SHOWN_SMALLER)) && options(cmd, &full, p)?.settings.standard == Standard::None { for n in notes.iter_mut().filter(|n| n.text.ends_with(SHOWN_SMALLER)) { @@ -504,6 +506,7 @@ fn export_pdf(s: &mut Session, p: &Value) -> Result { let p = &*expanded; let st = s.doc()?; super::check_linked_scripts(C, "pdf", st, p)?; + super::check_linked_images(C, "pdf", st, &st.doc, p)?; let display_doc_title = super::has_own_title(&st.doc); let titled = super::titled_for_export(&st.doc, st.path.as_deref(), "pdf"); let mut q = p.clone(); diff --git a/crates/engine/src/cmd/fileio/pdfimport.rs b/crates/engine/src/cmd/fileio/pdfimport.rs index 189274a31f..ea37575135 100644 --- a/crates/engine/src/cmd/fileio/pdfimport.rs +++ b/crates/engine/src/cmd/fileio/pdfimport.rs @@ -222,6 +222,13 @@ fn page_options(page: usize, o: &LoadOptions) -> ImportOptions { ImportOptions { pages: Some(vec![page]), crop: o.crop, password: o.password.clone(), text_as: o.text_as, layers: false, ..Default::default() } } +/// Whether `document.open`'s `linkPages` takes the file `name` holding `bytes`: a PDF or a +/// PDF-compatible `.ai` or `.ait` of at most [`document::MAX_FILE`] bytes. Its path, a password +/// and `textAs` are checked apart ([`linked_pages`]). +pub fn pages_can_link(name: &str, bytes: &[u8]) -> bool { + bytes.len() <= document::MAX_FILE && document::is_pdf(name, bytes) +} + /// `document.open` with `linkPages`: the pages `o` picks of the PDF (or PDF-compatible `.ai` or /// `.ait`) `name`, read from `path`, as a document holding one placed document per page, linked to /// that page of the file as File › Place with Link places one ([`document::source`]). Each page diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index 09b7924442..8a9b29fec2 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -896,7 +896,10 @@ fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option std::borrow::Cow::Borrowed(¶ms), }; super::check_linked_scripts(cmd, plan.format.id, st, &checked)?; + super::access::check_native_images(cmd, plan.format.id, &st.doc, crate::cmd::links::LinkBase::of(st), &checked)?; Ok(SaveJob { plan, doc, params, snapshot, source: st.doc.clone(), stamped, boards }) } diff --git a/crates/engine/src/cmd/fileio/screens.rs b/crates/engine/src/cmd/fileio/screens.rs index b8e797373d..3663d3e2f6 100644 --- a/crates/engine/src/cmd/fileio/screens.rs +++ b/crates/engine/src/cmd/fileio/screens.rs @@ -1129,6 +1129,28 @@ fn names_scripts(item: &Item, r: &Row, single: Option<&[usize]>) -> bool { super::access::names_linked_scripts(C, "pdf", &options, doc.artboards.len()) } +/// The document the file of `item` that row `r` writes carries when it carries one +/// ([`names_scripts`]): Full Document's PDF of every artboard, the item's artboard alone for a +/// native, `.ai` or EPS row ([`board_document`]), else the item's document. +fn carried_document<'a>(item: &'a Item, r: &Row, single: Option<&[usize]>) -> std::borrow::Cow<'a, Document> { + match (&item.every_artboard, r.format.id, single) { + (Some(all), "pdf", None) => std::borrow::Cow::Borrowed(&**all), + _ if r.whole_document() && item.artboard.is_some() => std::borrow::Cow::Owned(board_document(item)), + _ => std::borrow::Cow::Borrowed(&*item.doc), + } +} + +/// The document a native, `.ai` or EPS row writes for `item`'s artboard: that artboard alone, with +/// its background color and the art on it, as Save's separateArtboards writes it (#3868). +fn board_document(item: &Item) -> Document { + let mut d = single_artboard(&item.doc, item.region, &item.name); + if let (Some(a), Some(from)) = (d.artboards.first_mut(), item.doc.artboards.get(item.artboard.unwrap_or(0))) { + a.color = from.color; + } + super::save::keep_art_on(&mut d, item.region); + d +} + /// Every chosen artboard (asset, layer, selected object) in every format row, one file each (a PDF /// holds its artboard alone), or with `fullDocument` one file per row (a PDF of every artboard, /// else the bounds of all art). Items that share a name get `-2`, `-3`… instead of overwriting, and @@ -1177,6 +1199,23 @@ pub(crate) fn export(s: &mut Session, p: &Value, asked: &Value) -> Result super::check_images_in(C, r.format.id, &item.doc, base, &r.options_for(item.region, item.artboard)?)?; } } + // The native document the files of the other rows carry, each document looked through once. + if crate::file_access::current().is_some() { + let mut looked: HashSet<(usize, bool, Option)> = HashSet::new(); + for r in rows.iter().filter(|r| !matches!(r.format.id, "svg" | "svgz")) { + // A single-file PDF carries the first item's document alone, as the writer writes it. + let carried = items.iter().enumerate().filter(|(index, _)| !(single.is_some() && r.format.id == "pdf" && *index > 0)); + for (_, item) in carried.filter(|(_, i)| names_scripts(i, r, single.as_deref())) { + let all = item.every_artboard.is_some() && r.format.id == "pdf" && single.is_none(); + let board = item.artboard.filter(|_| !all && r.whole_document()); + if looked.insert((Arc::as_ptr(&item.doc) as usize, all, board)) + && crate::cmd::links::names_hidden_file(&carried_document(item, r, single.as_deref()), base) + { + return Err(bad(C, super::access::IMAGE_OUTSIDE)); + } + } + } + } // Appearance of Black › Printing / Exporting for RGB raster rows. // Include Artboard Fill off: the encoders leave the background colors out. let fill = if o.include_artboard_fill == Some(false) { json!({ "includeArtboardFill": false }) } else { json!({}) }; @@ -1318,8 +1357,9 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) -> } Ok(bytes) }; - // A whole-document copy of an artboard, for the formats that write documents to edit. - let mut board_docs: std::collections::HashMap> = std::collections::HashMap::new(); + // A whole-document copy of an artboard of an item's document, for the formats that write + // documents to edit. + let mut board_docs: std::collections::HashMap<(usize, usize), Arc> = std::collections::HashMap::new(); let mut files = 0u64; // One step per item and row, the files a name collision skips included. let steps = (items.len() * rows.len()) as u64; @@ -1358,19 +1398,7 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) -> write(pdf_doc.unwrap_or(all), "pdf", &options)? } else if r.whole_document() && item.artboard.is_some() { let b = item.artboard.unwrap_or(0); - // That artboard alone, as Save's separateArtboards writes it: its art, not the others' (#3868). - let d = board_docs - .entry(b) - .or_insert_with(|| { - let mut d = single_artboard(&item.doc, item.region, &item.name); - // It keeps its background color. - if let (Some(a), Some(from)) = (d.artboards.first_mut(), item.doc.artboards.get(b)) { - a.color = from.color; - } - super::save::keep_art_on(&mut d, item.region); - Arc::new(d) - }) - .clone(); + let d = board_docs.entry((Arc::as_ptr(&item.doc) as usize, b)).or_insert_with(|| Arc::new(board_document(item))).clone(); let mut options = r.options_for(item.region, None)?; // An EPS page is the artboard, not its art's bounds: an artboard without art still writes. if r.format.id == "eps" { diff --git a/crates/engine/src/cmd/fileio/svg.rs b/crates/engine/src/cmd/fileio/svg.rs index bcc01e37a4..066c6fc63f 100644 --- a/crates/engine/src/cmd/fileio/svg.rs +++ b/crates/engine/src/cmd/fileio/svg.rs @@ -183,13 +183,7 @@ pub(super) fn lost_artboards_warning(doc: &Document, p: &Value, label: &str) -> /// The native document Preserve Editing embeds: `doc`, without an Export for Screens `folder` /// outside the read roots of the request being served (the open document keeps it). fn native_attachment(doc: &Document) -> Vec { - let settings = super::screens::leave_out_unreadable_settings_folder(doc.export_settings.clone()); - if settings.len() == doc.export_settings.len() { - return vectorcraft_format::save(doc, false); - } - let mut kept = doc.clone(); - kept.export_settings = settings; - vectorcraft_format::save(&kept, false) + vectorcraft_format::save(&super::access::with_readable_settings_folder(doc), false) } /// Encode `doc` as SVG (or gzipped, SVGZ): one file per chosen artboard, with the images they diff --git a/crates/engine/src/cmd/fileio/tests.rs b/crates/engine/src/cmd/fileio/tests.rs index bbf6883834..f3161c229d 100644 --- a/crates/engine/src/cmd/fileio/tests.rs +++ b/crates/engine/src/cmd/fileio/tests.rs @@ -492,6 +492,19 @@ fn library_open_filters_list_library_formats_first() { } } +/// Other Library…'s Swatch Libraries filter lists the `.ai` and `.eps` documents whose swatches load +/// as a library, and it is the only filter of that label. +#[test] +fn the_swatch_library_filter_lists_ai_and_eps_files() { + let filters: Vec<_> = library_open_filters("Swatch libraries", crate::cmd::swatchlib::LIBRARY_PICK_EXTS).collect(); + for ext in ["ai", "ait", "eps", "epsf", "ase", "gpl", "acb", "vcswatches"] { + assert!(filters[0].1.contains(&ext), "{ext}: {:?}", filters[0]); + } + assert_eq!(filters.iter().filter(|f| f.0 == "Swatch libraries").count(), 1, "{filters:?}"); + // File › Open still opens a `.ai` as a document, not as a swatch library. + assert!(!crate::cmd::swatchlib::LIBRARY_EXTS.contains(&"ai") && !opens_as_other("ai")); +} + /// The extensions usage texts list for export: one per writable format, each picking that format /// (`.png` picks PNG; PNG-8 is asked for by `format`). #[test] diff --git a/crates/engine/src/cmd/fileio/tests_aiimport.rs b/crates/engine/src/cmd/fileio/tests_aiimport.rs index 9d263c8c97..3754752939 100644 --- a/crates/engine/src/cmd/fileio/tests_aiimport.rs +++ b/crates/engine/src/cmd/fileio/tests_aiimport.rs @@ -413,6 +413,114 @@ fn a_swatch_library_in_a_ai_file_without_layers_loads_its_palette() { assert!(matches!(sky, Some(vectorcraft_color::Paint::Gradient(_))), "{sky:?}"); } +/// A `.ai` swatch library (a palette and no layers) holding White, the gradient Sky and, in the +/// color group Textures, the swatch Tiles of the 4 pt pattern Dots, whose square is painted with +/// `square` (a color operator), a color the palette doesn't list. +fn textures_library(square: &str) -> Vec { + let dots = format!("%AI3_BeginPattern: (Dots)\n(Dots) 0 0 4 4\n%_{square}\n%_1 1 m\n%_3 1 L\n%_3 3 L\n%_1 3 L\n%_f\nE\n%AI3_EndPattern\n"); + let gradient = + "%AI5_BeginGradient: (Sky)\n(Sky) 0 2 Bd\n[\n%_0 0 0 0 1 1 1 2 1 6 50 0 Bs\n%_0 0 0 1 0 0 0 2 0.5 6 50 100 Bs\nBD\n%AI5_EndGradient\n"; + let palette = "%AI5_BeginPalette\n0 0 Pb\n0 0 0 0 1 1 1 Xa\n(White)\nPc\nBb\n2 (Sky) 0 0 0 1 1 0 0 1 0 0 1 Bg\n0 BB\n(Sky)\nPc\n\ + 1 (Textures) 1 Pg\n(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n(Tiles)\nPc\nPB\n%AI5_EndPalette\n"; + let data = ai::editing_data(200.0, 100.0, &format!("{dots}{gradient}{palette}")); + ai::ai(&compressed(data.as_bytes()), "1 0 0 rg 10 50 30 40 re f") +} + +/// `swatch.library.load` of `file` named `name` → its library id. +fn load_library(s: &mut Session, name: &str, file: &[u8]) -> Value { + let p = json!({"dataBase64": vectorcraft_format::base64_encode(file), "name": name}); + s.execute("swatch.library.load", &p).unwrap()["library"].clone() +} + +/// Other Library… on a `.ai` swatch library lists its colors, gradients and pattern swatches in its +/// order and color groups, and adding the pattern swatch makes a pattern swatch with the pattern's +/// tile and art in the document, in the library's color group, not the pattern's colors. +#[test] +fn a_swatch_library_in_a_ai_file_lists_and_adds_its_pattern_swatches() { + let mut s = Session::new(); + let id = load_library(&mut s, "textures.ai", &textures_library("0 0 0 1 k")); + let lib = s.execute("swatch.library.get", &json!({"library": id})).unwrap(); + let kinds: Vec<(&str, &str, Option<&str>)> = + lib["swatches"].as_array().unwrap().iter().map(|w| (w["name"].as_str().unwrap(), w["kind"].as_str().unwrap(), w["group"].as_str())).collect(); + assert_eq!(kinds, [("White", "color", None), ("Sky", "gradient", None), ("Tiles", "pattern", Some("Textures"))], "{lib}"); + assert_eq!(lib["swatches"][2]["pattern"], json!("Dots"), "{lib}"); + // The library panel draws the pattern from the file it came from; a copy of the swatch isn't its own. + let (_, library) = crate::cmd::swatchlib::library(&s, id.as_str().unwrap()).unwrap(); + let tiles = library.iter().find(|w| w.name == "Tiles").unwrap(); + assert!(crate::cmd::swatchlib::pattern_source(&s, tiles).is_some_and(|d| d.pattern("Dots").is_some())); + assert!(crate::cmd::swatchlib::pattern_source(&s, &tiles.clone()).is_none()); + + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let r = s.execute("swatch.library.add", &json!({"library": id, "names": ["Textures"]})).unwrap(); + assert_eq!(r["added"], json!(["Tiles"]), "{r}"); + let doc = &s.doc().unwrap().doc; + let dots = doc.pattern("Dots").expect("the pattern comes with its swatch"); + assert_eq!((dots.tile.width(), dots.tile.height()), (4.0, 4.0)); + assert_eq!(dots.art.len(), 1, "{:?}", dots.art); + let textures = doc.swatch_groups.iter().find(|g| g.name == "Textures").expect("the color group comes too"); + let tiles: Vec<_> = textures.swatches.iter().map(|w| (w.name.as_str(), &w.paint)).collect(); + assert!(matches!(tiles[..], [("Tiles", vectorcraft_color::Paint::Pattern { pattern, .. })] if pattern == "Dots"), "{tiles:?}"); + // Added again, the swatch the document has is used. + let again = s.execute("swatch.library.add", &json!({"library": id, "names": ["Tiles"]})).unwrap(); + assert_eq!((again["added"].clone(), again["existing"].clone()), (json!([]), json!(["Tiles"])), "{again}"); +} + +/// A pattern swatch of a `.ai` library whose pattern paints with a color the library doesn't list +/// still comes in with that color in its art. +#[test] +fn a_pattern_from_a_ai_library_keeps_a_color_the_library_lacks() { + let mut s = Session::new(); + let id = load_library(&mut s, "textures.ai", &textures_library("0 0.5 1 0 k")); + let lib = s.execute("swatch.library.get", &json!({"library": id})).unwrap(); + let names: Vec<&str> = lib["swatches"].as_array().unwrap().iter().map(|w| w["name"].as_str().unwrap()).collect(); + assert_eq!(names, ["White", "Sky", "Tiles"], "the pattern's color isn't listed: {lib}"); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("swatch.library.add", &json!({"library": id, "names": ["Tiles"]})).unwrap(); + let doc = &s.doc().unwrap().doc; + let art = &doc.pattern("Dots").unwrap().art; + let fill = art.first().and_then(|n| n.appearance.fill()).map(|f| f.paint.color()); + assert_eq!(fill, Some(Some(vectorcraft_color::Color::cmyk(0.0, 0.5, 1.0, 0.0))), "{art:?}"); + // Copy to User Defined would write a .vcswatches file, which can't hold the pattern swatch: it is + // refused, writes nothing and leaves the library loaded. + let dir = std::env::temp_dir().join(format!("vc-pattern-copy-{}", std::process::id())); + s.swatch_libraries.set_user_dir(Some(dir.to_string_lossy().to_string())); + let e = s.execute("swatch.library.copyToUser", &json!({"library": id})).unwrap_err().to_string(); + assert!(e.contains("`textures` has pattern swatches"), "{e}"); + assert!(!dir.exists() || std::fs::read_dir(&dir).unwrap().next().is_none(), "nothing written"); + assert!(s.execute("swatch.library.get", &json!({"library": id})).is_ok()); + std::fs::remove_dir_all(&dir).ok(); +} + +/// A `.ai` file without a palette of its own, and a document with no swatches, are refused as +/// swatch libraries with a message, not listed as the default swatches or as an empty library. A +/// damaged `.ai` is refused with the reader's error, and none of them is listed. A library file +/// with no swatches loads as an empty library. +#[test] +fn swatch_library_documents_without_swatches_or_damaged_are_refused() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.edit("Clear", |d, _| { + d.swatches.clear(); + d.swatch_groups.clear(); + Ok(()) + }) + .unwrap(); + let b64 = s.execute("document.serialize", &json!({})).unwrap()["dataBase64"].as_str().unwrap().to_string(); + let e = s.execute("swatch.library.load", &json!({"dataBase64": b64, "name": "Bare.vectorcraft"})).unwrap_err().to_string(); + assert!(e.contains("`Bare.vectorcraft` has no swatches of its own"), "{e}"); + let data = ai::editing_data(200.0, 100.0, &ai::layer("Art", &format!("0 0 0 1 k\n{}f\n", ai::rect(10.0, 50.0, 40.0, 90.0)))); + let p = json!({"dataBase64": vectorcraft_format::base64_encode(&ai::ai(&compressed(data.as_bytes()), "1 0 0 rg 10 50 30 40 re f")), "name": "art.ai"}); + let e = s.execute("swatch.library.load", &p).unwrap_err().to_string(); + assert!(e.contains("`art.ai` has no swatches of its own"), "{e}"); + let damaged = json!({"data": "%PDF-1.4\n%damaged\n", "name": "damaged.ai"}); + assert!(s.execute("swatch.library.load", &damaged).is_err()); + let list = s.execute("swatch.library.list", &json!({})).unwrap(); + assert!(list["libraries"].as_array().unwrap().iter().all(|l| l["category"] != "loaded"), "{list}"); + // A library file without swatches still loads, as an empty library. + let r = s.execute("swatch.library.load", &json!({"data": "GIMP Palette\nName: Empty\n#\n", "name": "Empty.gpl"})).unwrap(); + assert_eq!(r["count"], json!(0), "{r}"); +} + /// Other Library… on a `.ai` graphic style library (art styles, their list and no layers) gives the /// library the styles of its list, in the list's order, not the default styles; the file opens with /// them too. diff --git a/crates/engine/src/cmd/fileio/tests_dxf.rs b/crates/engine/src/cmd/fileio/tests_dxf.rs index 1a3368b56f..b5129d1910 100644 --- a/crates/engine/src/cmd/fileio/tests_dxf.rs +++ b/crates/engine/src/cmd/fileio/tests_dxf.rs @@ -116,6 +116,24 @@ fn use_artboards_writes_one_drawing_per_artboard() { assert!(e.contains("useArtboards"), "{e}"); } +#[test] +fn each_artboard_s_drawing_is_the_drawing_of_that_artboard_alone() { + let mut s = two_boards(); + // A second rectangle on the second artboard, so the two drawings differ. + let second = s.doc().unwrap().doc.artboards[1].rect.x0; + s.execute("shape.rectangle", &json!({"x": second + 50.0, "y": 50, "width": 20, "height": 20})).unwrap(); + let r = s.execute("document.export", &json!({"format": "dxf", "useArtboards": true, "unit": "pt"})).unwrap(); + let files = r["files"].as_array().unwrap(); + let doc = &s.doc().unwrap().doc; + let o = dxf::options(&json!({"unit": "pt"})).unwrap(); + assert_eq!(files.len(), doc.artboards.len()); + assert_ne!(b64(&files[0]), b64(&files[1])); + for (f, board) in files.iter().zip(&doc.artboards) { + let alone = vectorcraft_cad::export(doc, &vectorcraft_cad::DxfOptions { region: board.rect, crop: true, ..o.clone() }).unwrap(); + assert_eq!(b64(f), alone.bytes, "{}", f["name"]); + } +} + #[test] fn selected_only_exports_the_selection_in_its_layers() { let mut s = two_boards(); diff --git a/crates/engine/src/cmd/fileio/tests_pdfimport.rs b/crates/engine/src/cmd/fileio/tests_pdfimport.rs index 703c29fe74..63b70c48c7 100644 --- a/crates/engine/src/cmd/fileio/tests_pdfimport.rs +++ b/crates/engine/src/cmd/fileio/tests_pdfimport.rs @@ -410,3 +410,16 @@ fn a_placeholder_only_pdf_part_is_detected() { assert!(open(&mut s, &two, json!({"pages": "1"})).is_err()); open(&mut s, &two, json!({})).unwrap(); } + +/// `linkPages` takes a PDF up to the largest file placed, and nothing else. +#[test] +fn pages_can_link_a_pdf_up_to_the_largest_file_placed() { + let small = three_pages(); + assert!(pages_can_link("pages.pdf", &small)); + assert!(!pages_can_link("pages.svg", b"")); + let mut big = vec![0u8; crate::cmd::place::document::MAX_FILE + 1]; + big[..small.len()].copy_from_slice(&small); + assert!(!pages_can_link("pages.pdf", &big), "over the limit"); + big.pop(); + assert!(pages_can_link("pages.pdf", &big), "at the limit"); +} diff --git a/crates/engine/src/cmd/fileio/tests_screens.rs b/crates/engine/src/cmd/fileio/tests_screens.rs index 0f610b073f..c7c258b304 100644 --- a/crates/engine/src/cmd/fileio/tests_screens.rs +++ b/crates/engine/src/cmd/fileio/tests_screens.rs @@ -1461,3 +1461,25 @@ fn an_export_preset_adds_no_notes() { let r = export(&mut s, json!({"exportPreset": "Mixed"})); assert!(unused(&r).is_empty(), "{r}"); } + +/// Assets, layers and selected objects each write a native, `.ai` or EPS file of their own art: +/// every piece's file holds its own artboard, named after it, not the first piece's. +#[test] +fn each_piece_writes_its_own_native_document() { + let mut s = session(1); + s.execute("shape.ellipse", &json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap(); + let ids: Vec = s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id.0).collect(); + let mut assets = vec![]; + for (id, name) in ids.iter().zip(["Square", "Circle"]) { + assets.push(s.execute("assets.add", &json!({"ids": [id], "name": name})).unwrap()["assets"][0].as_u64().unwrap()); + } + let r = export(&mut s, json!({"assets": assets, "formats": [{"format": "vectorcraft"}, {"format": "eps"}]})); + let written = files(&r); + assert_eq!(written.len(), 4, "{r}"); + for (name, bytes) in written { + let native = if name.ends_with(".eps") { vectorcraft_eps::native(&bytes).expect("native document") } else { bytes }; + let doc = vectorcraft_format::load(&native).unwrap(); + let board = doc.artboards[0].name.clone(); + assert!(name.contains(&board), "{name} holds the artboard {board}"); + } +} diff --git a/crates/engine/src/cmd/globaledit.rs b/crates/engine/src/cmd/globaledit.rs index 879767d8be..29fbf97fac 100644 --- a/crates/engine/src/cmd/globaledit.rs +++ b/crates/engine/src/cmd/globaledit.rs @@ -769,6 +769,7 @@ fn give_item(a: &AppearanceItem, b: &AppearanceItem, m: &AppearanceItem, n: &mut arrow_scale, profile, brush, + brush_options, opacity, blend, visible, @@ -781,7 +782,11 @@ fn give_item(a: &AppearanceItem, b: &AppearanceItem, m: &AppearanceItem, n: &mut bearing: _, rotation: _, } = m; - give_fields!(a, b, n: paint, width, cap, join, miter_limit, align, dash, start_arrow, end_arrow, arrow_scale, profile, brush, opacity, blend, visible, effects, arrow_align, overprint, gradient_mode); + give_fields!(a, b, n: paint, width, cap, join, miter_limit, align, dash, start_arrow, end_arrow, arrow_scale, profile, brush, brush_options, opacity, blend, visible, effects, arrow_align, overprint, gradient_mode); + // A stroke's own brush settings go with the brush they set: a new brush takes the model's. + if a.brush != b.brush { + n.brush_options = brush_options.clone(); + } } _ => {} } diff --git a/crates/engine/src/cmd/graph.rs b/crates/engine/src/cmd/graph.rs index 301d361a1a..f1db9dd58a 100644 --- a/crates/engine/src/cmd/graph.rs +++ b/crates/engine/src/cmd/graph.rs @@ -37,7 +37,8 @@ use axis::{nice_axis, tick_values}; #[cfg(test)] use columns::{fill_totals, total_text}; pub use commands::specs; -pub(crate) use data::{apply_csv, parse_csv}; +pub use data::{MAX_GRAPH_DATA_FILE, graph_cell_text, graph_data_from_grid, graph_data_text, graph_grid_from_text}; +pub(crate) use data::{apply_csv, graph_csv_from_file, parse_csv}; #[cfg(test)] use data::{fmt_value, to_csv}; pub use edit::{GraphTypeSubject, graph_type_subject}; diff --git a/crates/engine/src/cmd/graph/data.rs b/crates/engine/src/cmd/graph/data.rs index 68a83fd80a..11cfd4ed26 100644 --- a/crates/engine/src/cmd/graph/data.rs +++ b/crates/engine/src/cmd/graph/data.rs @@ -91,6 +91,102 @@ pub(super) fn to_csv(g: &GraphSpec) -> String { g.to_csv() } +// ---------- graph data files ---------- + +/// The largest graph data file that Graph Data's Import Data and Import Data Sets' `%` columns +/// read, 1 MB (1,048,576 bytes). +pub const MAX_GRAPH_DATA_FILE: usize = 1 << 20; + +/// A graph data sheet's size: a row of labels over a graph's categories, a column of labels +/// before its series; a cell's longest text. +const SHEET_ROWS: usize = vectorcraft_doc::MAX_GRAPH_CATEGORIES + 1; +const SHEET_COLS: usize = vectorcraft_doc::MAX_GRAPH_SERIES + 1; +const SHEET_CELL: usize = 256; + +/// A graph data file's bytes as text: UTF-16 with its byte-order mark (spreadsheets' "Unicode +/// Text"), else UTF-16 without one when the bytes hold NUL bytes and Import Data Sets' rule gives +/// them a byte order ([`crate::cmd::utf16_order_without_mark`]), else UTF-8 with or without one. +/// UTF-16 is read as it is after a byte-order mark: an odd last byte is left out, and an unpaired +/// surrogate reads as U+FFFD. +pub fn graph_data_text(bytes: &[u8]) -> String { + let utf16 = |rest: &[u8], le: bool| { + let units: Vec = rest.as_chunks::<2>().0.iter().map(|p| if le { u16::from_le_bytes(*p) } else { u16::from_be_bytes(*p) }).collect(); + String::from_utf16_lossy(&units) + }; + match bytes { + [0xFF, 0xFE, rest @ ..] => utf16(rest, true), + [0xFE, 0xFF, rest @ ..] => utf16(rest, false), + [0xEF, 0xBB, 0xBF, rest @ ..] => String::from_utf8_lossy(rest).into_owned(), + _ => match bytes.contains(&0).then(|| crate::cmd::utf16_order_without_mark(bytes)).flatten() { + Some(le) => utf16(bytes, le), + None => String::from_utf8_lossy(bytes).into_owned(), + }, + } +} + +/// A graph data sheet cell's text: one line (tabs and line breaks become spaces), at most 256 +/// characters. +pub fn graph_cell_text(s: &str) -> String { + s.chars().map(|c| if matches!(c, '\t' | '\r' | '\n') { ' ' } else { c }).take(SHEET_CELL).collect() +} + +/// Text from a file or the clipboard as graph data sheet cells: tab-separated when any line holds +/// a tab, else comma-separated (decided once, so a label with a comma in a tab-separated file +/// stays whole), at most a graph's rows and columns. +pub fn graph_grid_from_text(text: &str) -> Vec> { + let sep = if text.contains('\t') { '\t' } else { ',' }; + text.lines().take(SHEET_ROWS).map(|l| l.trim_end_matches('\r').split(sep).take(SHEET_COLS).map(|c| graph_cell_text(c.trim())).collect()).collect() +} + +/// A graph data sheet as `graph.setData` takes it: the first row holds the series labels, the +/// first column the category labels (none when all are blank), and the other cells the values (a +/// blank cell, or text that isn't a number, has none), without the empty rows and columns past +/// the data. +pub fn graph_data_from_grid(grid: &[Vec]) -> Value { + let cell = |r: usize, c: usize| grid.get(r).and_then(|row| row.get(c)).cloned().unwrap_or_default(); + let filled = |s: &String| !s.trim().is_empty(); + // At most a graph's rows and columns, as a file gives (`graph_grid_from_text`): a grid sent by + // automation is any size, and the values are their product. + let grid = &grid[..grid.len().min(SHEET_ROWS)]; + let rows = grid.iter().rposition(|r| r.iter().take(SHEET_COLS).any(filled)).map_or(1, |i| i + 1).max(1); + let cols = grid.iter().take(rows).filter_map(|r| r.iter().take(SHEET_COLS).rposition(filled)).max().map_or(1, |i| i + 1).max(1); + let label = |s: &str| { + let s = s.trim(); + // A label typed in straight quotes (as the CSV form takes a number as a label) is the text inside. + s.strip_prefix('"').and_then(|t| t.strip_suffix('"')).unwrap_or(s).to_string() + }; + // Series labels up to the last one given (none when all are blank). + let mut series: Vec = (1..cols).map(|c| label(&cell(0, c))).collect(); + while series.last().is_some_and(String::is_empty) { + series.pop(); + } + let mut categories: Vec = (1..rows).map(|r| label(&cell(r, 0))).collect(); + if categories.iter().all(String::is_empty) { + categories.clear(); + } + let values: Vec> = (1..rows) + .map(|r| { + (1..cols) + .map(|c| { + let t = cell(r, c); + t.trim().parse::().ok().filter(|v| v.is_finite() && !t.trim().starts_with('"')).map_or(Value::Null, |v| json!(v)) + }) + .collect() + }) + .collect(); + json!({ "series": series, "categories": categories, "rows": values }) +} + +/// The graph value (the CSV form [`apply_csv`] reads) of a graph data file's bytes, read as Graph +/// Data's Import Data reads the file into its sheet and Apply sends the sheet: so applying the +/// value gives a graph the data that Import Data and Apply give it. +pub(crate) fn graph_csv_from_file(bytes: &[u8]) -> Result { + let data = graph_data_from_grid(&graph_grid_from_text(&graph_data_text(bytes))); + let mut spec = GraphSpec::default(); + apply_data(&mut spec, &data, "dataset.import")?; + Ok(spec.to_csv()) +} + /// Apply CSV graph data to the graph root `id` and rebuild its art (Variables data merge), as `graph.setData` with /// `csv` does. Data the graph already holds leaves the graph as it is. pub(crate) fn apply_csv(d: &mut Document, id: NodeId, csv: &str) -> Result<()> { @@ -149,6 +245,11 @@ pub(super) fn apply_data(g: &mut GraphSpec, p: &Value, cmd: &str) -> Result Vec { /// Inline graphics follow their symbols: after an edit of a document that has (or had) symbols, /// resolve the inline art of every text again, in the layers and in the art of symbols, graph /// designs, pattern tiles and opacity masks, and lay out again the texts whose art changed (a -/// symbol's type before the type that shows that symbol inline). -pub(crate) fn refresh(before: &Document, d: &mut Document) { +/// symbol's type before the type that shows that symbol inline). `last` is the document the last +/// refresh left resolved, with what it measured: when nothing the inline art depends on changed +/// since, only the layer trees that differ from its own are checked +/// ([`Document::resolve_inline_art_since`]). Returns what this refresh measured, or `None` when +/// neither document has symbols and nothing was checked. +pub(crate) fn refresh(last: Option<&Resolved>, before: &Document, d: &mut Document) -> Option { if before.symbols.is_empty() && d.symbols.is_empty() { - return; + return None; } - d.resolve_inline_art_with(&mut refresh_bounds); + #[cfg(test)] + let last = last.filter(|_| !FULL_PASS.get()); + let pass = d.resolve_inline_art_since(last.map(|(doc, m)| (&**doc, m)), &mut refresh_bounds); + #[cfg(test)] + PASSES.with(|p| p.borrow_mut().push((pass.partial, pass.changed.clone()))); + Some(pass.measured) +} + +/// A document a [`refresh`] left resolved, and what that refresh measured. +pub(crate) type Resolved = (std::sync::Arc, InlineMeasured); + +#[cfg(test)] +thread_local! { + /// Each [`refresh`] on this thread that checked the document: whether it checked only the + /// changed layer trees, and the ids of the texts in the layers that changed. + pub(crate) static PASSES: std::cell::RefCell)>> = const { std::cell::RefCell::new(vec![]) }; + /// Set: every [`refresh`] on this thread takes the full pass. + pub(crate) static FULL_PASS: std::cell::Cell = const { std::cell::Cell::new(false) }; } fn insert_inline(s: &mut Session, p: &Value) -> Result { @@ -47,18 +68,22 @@ fn insert_inline(s: &mut Session, p: &Value) -> Result { }; let len = edit::runs_len(&t.runs); let from_tool = editing == Some(id); - let (a, b) = match p.get("at") { - None | Some(Value::Null) if from_tool => { - let g = |k: &str| tool.get(k).and_then(Value::as_u64).map_or(len, |v| (v as usize).min(len)); - let (x, y) = (g("start"), g("end")); - (x.min(y), x.max(y)) - } - None | Some(Value::Null) => (len, len), - Some(v) => { - let at = v.as_u64().ok_or_else(|| bad(C, "`at` must be a byte offset"))?.min(len as u64) as usize; - (at, at) - } + // Where the graphic goes in text `len` bytes long. + let range = |len: usize| -> Result<(usize, usize)> { + Ok(match p.get("at") { + None | Some(Value::Null) if from_tool => { + let g = |k: &str| tool.get(k).and_then(Value::as_u64).map_or(len, |v| (v as usize).min(len)); + let (x, y) = (g("start"), g("end")); + (x.min(y), x.max(y)) + } + None | Some(Value::Null) => (len, len), + Some(v) => { + let at = v.as_u64().ok_or_else(|| bad(C, "`at` must be a byte offset"))?.min(len as u64) as usize; + (at, at) + } + }) }; + let (mut a, mut b) = range(len)?; let symbol = match str_param(p, "symbol") { Some(n) if doc.symbols.iter().any(|s| s.name == n) => n.to_string(), Some(n) => return Err(bad(C, format!("no symbol named `{n}`"))), @@ -76,11 +101,16 @@ fn insert_inline(s: &mut Session, p: &Value) -> Result { None | Some(Value::Null) => 0.0, Some(v) => v.as_f64().filter(|k| k.is_finite() && k.abs() <= 1e5).ok_or_else(|| bad(C, "`shift` must be a number of points"))?, }; - // A typing session ends first: the insertion is a step of its own. + // A typing session ends first: the insertion is a step of its own. Typing that Real-time + // Drawing off left unapplied is applied first, and the caret is read in the typed text. let typing = tool.get("typing").and_then(Value::as_bool) == Some(true); if typing && from_tool { s.set_tool_option("commitTyping", &Value::Bool(true)); - s.commit_interaction()?; + super::settle_interaction(s)?; + let NodeKind::Text(t) = &s.doc()?.doc.node(id).ok_or(EngineError::NoNode(id))?.kind else { + return Err(bad(C, format!("node {} is not text", id.0))); + }; + (a, b) = range(edit::runs_len(&t.runs))?; } let caret = s.edit("Insert Inline Symbol", |d, _| { let mut art = InlineArt { scale, baseline_shift: shift, ..InlineArt::new(symbol.clone()) }; diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 237f0f9d49..7a7f2b8e08 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -29,7 +29,7 @@ pub fn specs() -> Vec { "New Layer…", ["Window", "Layers"], Some("Cmd+L"), - "{name?, top?: bool, below?: bool, color?, template?, locked?, visible?, printable?, preview?, dimImages?} a layer directly above the current layer, at its level (a sublayer beside a current sublayer); `top`: above all layers (Ctrl/Cmd-click the button); `below`: directly below the current layer, at its level (Ctrl/Cmd+Alt-click the button), not with `top`. Options as layer.setProps; refused while an opacity mask is edited (the Layers panel lists only the mask) → {id}", + "{name?, top?: bool, below?: bool, color?, template?, locked?, visible?, printable?, preview?, dimImages?} a layer directly above the current layer, at its level (a sublayer beside a current sublayer), or directly below it in Draw Behind; `top`: above all layers (Ctrl/Cmd-click the button); `below`: directly below the current layer, at its level (Ctrl/Cmd+Alt-click the button), not with `top`. Options as layer.setProps; refused while an opacity mask is edited (the Layers panel lists only the mask) → {id}", super::maskedit::outside_mask_editing, new_layer ), @@ -110,7 +110,7 @@ pub fn specs() -> Vec { "Move Rows", [], None, - "{ids|id, target, place?: \"above\"|\"below\"|\"inside\" (default inside), copy?: bool} drag rows in the Layers panel: above or below the target row (beside it, in its layer or group), or inside a layer, group or Intertwine group (on top of its contents). Layers go only in layers or at the top level, objects in layers, groups and Intertwine groups; an object placed beside a top-level layer goes inside it. An object placed in an Intertwine group becomes a member drawn in its row's order, with no arranged areas, and one placed in a group that is a member becomes part of that member; one that is or holds an Intertwine group, a Repeat, a graph or a Live Paint group is refused. A member moved out of its Intertwine group drops its arranged areas, and a group left with one member is replaced by that member, or becomes a plain group of it when the group has an opacity, blending, appearance, mask, lock or hidden state of its own (with no member, it is removed). A row never goes into itself; a locked layer or group takes nothing. `copy` (Alt-drag) moves copies. Every selected object left hidden or locked, such as one moved into a hidden layer or group, is deselected (the key object too). One undo step → {ids}", + "{ids|id, target, place?: \"above\"|\"below\"|\"inside\" (default inside), copy?: bool} drag rows in the Layers panel: above or below the target row (beside it, in its layer or group), or inside a layer, group or Intertwine group (on top of its contents). Layers go only in layers or at the top level, objects in layers, groups and Intertwine groups; an object placed beside a top-level layer goes inside it. An object placed in an Intertwine group becomes a member drawn in its row's order, with no arranged areas, and one placed in a group that is a member becomes part of that member; one that is or holds an Intertwine group, a Repeat, a graph or a Live Paint group is refused. A member moved out of its Intertwine group drops its arranged areas, and a group left with one member is replaced by that member, or becomes a plain group of it when the group has an opacity, blending, appearance, mask, lock or hidden state of its own (with no member, it is removed). A row never goes into itself; a locked layer or group takes nothing. `copy` (Alt-drag) moves copies, which may also go above or below a row they copy (the target among `ids`). Every selected object left hidden or locked, such as one moved into a hidden layer or group, is deselected (the key object too). One undo step → {ids}", has_doc, move_rows ), @@ -526,12 +526,15 @@ fn add_layer(s: &mut Session, p: &Value, cmd: &str, label: &str, place: impl FnO fn new_layer(s: &mut Session, p: &Value) -> Result { const C: &str = "layer.new"; let below = switch_or(p, "below", false, C)?; - if below && bool_or(p, "top", false) { + let top = bool_or(p, "top", false); + if below && top { return Err(bad(C, "`top` and `below` can't both be true")); } + // In Draw Behind a layer given neither `top` nor `below` goes below the current layer. + let below = below || (!top && s.draw_mode == crate::DrawMode::Behind); let st = s.doc()?; // Above the current layer, at its level; below it with `below`; on top of everything with `top`. - let cur = st.current_layer().filter(|_| !bool_or(p, "top", false)); + let cur = st.current_layer().filter(|_| !top); add_layer(s, p, C, "New Layer", |d| match cur.and_then(|c| d.position(c)) { Some((parent, i, _)) => Ok((parent, if below { i } else { i + 1 })), None => Ok((None, if below { 0 } else { usize::MAX })), @@ -723,19 +726,18 @@ fn select_art(s: &mut Session, p: &Value) -> Result { } else { vec![id] }; - let all_selected = !ids.is_empty() && ids.iter().all(|i| st.selection.contains(*i)); + let all_selected = add && !ids.is_empty() && { + let selected: HashSet = st.selection.objects.iter().copied().collect(); + ids.iter().all(|i| selected.contains(i)) + }; let rows = st.layer_rows.clone(); s.select(|_, sel| { if !add { sel.set(ids.iter().copied()); } else if all_selected { - for i in &ids { - sel.remove(*i); - } + sel.remove_all(ids.iter().copied()); } else { - for i in &ids { - sel.add(*i); - } + sel.add_all(ids.iter().copied()); } })?; let st = s.doc_mut()?; @@ -774,9 +776,11 @@ fn move_rows(s: &mut Session, p: &Value) -> Result { if ids.is_empty() { return Err(bad(C, "no such rows")); } - // Never into itself or a row inside it. + // Never into itself or a row inside it. A copy may go above or below one of the rows it + // copies, which a move there would leave where it is (#8237). + let beside_itself = copy && place != Place::Inside && ids.contains(&target); let around = d.ancestry(target).unwrap_or_default(); - if ids.iter().any(|i| around.contains(i)) { + if ids.iter().any(|i| around.contains(i) && !(beside_itself && *i == target)) { return Err(bad(C, "a row can't go into itself")); } let nodes: Vec<&Node> = ids.iter().filter_map(|i| d.node(*i)).collect(); @@ -788,6 +792,11 @@ fn move_rows(s: &mut Session, p: &Value) -> Result { parent => (parent, Some(target)), }, }; + // A copy beside a top-level layer it copies, with objects among the rows, would go inside + // that layer: into itself. + if parent.is_some_and(|p| ids.contains(&p)) { + return Err(bad(C, "a row can't go into itself")); + } if let Some(n) = nodes.iter().find(|n| !accepts(d, parent, n)) { let into = parent.and_then(|p| d.node(p)).map_or("the top level", |p| if p.is_layer() { "a layer" } else { p.kind_label() }); return Err(bad(C, format!("{} can't go into {into}", n.display_name()))); diff --git a/crates/engine/src/cmd/layerpanel.rs b/crates/engine/src/cmd/layerpanel.rs index 95c152e959..5400e66728 100644 --- a/crates/engine/src/cmd/layerpanel.rs +++ b/crates/engine/src/cmd/layerpanel.rs @@ -132,7 +132,7 @@ pub fn specs() -> Vec { "Locate Object", ["Window", "Layers"], None, - "{id?} (default: the last selected object) highlight the object's row; the Layers panel opens the layers around it and scrolls to it → {id, ancestry: [layer…, id]}", + "{id?, layersOnly?} (default: the last selected object) highlight the object's row; the Layers panel opens the layers around it and scrolls to it, also when the row was already highlighted →{id, ancestry: [layer…, id]}. layersOnly (default false; the panel sends true while Show Layers Only is on, as Locate Layer) highlights the innermost layer or sublayer holding the object instead, or a layer id itself → {id: layer, objectId, ancestry: [layer…]}", has_doc, locate ), @@ -435,10 +435,19 @@ fn reverse(s: &mut Session, p: &Value) -> Result { fn locate(s: &mut Session, p: &Value) -> Result { let id = object_param(p, "id", "layer.locate")?; + let layers_only = switch_or(p, "layersOnly", false, "layer.locate")?; let st = s.doc_mut()?; let id = id.or_else(|| st.selection.objects.last().copied()).ok_or_else(|| bad("layer.locate", "nothing selected"))?; - let ancestry = st.doc.ancestry(id).ok_or(EngineError::NoNode(id))?; - st.layer_rows = vec![id]; + let mut ancestry = st.doc.ancestry(id).ok_or(EngineError::NoNode(id))?; + if layers_only { + // Locate Layer: the innermost layer or sublayer holding the object (a layer locates itself). + let at = ancestry.iter().rposition(|a| st.doc.node(*a).is_some_and(Node::is_layer)).ok_or(EngineError::NoNode(id))?; + ancestry.truncate(at + 1); + } + let row = ancestry.last().copied().ok_or(EngineError::NoNode(id))?; + st.layer_rows = vec![row]; + st.locate_reveal = Some(row); st.revision += 1; - Ok(json!({ "id": id.0, "ancestry": ancestry.iter().map(|i| i.0).collect::>() })) + let ancestry: Vec = ancestry.iter().map(|i| i.0).collect(); + Ok(if layers_only { json!({ "id": row.0, "objectId": id.0, "ancestry": ancestry }) } else { json!({ "id": id.0, "ancestry": ancestry }) }) } diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 81d1c72497..55c6612494 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -36,7 +36,7 @@ use vectorcraft_doc::{ use vectorcraft_geom::{Affine, FillRule, PathData, Rect, shapes}; use super::fileio::{self, RasterImage, absolute_path, file_created, file_stamp, read_file, write_file}; -use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, ids_param, object_param, str_param, switch_or}; +use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, ids_param, object_param, str_param, switch_or, text_param}; pub fn specs() -> Vec { vec![ @@ -108,7 +108,7 @@ pub fn specs() -> Vec { "Unembed", [], None, - "{id?: an embedded image (default: the one selected), path?} write the image's pixels to the file at path (PNG, JPEG, GIF or WebP as stored, other images as PNG; a path ending in .png/.jpg/.jpeg/.gif/.webp/.tif/.tiff/.bmp converts them) and link the image to it, keeping its bounds. One undo step → {id, path}; no path → {name, dataBase64} (nothing changes: there is no file to link to)", + "{id?: an embedded image (default: the one selected), path?, ids?: [image ids] (instead of id; one id is the same as id), folder?} write the image's pixels to the file at path (PNG, JPEG, GIF or WebP as stored, other images as PNG; a path ending in .png/.jpg/.jpeg/.gif/.webp/.tif/.tiff/.bmp converts them) and link the image to it, keeping its bounds. One undo step → {id, path}; no path → {name, dataBase64} (nothing changes: there is no file to link to). With folder: write each embedded image of ids or id (default: the selected embedded images) to a new file in folder, as stored (as PNG when that format is not one of VectorCraft's raster file formats), named after the image (characters a file name can't hold become _; Image when nothing is left), with Name 2 … Name 99 when the name is taken; a file already there is never replaced. Linked images among ids are left as they are. Each image links to its file and keeps its bounds. One undo step (undo does not remove the files); when a file can't be written, the files this call wrote are removed and nothing changes → {unembedded: [{id, path}], skipped: [ids of linked images]}; id with ids, path with folder, and ids of more or fewer than one image without folder are errors", has_doc, unembed ), @@ -2686,11 +2686,35 @@ fn convert_image(bytes: &[u8], ext: &str) -> std::result::Result, String craft_image_codecs::encode(&raw, format, &craft_image_codecs::EncodeOptions::default()).map_err(|e| e.to_string()) } +/// The extension of the format embedded image `blob` is stored in (PNG for one Unembed doesn't +/// name). +fn stored_extension(blob: &vectorcraft_doc::ImageBlob) -> &'static str { + fileio::FORMATS.iter().find(|f| f.raster && f.mime == blob.mime).map_or("png", |f| f.extensions.first().copied().unwrap_or("png")) +} + +/// The bytes of embedded image `blob` in the format of extension `ext`: its own bytes when it is +/// stored in that format, else converted. +fn unembed_bytes(blob: &vectorcraft_doc::ImageBlob, ext: &str) -> std::result::Result, String> { + let same = fileio::format(ext).is_some_and(|f| f.mime == blob.mime); + if same { Ok(blob.bytes.to_vec()) } else { convert_image(&blob.bytes, ext) } +} + fn unembed(s: &mut Session, p: &Value) -> Result { const C: &str = "links.unembed"; + let given = |k: &str| p.get(k).is_some_and(|v| !v.is_null()); + // `id` with `ids`, and `path` with `folder`, are refused, in a replayed step too. + super::params::check_exclusive_keys(C, p)?; + let ids = ids_param(p, "ids", C)?; + if given("folder") || ids.as_ref().is_some_and(|ids| ids.len() != 1) { + return unembed_to_folder(s, p, ids); + } let st = s.doc()?; let doc = with_brush_art(&st.doc); - let id = image_param(st, &doc, p, C)?; + // `ids` of one image is `id`. + let id = match ids.as_deref() { + Some(&[id]) => id, + _ => image_param(st, &doc, p, C)?, + }; let n = stored(&doc, id).ok_or(crate::EngineError::NoNode(id))?; let im = image_of(&doc, id).ok_or_else(|| bad(C, format!("object {} is not an image", id.0)))?; if im.link.is_some() { @@ -2698,15 +2722,14 @@ fn unembed(s: &mut Session, p: &Value) -> Result { } let blob = st.doc.images.get(&im.key).filter(|b| !b.is_proxy()).ok_or_else(|| bad(C, "the image's pixels aren't in the document"))?; // As stored (PNG, JPEG, GIF, WebP), unless the path names another format. - let stored = fileio::FORMATS.iter().find(|f| f.raster && f.mime == blob.mime).map_or("png", |f| f.extensions.first().copied().unwrap_or("png")); + let stored = stored_extension(blob); let path = str_param(p, "path"); let ext = match path.map(fileio::extension) { Some(e) if UNEMBED_EXTS.contains(&e.as_str()) => e, Some(e) if !e.is_empty() => return Err(bad(C, format!("can't write .{e} images: use .png, .jpg, .gif, .webp, .tif or .bmp"))), _ => stored.to_string(), }; - let same = fileio::format(&ext).is_some_and(|f| f.mime == blob.mime); - let bytes = if same { blob.bytes.to_vec() } else { convert_image(&blob.bytes, &ext).map_err(|e| bad(C, e))? }; + let bytes = unembed_bytes(blob, &ext).map_err(|e| bad(C, e))?; let Some(path) = path else { let name = n.display_name(); let stem = Path::new(&name).file_stem().map_or_else(|| name.clone(), |s| s.to_string_lossy().into_owned()); @@ -2722,6 +2745,146 @@ fn unembed(s: &mut Session, p: &Value) -> Result { Ok(json!({ "id": id.0, "path": path })) } +/// `links.unembed {ids?, folder}`: each embedded image of `ids` (`id` as `ids` of one; default: the +/// selected embedded images) written to a new file in `folder` as stored (as PNG when that format is not one of +/// VectorCraft's raster file formats) and linked to it, in one undo step. Linked images are skipped. When any image fails, the files written before it +/// are removed and the document does not change. +fn unembed_to_folder(s: &mut Session, p: &Value, ids: Option>) -> Result { + const C: &str = "links.unembed"; + let folder = text_param(p, "folder", C)?.filter(|f| !f.is_empty()).ok_or_else(|| bad(C, "missing `folder`"))?; + let ids = match ids { + Some(ids) => Some(ids), + None => object_param(p, "id", C)?.map(|id| vec![id]), + }; + let st = s.doc()?; + let doc = with_brush_art(&st.doc); + let ids = ids.unwrap_or_else(|| selected_images(st, |im| im.link.is_none())); + let mut seen = BTreeSet::new(); + if !ids.iter().all(|id| seen.insert(id.0)) { + return Err(bad(C, "`ids` names an object twice")); + } + let (mut embedded, mut skipped) = (vec![], vec![]); + for &id in &ids { + let n = stored(&doc, id).ok_or(crate::EngineError::NoNode(id))?; + let im = image_of(&doc, id).ok_or_else(|| bad(C, format!("object {} is not an image", id.0)))?; + if im.link.is_some() { + skipped.push(id); + continue; + } + let blob = st.doc.images.get(&im.key).filter(|b| !b.is_proxy()).ok_or_else(|| bad(C, "the image's pixels aren't in the document"))?; + embedded.push((id, n.display_name(), blob)); + } + match (embedded.is_empty(), skipped.first()) { + (true, Some(id)) => return Err(bad(C, format!("image {} is linked already", id.0))), + (true, None) => return Err(bad(C, "select an image")), + _ => {} + } + let dir = absolute_path(folder); + writable_folder(&dir)?; + // One image at a time: its bytes are read before its file is written, so pixels that can't be + // read leave no file behind. + let mut written: Vec = vec![]; + let mut reads = Vec::with_capacity(embedded.len()); + let wrote = embedded.iter().try_for_each(|(id, name, blob)| { + vectorcraft_doc::cancel::check()?; + let ext = stored_extension(blob); + let bytes = unembed_bytes(blob, ext).map_err(|e| bad(C, e))?; + let name = format!("{}.{ext}", unembed_stem(name)); + let img = linked_image(&bytes, Some(Path::new(&dir).join(&name).to_string_lossy().as_ref()))?; + let path = write_numbered(&dir, &name, &bytes)?; + written.push(path.clone()); + reads.push((*id, (link_info(&path, &bytes), img))); + Ok(()) + }); + let remove_written = |written: &[String]| { + for path in written { + let _ = std::fs::remove_file(path); + } + }; + if let Err(e) = wrote { + remove_written(&written); + return Err(e); + } + drop(doc); + let done: Vec = reads.iter().map(|(id, (l, _))| json!({ "id": id.0, "path": l.path })).collect(); + let edited = s.edit("Unembed", |d, _| { + editing_brush_art(d, |d| reads.into_iter().try_for_each(|(id, read)| install(d, &[id], read, Some(Preserve::Bounds), None))) + }); + if let Err(e) = edited { + remove_written(&written); + return Err(e); + } + Ok(json!({ "unembedded": done, "skipped": ids_json(&skipped) })) +} + +/// The name Unembed gives image `name`'s file in a folder, before its extension: the name without +/// a folder part or extension, each character a file name can't hold on some system +/// (`/ \ : * ? " < > |` and control characters) as `_`, without leading spaces or trailing dots and +/// spaces, at most 150 bytes long, and `Image` when nothing is left. A name Windows keeps for a +/// device (`CON`, `NUL`, `COM1` …) gets `_` after it. +fn unembed_stem(name: &str) -> String { + let base = name.rsplit(['/', '\\']).next().unwrap_or_default(); + let stem = match base.rfind('.') { + Some(i) if i > 0 => &base[..i], + _ => base, + }; + let mut clean = String::new(); + for c in stem.chars().map(|c| if c.is_control() || "/\\:*?\"<>|".contains(c) { '_' } else { c }) { + if clean.len() + c.len_utf8() > 150 { + break; + } + clean.push(c); + } + let clean = clean.trim_start_matches(' ').trim_end_matches(['.', ' ']); + if clean.is_empty() { + return "Image".to_string(); + } + let device = clean.split('.').next().unwrap_or_default().trim_end().to_ascii_uppercase(); + let numbered = |prefix: &str| device.strip_prefix(prefix).is_some_and(|d| d.len() == 1 && matches!(d.as_bytes().first(), Some(b'1'..=b'9'))); + if matches!(device.as_str(), "CON" | "PRN" | "AUX" | "NUL") || numbered("COM") || numbered("LPT") { + format!("{clean}_") + } else { + clean.to_string() + } +} + +/// Folder `path` may take Unembed's files: inside the automation write roots, and a folder. +#[cfg(not(target_arch = "wasm32"))] +fn writable_folder(path: &str) -> Result<()> { + crate::file_access::check_write(path).map_err(EngineError::Other)?; + if !std::fs::metadata(path).is_ok_and(|m| m.is_dir()) { + return Err(EngineError::Other(format!("{path} is not a folder"))); + } + Ok(()) +} + +/// Write `bytes` to a new file named `name` in folder `dir`, never replacing a file there: `Name.ext`, +/// else `Name 2.ext` up to `Name 99.ext`, as [`fileio::copy_new`] names them → its path. +#[cfg(not(target_arch = "wasm32"))] +fn write_numbered(dir: &str, name: &str, bytes: &[u8]) -> Result { + use std::io::Write as _; + let create = |to: &Path| { + crate::file_access::check_write(&to.to_string_lossy()).map_err(|e| std::io::Error::new(std::io::ErrorKind::PermissionDenied, e))?; + vectorcraft_format::write_new_with(to, |f| f.write_all(bytes)) + }; + match fileio::copy_new(Path::new(name), Path::new(dir), create, |_, _| false) { + Ok(Some(fileio::Placed::Copied(to) | fileio::Placed::Kept(to))) => Ok(to.to_string_lossy().into_owned()), + Ok(None) => Err(EngineError::Other(format!("every numbered name for {name} is taken in that folder"))), + Err(e) => Err(EngineError::Other(format!("{dir}: {e}"))), + } +} + +/// The web has no folders to write to. +#[cfg(target_arch = "wasm32")] +fn writable_folder(_: &str) -> Result<()> { + Err(EngineError::Other("no file system here".into())) +} + +#[cfg(target_arch = "wasm32")] +fn write_numbered(_: &str, _: &str, _: &[u8]) -> Result { + Err(EngineError::Other("no file system here".into())) +} + /// Placement Options as `{preserve, align, clip}`. fn placement_json(o: PlacementOptions) -> Value { json!({ "preserve": o.preserve.id(), "align": o.align.id(), "clip": o.clip }) @@ -2901,4 +3064,28 @@ mod tests { let c = read(); assert!(!Arc::ptr_eq(&a.blob.bytes, &c.blob.bytes)); } + + #[test] + fn unembed_names_a_file_after_the_image_with_only_characters_a_file_name_holds() { + for (name, stem) in [ + ("photo.png", "photo"), + ("Image", "Image"), + ("../../etc/passwd", "passwd"), + ("C:\\art\\logo.tif", "logo"), + ("a:b*c?d\"eg|h", "a_b_c_d_e_f_g_h"), + ("tab\there", "tab_here"), + (" name. .png", "name"), + ("..", "Image"), + ("", "Image"), + (".hidden", ".hidden"), + ("CON.png", "CON_"), + ("lpt1", "lpt1_"), + ("COM0", "COM0"), + ("console", "console"), + ] { + assert_eq!(unembed_stem(name), stem, "{name:?}"); + } + let long = unembed_stem(&"é".repeat(200)); + assert!(long.len() <= 150 && long.chars().all(|c| c == 'é'), "{}", long.len()); + } } diff --git a/crates/engine/src/cmd/live.rs b/crates/engine/src/cmd/live.rs index 618865cede..1d23d07792 100644 --- a/crates/engine/src/cmd/live.rs +++ b/crates/engine/src/cmd/live.rs @@ -29,6 +29,8 @@ mod commands; mod common; mod envelope; mod mesh; +#[cfg(test)] +mod selected_tests; pub(crate) use blend::expand_blends; pub use commands::specs; diff --git a/crates/engine/src/cmd/live/blend.rs b/crates/engine/src/cmd/live/blend.rs index 5334311789..a2cb0e3f91 100644 --- a/crates/engine/src/cmd/live/blend.rs +++ b/crates/engine/src/cmd/live/blend.rs @@ -657,9 +657,8 @@ pub(super) fn blend_replace_spine(s: &mut Session, _: &Value) -> Result { } /// Is any selected blend one made without a spine? -fn any_without_spine(s: &Session) -> bool { - let Ok(st) = s.doc() else { return false }; - selected_of(s, is_blend).iter().any(|b| matches!(st.doc.node(*b).map(|n| &n.kind), Some(NodeKind::Blend { spec, .. }) if spec.no_spine)) +pub(super) fn any_without_spine(s: &Session) -> bool { + super::common::any_selected_of(s, is_blend, |n| matches!(&n.kind, NodeKind::Blend { spec, .. } if spec.no_spine)) } pub(super) fn blend_reverse_spine(s: &mut Session, _: &Value) -> Result { diff --git a/crates/engine/src/cmd/live/common.rs b/crates/engine/src/cmd/live/common.rs index cfa3f32076..661d574b58 100644 --- a/crates/engine/src/cmd/live/common.rs +++ b/crates/engine/src/cmd/live/common.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use super::mesh::whole; use super::{ Arc, BlendEase, BlendEaseType, BlendOrientation, BlendSpacing, Document, EngineError, Node, NodeId, NodeKind, Result, Selection, Session, Value, @@ -20,13 +22,14 @@ pub(super) fn roots_param(s: &Session, p: &Value) -> Result> { let mut sel = Selection::default(); sel.set(ids.iter().copied().filter(|id| st.doc.node(*id).is_some_and(|n| !n.is_layer()))); let ordered = sel.in_paint_order(&st.doc); + let given: HashSet = ordered.iter().copied().collect(); // Drop ids nested inside other given ids. return Ok(ordered .iter() .copied() .filter(|id| { let anc = st.doc.ancestry(*id).unwrap_or_default(); - !anc[..anc.len().saturating_sub(1)].iter().any(|a| ordered.contains(a)) + !anc[..anc.len().saturating_sub(1)].iter().any(|a| given.contains(a)) }) .collect()); } @@ -37,20 +40,27 @@ pub(super) fn roots_param(s: &Session, p: &Value) -> Result> { /// dynamic symbol instance's art is selected. pub(super) fn selected_of(s: &Session, pred: fn(&Node) -> bool) -> Vec { let Some(st) = s.active().filter(|st| st.selection.symbol_part.is_none()) else { return vec![] }; + let mut find = st.doc.nearest_finder(); + let mut seen = HashSet::new(); let mut out = vec![]; for id in &st.selection.objects { - for a in st.doc.ancestry(*id).unwrap_or_default().into_iter().rev() { - if st.doc.node(a).is_some_and(pred) { - if !out.contains(&a) { - out.push(a); - } - break; - } + if let Some(n) = find.nearest(*id, pred) + && seen.insert(n.id) + { + out.push(n.id); } } out } +/// Whether some selected object's node of a kind ([`selected_of`]) passes `test`; stops at the +/// first one that does. +pub(super) fn any_selected_of(s: &Session, pred: fn(&Node) -> bool, test: impl Fn(&Node) -> bool) -> bool { + let Some(st) = s.active().filter(|st| st.selection.symbol_part.is_none()) else { return false }; + let mut find = st.doc.nearest_finder(); + st.selection.objects.iter().any(|id| find.nearest(*id, pred).is_some_and(&test)) +} + pub(super) fn is_blend(n: &Node) -> bool { matches!(n.kind, NodeKind::Blend { .. }) } @@ -66,19 +76,19 @@ pub(super) fn is_mesh(n: &Node) -> bool { pub(super) fn has_blend(s: &Session) -> std::result::Result<(), String> { has_selection(s)?; crate::cmd::edit::no_symbol_part(s)?; - if selected_of(s, is_blend).is_empty() { Err("select a blend".into()) } else { Ok(()) } + if any_selected_of(s, is_blend, |_| true) { Ok(()) } else { Err("select a blend".into()) } } pub(super) fn has_envelope(s: &Session) -> std::result::Result<(), String> { has_selection(s)?; crate::cmd::edit::no_symbol_part(s)?; - if selected_of(s, is_envelope).is_empty() { Err("select an envelope".into()) } else { Ok(()) } + if any_selected_of(s, is_envelope, |_| true) { Ok(()) } else { Err("select an envelope".into()) } } pub(super) fn has_mesh(s: &Session) -> std::result::Result<(), String> { has_selection(s)?; crate::cmd::edit::no_symbol_part(s)?; - if selected_of(s, is_mesh).is_empty() { Err("select a gradient mesh".into()) } else { Ok(()) } + if any_selected_of(s, is_mesh, |_| true) { Ok(()) } else { Err("select a gradient mesh".into()) } } /// Wrap `roots` (paint order) into a new node built by `make`, placed where the topmost root was. diff --git a/crates/engine/src/cmd/live/selected_tests.rs b/crates/engine/src/cmd/live/selected_tests.rs new file mode 100644 index 0000000000..b1250e2560 --- /dev/null +++ b/crates/engine/src/cmd/live/selected_tests.rs @@ -0,0 +1,324 @@ +//! The selected blend, envelope and mesh ([`selected_of`] and the checks built on it) are the ones +//! the lookup of every ancestor by id found: the same ids in the same order, the same availability +//! and errors, on selections with keys, nested blends, stale and repeated ids and a damaged tree. + +use std::sync::atomic::{AtomicUsize, Ordering}; + +use serde_json::json; +use vectorcraft_doc::{Node, NodeId, NodeKind, SymbolPart}; + +use super::Session; +use super::blend::any_without_spine; +use super::common::{any_selected_of, has_blend, has_envelope, has_mesh, is_blend, is_envelope, is_mesh, selected_of}; + +/// [`selected_of`] as each ancestor was looked up by id: `ancestry`, then `node` for each id from +/// the object up, repeats dropped by a scan of the list. +fn selected_of_by_ids(s: &Session, pred: fn(&Node) -> bool) -> Vec { + let Some(st) = s.active().filter(|st| st.selection.symbol_part.is_none()) else { return vec![] }; + let mut out = vec![]; + for id in &st.selection.objects { + for a in st.doc.ancestry(*id).unwrap_or_default().into_iter().rev() { + if st.doc.node(a).is_some_and(pred) { + if !out.contains(&a) { + out.push(a); + } + break; + } + } + } + out +} + +/// The availability [`has_blend`] and the others gave, from [`selected_of_by_ids`]. +fn has_by_ids(s: &Session, pred: fn(&Node) -> bool, msg: &str) -> std::result::Result<(), String> { + super::has_selection(s)?; + crate::cmd::edit::no_symbol_part(s)?; + if selected_of_by_ids(s, pred).is_empty() { Err(msg.into()) } else { Ok(()) } +} + +/// The no-spine check [`any_without_spine`] made, from [`selected_of_by_ids`]. +fn without_spine_by_ids(s: &Session) -> bool { + let Ok(st) = s.doc() else { return false }; + selected_of_by_ids(s, is_blend).iter().any(|b| matches!(st.doc.node(*b).map(|n| &n.kind), Some(NodeKind::Blend { spec, .. }) if spec.no_spine)) +} + +/// Every check on the current selection gives what the lookups by id gave. +fn agree(s: &Session, what: &str) { + type Has = fn(&Session) -> std::result::Result<(), String>; + for (name, pred, has, msg) in [ + ("blend", is_blend as fn(&Node) -> bool, has_blend as Has, "select a blend"), + ("envelope", is_envelope, has_envelope, "select an envelope"), + ("mesh", is_mesh, has_mesh, "select a gradient mesh"), + ] { + let want = selected_of_by_ids(s, pred); + assert_eq!(selected_of(s, pred), want, "{what}: selected {name}s"); + assert_eq!(any_selected_of(s, pred, |_| true), !want.is_empty(), "{what}: any {name}"); + assert_eq!(has(s), has_by_ids(s, pred, msg), "{what}: has {name}"); + } + assert_eq!(any_without_spine(s), without_spine_by_ids(s), "{what}: a blend without a spine"); +} + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + s +} + +fn id_of(v: &serde_json::Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap()) +} + +fn rect(s: &mut Session, x: f64) -> NodeId { + id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 20, "height": 20})).unwrap()) +} + +fn select(s: &mut Session, ids: &[NodeId]) { + s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); +} + +fn run(s: &mut Session, cmd: &str, ids: &[NodeId], p: serde_json::Value) -> NodeId { + select(s, ids); + id_of(&s.execute(cmd, &p).unwrap()) +} + +/// Every node id under the layers, parents before children (as Direct Selection can pick them). +fn all_ids(s: &Session) -> Vec { + fn walk(nodes: &[std::sync::Arc], out: &mut Vec) { + for n in nodes { + out.push(n.id); + if let Some(ch) = n.children() { + walk(ch, out); + } + } + } + let mut out = vec![]; + for l in &s.doc().unwrap().doc.layers { + walk(l.children().map_or(&[][..], |c| c.as_slice()), &mut out); + } + out +} + +/// The active document, to change in place. +fn doc_mut(s: &mut Session) -> &mut vectorcraft_doc::Document { + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc) +} + +/// Set the selection's objects as given, stale and repeated ids included. +fn set_objects(s: &mut Session, ids: Vec) { + s.doc_mut().unwrap().selection.objects = ids; +} + +/// Two blends, a blend in a key group of a third, an envelope and a mesh; one blend has no spine. +/// Returns the blends `a`, `b` and `c`, the group `g` of `c` that holds `a`, the envelope, and a key +/// of `a`. +fn document() -> (Session, [NodeId; 6]) { + let mut s = session(); + let r: Vec = (0..10).map(|i| rect(&mut s, 40.0 * i as f64)).collect(); + let a = run(&mut s, "object.blend.make", &[r[0], r[1]], json!({})); + let b = run(&mut s, "object.blend.make", &[r[2], r[3]], json!({})); + let g = run(&mut s, "object.group", &[a, r[4]], json!({})); + let c = run(&mut s, "object.blend.make", &[g, r[5]], json!({})); + let e = run(&mut s, "object.envelope.makeWithWarp", &[r[6]], json!({"style": "arch", "bend": 50})); + select(&mut s, &[r[7]]); + s.execute("object.mesh.create", &json!({"ids": [r[7].0], "rows": 1, "cols": 1})).unwrap(); + if let Some(NodeKind::Blend { spec, .. }) = doc_mut(&mut s).node_mut(b).map(|n| &mut n.kind) { + spec.no_spine = true; + } + (s, [a, b, c, g, e, r[0]]) +} + +#[test] +fn selected_blends_envelopes_and_meshes_match_the_lookups_by_id() { + let (mut s, [a, b, c, g, e, inner_key]) = document(); + s.execute("select.all", &json!({})).unwrap(); + agree(&s, "select all"); + let all = all_ids(&s); + let keys: Vec = all.iter().copied().filter(|id| ![a, b, c, g, e].contains(id)).collect(); + set_objects(&mut s, keys.clone()); + agree(&s, "keys, as Direct Selection picks them"); + set_objects(&mut s, all.iter().rev().copied().collect()); + agree(&s, "every node, children first"); + set_objects(&mut s, vec![a, keys[0], b, keys[1], keys[0], NodeId(999_999), a]); + agree(&s, "repeated and stale ids, in first-seen order"); + assert_eq!(selected_of(&s, is_blend), vec![a, b], "the blend with no spine is listed once, in order"); + set_objects(&mut s, vec![NodeId(999_999)]); + agree(&s, "only a stale id"); + set_objects(&mut s, vec![]); + agree(&s, "nothing"); + // A blend in another blend's key group: the inner one. + set_objects(&mut s, vec![inner_key]); + agree(&s, "a key of a blend nested in another's key group"); + assert_eq!(selected_of(&s, is_blend), vec![a]); + // An object of a dynamic symbol instance's art: nothing. + set_objects(&mut s, all.clone()); + s.doc_mut().unwrap().selection.symbol_part = Some(SymbolPart { instance: a, path: vec![0] }); + agree(&s, "a symbol part"); + assert!(selected_of(&s, is_blend).is_empty()); +} + +/// A damaged tree: an earlier node of another kind with the id of a blend on the selected key's +/// path. `node` gives the earlier node, so that blend does not count, before and after the cache is +/// built again. +#[test] +fn a_repeated_id_counts_as_its_first_node() { + let (mut s, [a, _, c, _, _, inner_key]) = document(); + let all = all_ids(&s); + s.doc().unwrap().doc.node(a); + let doc = doc_mut(&mut s); + if let Some(ch) = std::sync::Arc::make_mut(&mut doc.layers[0]).children_mut() { + ch.insert(0, std::sync::Arc::new(Node::group(a, vec![]))); + } + set_objects(&mut s, all.clone()); + agree(&s, "a repeated id, the cache older than the tree"); + s.doc().unwrap().doc.drop_lookup_cache(); + agree(&s, "a repeated id, no cache"); + s.doc().unwrap().doc.node(a); + agree(&s, "a repeated id, cached afresh"); + set_objects(&mut s, vec![inner_key]); + assert_eq!(selected_of(&s, is_blend), vec![c], "the nested blend's id is the group's, so the outer blend counts"); +} + +/// Large selections: with the lookup cache built, finding the selected blends looks no id up, and +/// the checks stop at the first selected object that has one. +#[test] +fn selected_blends_take_no_lookups_by_id() { + let mut s = session(); + let mut keys = vec![]; + for i in 0..300 { + let (x, y) = (rect(&mut s, i as f64), rect(&mut s, i as f64 + 30.0)); + run(&mut s, "object.blend.make", &[x, y], json!({})); + keys.extend([x, y]); + } + for i in 0..1_000 { + rect(&mut s, i as f64); + } + s.execute("select.all", &json!({})).unwrap(); + s.doc().unwrap().doc.drop_lookup_cache(); + s.doc().unwrap().doc.node(keys[0]); + let before = vectorcraft_doc::path_lookups(); + assert_eq!(selected_of(&s, is_blend).len(), 300); + assert!(!any_selected_of(&s, is_mesh, |_| true)); + set_objects(&mut s, keys.clone()); + assert_eq!(selected_of(&s, is_blend).len(), 300, "each blend once from its two keys"); + assert_eq!(vectorcraft_doc::path_lookups() - before, 0, "lookups by id"); + // The first key is in a blend: the check tests that key and its blend only. + static TESTED: AtomicUsize = AtomicUsize::new(0); + fn counted(n: &Node) -> bool { + TESTED.fetch_add(1, Ordering::Relaxed); + is_blend(n) + } + assert!(any_selected_of(&s, counted, |_| true)); + assert_eq!(TESTED.load(Ordering::Relaxed), 2, "nodes tested"); +} + +/// `n` and everything under it with new ids. +fn renumber(d: &mut vectorcraft_doc::Document, n: &Node) -> Node { + let mut n = n.clone(); + n.id = d.alloc_id(); + if let Some(ch) = n.children_mut() { + for c in ch.iter_mut() { + *c = std::sync::Arc::new(renumber(d, c)); + } + } + n +} + +/// This thread's CPU time in nanoseconds, where the system reports it (Linux). +fn cpu_ns() -> Option { + std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok() +} + +/// Milliseconds one call of `f` takes over `calls` calls, in CPU time where the system reports it, +/// otherwise in wall-clock time. +fn ms_per_call(calls: u32, f: &dyn Fn()) -> f64 { + let (cpu, wall) = (cpu_ns(), std::time::Instant::now()); + for _ in 0..calls { + f(); + } + let ms = match (cpu, cpu_ns()) { + (Some(a), Some(b)) => b.saturating_sub(a) as f64 / 1e6, + _ => wall.elapsed().as_secs_f64() * 1e3, + }; + ms / f64::from(calls) +} + +/// The medians of 7 runs of `a` and of `b`, the runs taking turns. +fn medians(calls: u32, a: &dyn Fn(), b: &dyn Fn()) -> (f64, f64) { + let (mut ta, mut tb) = (vec![], vec![]); + for _ in 0..7 { + ta.push(ms_per_call(calls, a)); + tb.push(ms_per_call(calls, b)); + } + ta.sort_by(f64::total_cmp); + tb.sort_by(f64::total_cmp); + (ta[3], tb[3]) +} + +/// Timings of the lookups by id and of the one-path lookup on 100,000 rectangles in 10 layers, +/// 2,000 two-key blends (every fourth one in a group) and 200 envelopes, all selected. Run with +/// `cargo test --release -p vectorcraft-engine --lib selected_tests::timing -- --ignored --nocapture`. +#[test] +#[ignore = "timing; run by hand"] +fn timing_of_the_selected_blend_checks() { + let mut s = session(); + let (a, b, c) = (rect(&mut s, 0.0), rect(&mut s, 40.0), rect(&mut s, 80.0)); + let square = rect(&mut s, 120.0); + let blend = run(&mut s, "object.blend.make", &[a, b], json!({})); + let envelope = run(&mut s, "object.envelope.makeWithWarp", &[c], json!({"style": "arch", "bend": 50})); + let doc = doc_mut(&mut s); + let templates: Vec = [square, blend, envelope].iter().map(|id| doc.node(*id).cloned().unwrap()).collect(); + let mut layers = vec![]; + for l in 0..10 { + let mut layer = Node::layer(doc.alloc_id(), &format!("Layer {l}"), vectorcraft_doc::LayerColor::Preset(0)); + let mut kids = vec![]; + for _ in 0..10_000 { + kids.push(std::sync::Arc::new(renumber(doc, &templates[0]))); + } + for i in 0..200 { + let b = renumber(doc, &templates[1]); + let b = if i % 4 == 0 { Node::group(doc.alloc_id(), vec![std::sync::Arc::new(b)]) } else { b }; + kids.push(std::sync::Arc::new(b)); + } + for _ in 0..20 { + kids.push(std::sync::Arc::new(renumber(doc, &templates[2]))); + } + if let Some(ch) = layer.children_mut() { + *ch = kids; + } + layers.push(std::sync::Arc::new(layer)); + } + doc.layers = layers; + s.execute("select.all", &json!({})).unwrap(); + let first = s.doc().unwrap().selection.objects[0]; + s.doc().unwrap().doc.drop_lookup_cache(); + s.doc().unwrap().doc.node(first); + println!("{} objects selected", s.doc().unwrap().selection.objects.len()); + type Check = fn(&Session) -> bool; + let checks: [(&str, Check, Check); 5] = [ + ("has_blend", |s| has_by_ids(s, is_blend, "").is_ok(), |s| has_blend(s).is_ok()), + ("has_envelope", |s| has_by_ids(s, is_envelope, "").is_ok(), |s| has_envelope(s).is_ok()), + ("has_mesh", |s| has_by_ids(s, is_mesh, "").is_ok(), |s| has_mesh(s).is_ok()), + ( + "selected blends (object.blend.info and the Blend commands)", + |s| !selected_of_by_ids(s, is_blend).is_empty(), + |s| !selected_of(s, is_blend).is_empty(), + ), + ("a blend without a spine (Reverse Spine, the Blend panel)", without_spine_by_ids, any_without_spine), + ]; + assert_eq!(selected_of(&s, is_blend), selected_of_by_ids(&s, is_blend)); + println!("| Check | Lookups by id (ms) | One path (ms) |"); + println!("|---|---:|---:|"); + for (name, by_ids, one_path) in checks { + assert_eq!(by_ids(&s), one_path(&s), "{name}"); + let (old, new) = medians( + 15, + &|| { + std::hint::black_box(by_ids(&s)); + }, + &|| { + std::hint::black_box(one_path(&s)); + }, + ); + println!("| {name} | {old:.3} | {new:.3} |"); + } +} diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index 2a073ab62a..defc405514 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -1,6 +1,6 @@ //! Object menu long tail: Lock/Hide All Artwork Above & Other Layers, Transform Each, Reset -//! Bounding Box, Rasterize, Crop Image, Mask (an image), Create Trim Marks, Convert to Shape and -//! Artboards → Convert / Rearrange. (Live blends are in `live.rs`.) +//! Bounding Box, Rotate Bounding Box, Rasterize, Crop Image, Mask (an image), Create Trim Marks, +//! Convert to Shape and Artboards → Convert / Rearrange. (Live blends are in `live.rs`.) use std::collections::{BTreeMap, BTreeSet, HashSet}; use std::sync::Arc; @@ -15,8 +15,8 @@ use vectorcraft_render::encode::{RasterExportOptions, RasterFormat}; use super::edit::{duplicate_in, selected_roots, selected_roots_to_transform}; use super::{ - CommandSpec, EngineError, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, fileio, find_command, has_doc, has_selected_member, - has_selection, switch_or, + CommandSpec, EngineError, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, f64_req, fileio, find_command, has_doc, + has_selected_member, has_selection, switch_or, }; /// Session-level (not saved) state owned by the menu commands. @@ -110,6 +110,15 @@ pub fn specs() -> Vec { has_selection, reset_bounding_box ), + cmd!( + "object.rotateBoundingBox", + "Rotate Bounding Box…", + ["Object", "Transform"], + None, + "{angle: degrees (counter-clockwise), absolute?: bool (true: turn the box to angle; default false: turn it by angle from the angle the selected objects share, 0 when theirs differ)} turn the bounding box of the selected objects to one angle without moving their art; the objects inside them (the children of groups, compound paths, clip groups, blends, envelopes, repeats and intertwines, and the art of linked opacity masks) turn with them and keep their angle relative to them; a path of a compound path selected on its own turns only its own box; one undo step, none when every box is already at the angle; object.resetBoundingBox squares the boxes again; a missing or non-numeric angle is an error → {angle: the new angle of the boxes, in (-180, 180], changed: objects whose box turned, the objects inside the selected ones included}", + has_selection, + rotate_bounding_box + ), cmd!( "object.rasterize", "Rasterize…", @@ -225,9 +234,10 @@ pub(crate) fn squash(s: &mut Session, from: usize, label: &str) { // ---------- Reset Bounding Box ---------- /// Squares each selected object and every object inside it: the children of groups, compound paths, -/// clip groups, blends, envelopes, repeats and intertwines, and the art of linked opacity masks. +/// clip groups, blends, envelopes, repeats and intertwines, and the art of linked opacity masks. A +/// path of a compound path selected on its own is squared alone, as the transforms move it alone. fn reset_bounding_box(s: &mut Session, _: &Value) -> Result { - let ids = selected_roots(s)?; + let ids = selected_roots_to_transform(s)?; let d = &s.doc()?.doc; let mut changed = 0; let squared: Vec<(NodeId, Node)> = ids @@ -251,6 +261,69 @@ fn reset_bounding_box(s: &mut Session, _: &Value) -> Result { Ok(json!({ "changed": changed })) } +// ---------- Rotate Bounding Box ---------- + +/// Turns the bounding box of the selected objects to one angle without moving their art: by `angle` +/// from the angle they share (0 when it differs), or to `angle` with `absolute`. Each object's box +/// turns by what takes it there, and so do the boxes of the objects inside it (the children of +/// groups and the art of linked opacity masks), which keep their angle relative to it. +fn rotate_bounding_box(s: &mut Session, p: &Value) -> Result { + const C: &str = "object.rotateBoundingBox"; + // A JSON number is always finite. + let angle = f64_req(p, "angle", C)?; + let absolute = switch_or(p, "absolute", false, C)?; + // The same objects the transforms move: a path of a compound path selected on its own turns + // its own box. Layers are left out, as they have no box. + let owners = selected_roots_to_transform(s)?; + let d = &s.doc()?.doc; + let start = if absolute { 0.0 } else { d.bbox_angle(&owners) }; + // An angle within the tolerance of 0 is stored as 0, as `Node::turn_boxes` stores it. + let target = match vectorcraft_geom::normalize_deg(start + angle) { + a if a.abs() <= BOX_EPS_DEG => 0.0, + a => a, + }; + let mut changed = 0; + let turned: Vec<(NodeId, Node)> = owners + .iter() + .filter_map(|id| { + let n = d.node(*id)?; + let by = vectorcraft_geom::normalize_deg(target - n.bbox_angle); + (by.abs() > BOX_EPS_DEG).then(|| { + let mut c = n.clone(); + c.turn_boxes(by); + // The selected object's box is set to the target itself, so repeated turns add no + // rounding error to it. + c.bbox_angle = target; + changed += boxes(&c); + (*id, c) + }) + }) + .collect(); + if !turned.is_empty() { + s.edit("Rotate Bounding Box", |d, _| { + for (id, n) in turned { + if let Some(slot) = d.node_mut(id) { + *slot = n; + } + } + Ok(()) + })?; + } + Ok(json!({ "angle": target, "changed": changed })) +} + +/// Angles closer than this (degrees) are the same, as `vectorcraft_doc::orient` compares them. +const BOX_EPS_DEG: f64 = 1e-6; + +/// The number of objects in `n`'s subtree whose box [`Node::turn_boxes`] turns: `n`, its children +/// and the art of a linked opacity mask, layers left out. +fn boxes(n: &Node) -> usize { + let own = usize::from(!n.is_layer()); + let children: usize = n.children().into_iter().flatten().map(|c| boxes(c)).sum(); + let mask = n.extras().mask.as_ref().filter(|m| m.linked).map_or(0, |m| boxes(&m.art)); + own + children + mask +} + /// A copy of `n` with the angle of every object in its subtree set to 0, or `None` when no box in /// it stands at an angle, and the number of objects squared. The subtree takes in children and the /// art of linked opacity masks (an unlinked mask's art turns on its own); layers have no box. Only diff --git a/crates/engine/src/cmd/newart.rs b/crates/engine/src/cmd/newart.rs index ce8029e71b..84812dad97 100644 --- a/crates/engine/src/cmd/newart.rs +++ b/crates/engine/src/cmd/newart.rs @@ -7,12 +7,16 @@ //! panel's New Art Has Basic Appearance off, the whole appearance of the last selection. With the //! option on (the default) an inherited appearance gives new art its top stroke's options only, //! and a change of selection loads only the proxies. `paint.default` resets it. +//! +//! A document whose Default Graphic Style no longer has the shipped look (a New Document profile +//! redefined it) gives the reset that style's fills, strokes and effects instead, and `file.new` +//! resets new art when it opens such a document. use std::borrow::Cow; use serde_json::{Value, json}; use vectorcraft_color::{BlendMode, Paint}; -use vectorcraft_doc::{Appearance, AppearanceItem, FillLayer, GraphicStyle, Node, NodeKind, StrokeLayer}; +use vectorcraft_doc::{Appearance, AppearanceItem, ColorMode, DEFAULT_GRAPHIC_STYLE, Document, FillLayer, GraphicStyle, Node, NodeKind, StrokeLayer}; use vectorcraft_tools::PaintDefaults; use super::gradient::unplaced; @@ -263,7 +267,35 @@ fn describe(s: &mut Session, _: &Value) -> Result { })) } -/// The defaults for new art reset (`paint.default`): white fill, 1 pt black stroke, no template. +/// The defaults for new art reset (`paint.default`): white fill, 1 pt black stroke, no template; +/// in a document whose Default Graphic Style was redefined, that style's fills, strokes and effects +/// at full opacity, not linked to the style. pub(crate) fn reset(s: &mut Session) { s.paint = PaintDefaults::default(); + let style = s.doc().ok().and_then(|st| redefined_default_style(&st.doc)).cloned(); + if let Some(g) = style { + let ap = if g.unit_box { g.appearance } else { unplace_all(g.appearance) }; + s.take_new_art(ap, 1.0, BlendMode::Normal, None, false); + } +} + +/// `d`'s Default Graphic Style when its fills, strokes, effects or transparency differ from the +/// shipped style's (white fill, 1 pt black stroke), the shipped colors converted to `d`'s color mode +/// as a New Document profile's are. +pub(crate) fn redefined_default_style(d: &Document) -> Option<&GraphicStyle> { + let g = d.graphic_styles.iter().find(|g| g.name == DEFAULT_GRAPHIC_STYLE)?; + let same = + |o: &GraphicStyle| (&o.appearance, o.opacity, o.blend, o.isolate, o.knockout) == (&g.appearance, g.opacity, g.blend, g.isolate, g.knockout); + if same(&GraphicStyle::new(DEFAULT_GRAPHIC_STYLE, Appearance::default_art())) { + return None; + } + if d.color_mode != ColorMode::Rgb { + let mut shipped = Document::new_with_mode(1.0, 1.0, ColorMode::Rgb); + shipped.graphic_styles.retain(|o| o.name == DEFAULT_GRAPHIC_STYLE); + super::colormgmt::set_color_mode(&mut shipped, d.color_mode, true, None, super::colormgmt::Grays::Profile); + if shipped.graphic_styles.first().is_some_and(same) { + return None; + } + } + Some(g) } diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index 2a8d074617..e74a570a5b 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -814,6 +814,10 @@ pub(crate) fn file_new(s: &mut Session, p: &Value) -> Result { // The profile's links keep their relative paths, which name places from the profile's file, as // a new document from a history state keeps its source's. s.doc_mut()?.links_from = links_from; + // A profile whose Default Graphic Style was redefined gives new art in the document that style. + if super::newart::redefined_default_style(&s.doc()?.doc).is_some() { + super::newart::reset(s); + } // Overprint Preview is the engine's (the UI turns Pixel Preview on from `previewMode`). Both // are views of the whole app, so Default leaves them as they are. if settings.preview_mode == PreviewMode::Overprint { diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index a58f206c84..fd0aece164 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -42,3 +42,4 @@ pub(crate) use pixelgrid::{ }; pub(super) use shape::recut; pub(crate) use transform::{apply_transform, preview_copies, scaling, transform_node, transform_patterns, transforms_objects}; +pub use transform::{reflect_axis, scale_factors, shear_tangent}; diff --git a/crates/engine/src/cmd/object/arrange.rs b/crates/engine/src/cmd/object/arrange.rs index 17568d50b9..ff0b22b31b 100644 --- a/crates/engine/src/cmd/object/arrange.rs +++ b/crates/engine/src/cmd/object/arrange.rs @@ -384,6 +384,11 @@ fn add_drawn_live_paint(s: &mut Session, isolated: NodeId, next: Option) } pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result { + let key = "all"; + let all = match p.get(key) { + None => false, + Some(v) => v.as_bool().ok_or_else(|| bad("object.exitIsolation", format!("`{key}` must be true or false")))?, + }; // Opacity mask editing, pattern editing and symbol editing isolate their editing layer. Leaving // isolation mode then leaves that mode, as Stop Editing Opacity Mask and the isolation bar's // Done do. A group isolated inside the symbol's art goes back to the symbol's layer. @@ -419,12 +424,18 @@ pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result { return ok(); } let menu = s.menu.clone(); - let prev = s.active().and_then(|d| d.isolation); + let prev = st.isolation; + // An isolated sublayer goes up to its parent layer, which stays isolated, unless `all` is true or + // that layer is hidden or locked; anything else leaves isolation mode. + let up = prev + .filter(|i| !all && st.doc.node(*i).is_some_and(Node::is_layer)) + .and_then(|i| st.doc.parent_of(i)) + .filter(|parent| st.doc.is_editable(*parent)); if let Some(i) = prev { crate::cmd::settle_interaction(s)?; - let left = add_drawn_live_paint(s, i, None)?.unwrap_or(i); + let left = add_drawn_live_paint(s, i, up)?.unwrap_or(i); let st = s.doc_mut()?; - st.isolation = None; + st.isolation = up; crate::cmd::distortcmds::finish_edit_text(st, i); let target = st.doc.parent_of(left).filter(|p| st.doc.node(*p).is_some_and(|n| n.extras().shaper.is_some())).unwrap_or(left); st.selection.set([target]); diff --git a/crates/engine/src/cmd/object/bounds.rs b/crates/engine/src/cmd/object/bounds.rs index cf0473f353..a24e71c9a6 100644 --- a/crates/engine/src/cmd/object/bounds.rs +++ b/crates/engine/src/cmd/object/bounds.rs @@ -59,7 +59,7 @@ fn bounds_transform(s: &Session, p: &Value, ids: Vec, least: f64, anchor let refi = reference_index(p)?; let st = s.doc()?; check_switches(p, &TRANSFORM_SWITCHES, "object.setBounds")?; - check_switches(p, &["proportional"], "object.setBounds")?; + check_switches(p, &["proportional", "interpolate"], "object.setBounds")?; let how = s.bounds_measure(); if anchors && transforms_objects(p) diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index 0c638ceb5e..4be83d7da6 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -16,7 +16,7 @@ pub fn specs() -> Vec { "Transform", [], None, - "{matrix: [a,b,c,d,e,f], copy?: bool, ids?, strokes?: bool, corners?: bool, typeAreas?: bool, anchors?: bool, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), releaseOutside?: bool} apply an affine to the selection (or ids); anchors (without ids or copy): paths with anchors selected with Direct Selection have only those anchors and their handles transformed, as the Transform tools and object.move/rotate/scale/reflect/shear do (default: the whole objects); strokes/corners: Scale Strokes & Effects / Scale Corners (default: the preferences); typeAreas: area type among them (not type inside a group) reshapes its frame by the matrix and its text reflows at its size, as a bounding-box handle drag does (default: the type transforms too); releaseOutside (without copy or anchors): a Shaper Group's original shape that ends wholly outside the bounds the group's original shapes had before takes shaper.releaseSource in the same undo step, named Remove from Shaper Group, as the Selection tool's moves in Construction mode do", + "{matrix: [a,b,c,d,e,f], copy?: bool, ids?, strokes?: bool, corners?: bool, typeAreas?: bool, anchors?: bool, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), releaseOutside?: bool, interpolate?: bool (with anchors and a matrix that only moves them: the handles of each segment with one moved end are re-mapped, as path.moveAnchors's; default: prefs interpolateControlPoints)} apply an affine to the selection (or ids); anchors (without ids or copy): paths with anchors selected with Direct Selection have only those anchors and their handles transformed, as the Transform tools and object.move/rotate/scale/reflect/shear do (default: the whole objects); strokes/corners: Scale Strokes & Effects / Scale Corners (default: the preferences); typeAreas: area type among them (not type inside a group) reshapes its frame by the matrix and its text reflows at its size, as a bounding-box handle drag does (default: the type transforms too); releaseOutside (without copy or anchors): a Shaper Group's original shape that ends wholly outside the bounds the group's original shapes had before takes shaper.releaseSource in the same undo step, named Remove from Shaper Group, as the Selection tool's moves in Construction mode do", has_doc, transform ), @@ -25,7 +25,7 @@ pub fn specs() -> Vec { "Move…", ["Object", "Transform"], Some("Cmd+Shift+M"), - "{ids?: [id…] (selected first; default: the selection), dx, dy, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.", + "{ids?: [id…] (selected first; default: the selection), dx, dy, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), interpolate?: bool (as path.moveAnchors's; default: prefs interpolateControlPoints)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.", has_selection_or_guides, move_cmd ), @@ -61,7 +61,7 @@ pub fn specs() -> Vec { "Shear…", ["Object", "Transform"], None, - "{ids?: [id…] (selected first; default: the selection), angle: deg (positive turns the vertical edges clockwise with the horizontal axis, the top to the right; the horizontal edges clockwise with the vertical axis, the right side down), axis?: \"horizontal\"|\"vertical\", origin?, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.", + "{ids?: [id…] (selected first; default: the selection), angle: deg (-359 to 359, sheared by its tangent, so 120 slants as -60; 0 and ±180 have no slant and, without copy, change nothing; ±90 and ±270 are an error; positive turns the vertical edges clockwise with the horizontal axis, the top to the right; the horizontal edges clockwise with the vertical axis, the right side down), axis?: \"horizontal\"|\"vertical\"|deg (the line the art slides along, counter-clockwise from horizontal on the page, -359 to 359; 0: horizontal, 90: vertical; omitted: horizontal), origin?, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.", has_selection, shear ), @@ -70,7 +70,7 @@ pub fn specs() -> Vec { "Transform Again", ["Object", "Transform"], Some("Cmd+D"), - "{copy?, strokes?, corners?, patterns?, typeAreas?: bool (as object.transform's; default: the value the transform it repeats used, else object.transform's default)} the last transform's matrix on the selection (after a perspective move or scale: that plane-space transform, without these params)", + "{copy?, strokes?, corners?, patterns?, typeAreas?, interpolate?: bool (as object.transform's; default: the value the transform it repeats used, else object.transform's default)} the last transform's matrix on the selection (after a perspective move or scale: that plane-space transform, without these params)", has_selection, transform_again ), @@ -79,7 +79,7 @@ pub fn specs() -> Vec { "Nudge", [], None, - "{dx: -1|0|1, dy: -1|0|1, big?: bool (×10), copy?: bool, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move)} arrow-key nudge by the keyboard increment (the selected anchors, else objects, along the x and y axes turned by the constrainAngle preference; else ruler guides, along the page axes)", + "{dx: -1|0|1, dy: -1|0|1, big?: bool (×10), copy?: bool, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move), interpolate?: bool (as path.moveAnchors's; default: prefs interpolateControlPoints)} arrow-key nudge by the keyboard increment (the selected anchors, else objects, along the x and y axes turned by the constrainAngle preference; else ruler guides, along the page axes)", has_selection_or_guides, nudge ), @@ -250,7 +250,7 @@ pub fn specs() -> Vec { "Exit Isolation Mode", [], None, - "{} leave isolation mode; leaving an isolated Live Paint group adds the paths, compound paths and groups of them drawn in it (shown and unlocked with everything in them) to the group as livePaint.merge does, in one undo step, and leaves type, images and other objects in it as they are; object.isolate on a level outside the group does the same", + "{all?: bool (default false)} leave isolation mode; from an isolated sublayer, go up one level to its parent layer instead (the next call goes up again), unless all is true or the parent layer is hidden or locked; no undo step for the move up; while a symbol is edited, a group isolated in its art goes back to the symbol's layer first, with or without all; leaving an isolated Live Paint group adds the paths, compound paths and groups of them drawn in it (shown and unlocked with everything in them) to the group as livePaint.merge does, in one undo step, and leaves type, images and other objects in it as they are; object.isolate on a level outside the group does the same", has_doc, exit_isolation ), @@ -295,7 +295,7 @@ pub fn specs() -> Vec { "Set Bounds", [], None, - "{x?, y?, width?, height?, reference?: whole number >= 0 (9-point grid 0..8; 0.0 equals 0; a whole number past 8 is read as 8; omitted/null: center, 4), proportional?, strokes?, corners?, copy?: bool, patterns?: bool (Transform Patterns), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move)} (Transform panel; width/height and the reference point follow the bounding box, rotated with rotated objects; x, y are page coordinates; with Use Preview Bounds the values measure the visual bounds; with the typeGlyphBounds preference, each point type object selected as an object (not inside a selected group) is measured by its glyphs' ink (underline and strikethrough included), which the scale gives the size asked for; strokes/corners as object.scale; with anchor points selected (Direct Selection) and no copy, the values are the box around those points, square to the page, and only they move or scale, as with object.move (#1824))", + "{x?, y?, width?, height?, reference?: whole number >= 0 (9-point grid 0..8; 0.0 equals 0; a whole number past 8 is read as 8; omitted/null: center, 4), proportional?, strokes?, corners?, copy?: bool, patterns?: bool (Transform Patterns), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move), interpolate?: bool (with anchor points selected and only x or y changed: as path.moveAnchors's; default: prefs interpolateControlPoints)} (Transform panel; width/height and the reference point follow the bounding box, rotated with rotated objects; x, y are page coordinates; with Use Preview Bounds the values measure the visual bounds; with the typeGlyphBounds preference, each point type object selected as an object (not inside a selected group) is measured by its glyphs' ink (underline and strikethrough included), which the scale gives the size asked for; strokes/corners as object.scale; with anchor points selected (Direct Selection) and no copy, the values are the box around those points, square to the page, and only they move or scale, as with object.move (#1824))", has_selection, set_bounds ), @@ -305,7 +305,7 @@ pub fn specs() -> Vec { "Live Shape Properties", [], None, - "{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding, as in the reference app: store radii as fractions of each corner's maximum so they scale with the shape), corners?: [i…], items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse)} (Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius)", + "{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding, as in the reference app: store radii as fractions of each corner's maximum so they scale with the shape), corners?: [i…], items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint)} (Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)", has_selection, set_live_shape ), diff --git a/crates/engine/src/cmd/object/shape.rs b/crates/engine/src/cmd/object/shape.rs index b30959de99..02edf6193b 100644 --- a/crates/engine/src/cmd/object/shape.rs +++ b/crates/engine/src/cmd/object/shape.rs @@ -6,6 +6,7 @@ use super::{ BTreeSet, CornerKind, EngineError, LiveCorners, LiveShape, NodeId, NodeKind, Result, Session, Value, bad, check_numbers, check_switches, convert_radii_relative, ok, selected_roots, set_corners, targets, }; +use crate::MAX_COORD; /// The largest scale of 0 or more at which `spans`, with the margins that scale grown by `k`, /// reach across `size` together. Returns 1 when their geometric boxes reach 1e-9 or less across @@ -98,8 +99,32 @@ fn corners_param(p: &Value) -> Result>> { list.iter().map(|k| k.as_u64().and_then(|k| usize::try_from(k).ok()).ok_or_else(err)).collect::>().map(Some) } +/// Live line `l` with Line Length `len` (its first end stays) and then Line Angle `angle` (about +/// its midpoint; a line whose ends meet has none to turn), or None when neither changes it. +fn line_edit(l: &LiveShape, len: Option, angle: Option) -> Option { + let now = l.line_length()?; + let mut new = l.clone(); + let mut changed = false; + if let Some(len) = len + && (len - now).abs() > 1e-9 * len.max(now) + { + new.set_line_length(len); + changed = true; + } + if let Some(a) = angle + && new.line_length().is_some_and(|n| n > 0.0) + && let Some(turn) = new.line_angle().map(|now| (a - now).rem_euclid(360.0)) + && turn > 1e-9 + && turn < 360.0 - 1e-9 + { + new.set_line_angle(a); + changed = true; + } + (changed && new != *l).then_some(new) +} + pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { - check_switches(p, &["invertPie", "makeSidesEqual", "relativeRadii"], "object.setLiveShape")?; + check_switches(p, &["constrainPie", "invertPie", "makeSidesEqual", "relativeRadii"], "object.setLiveShape")?; check_numbers(p, &["radius", "sides"], "object.setLiveShape")?; // `items`: objects each with its own `corners`; else `ids` (or the selection) sharing them. let items = match p.get("items").filter(|v| !v.is_null()) { @@ -148,7 +173,7 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { } }; let angle = |k: &str| Ok::<_, EngineError>(number(k, |_| true, "an angle in degrees")?.map(|a| a.rem_euclid(360.0))); - let length = |k: &str| number(k, |x| x > 0.0 && x <= crate::MAX_COORD, "a length in points above 0"); + let length = |k: &str| number(k, |x| x > 0.0 && x <= MAX_COORD, "a length in points above 0"); // Saved steps ([`Session::replay`]) can hold values a direct call refuses, recorded before these // checks: a negative radius is 0, a whole side count of 0 or more is brought into 3 to 1000, and // a fractional or negative one is ignored. A whole number written as 5.0 counts as 5, as in a @@ -168,21 +193,58 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { // An ellipse's pie (Ellipse Properties: Pie Start and End Angle, degrees; Invert Pie swaps them). let (pie_start, pie_end) = (angle("pieStart")?, angle("pieEnd")?); let invert = p.get("invertPie").and_then(Value::as_bool) == Some(true); + // Constrain Pie Angle: the one angle given moves the other by as much, so each ellipse keeps + // its span (its end angle less its start angle, counterclockwise). + let constrain = p.get("constrainPie").and_then(Value::as_bool) == Some(true); + if constrain && (invert || pie_start.is_some() == pie_end.is_some()) { + return Err(bad("object.setLiveShape", "`constrainPie` needs one of `pieStart` and `pieEnd`, without `invertPie`")); + } // A polygon's Polygon Properties: its angle, radius or side length, Make Sides Equal. let (polygon_angle, polygon_radius, side) = (angle("polygonAngle")?, length("polygonRadius")?, length("sideLength")?); let equal = p.get("makeSidesEqual").and_then(Value::as_bool) == Some(true); + // A line's Line Properties: its length (its first end stays) and its angle (about its midpoint). + // A line's length can reach across the whole canvas, past `MAX_COORD`: its ends are checked below. + let line_length = number("lineLength", |x| x > 0.0, "a length in points above 0")?; + let line_angle = angle("lineAngle")?; // An ellipse's pie becomes `pie_of(pie)`. An end of 0 is a full turn (Illustrator shows a whole // ellipse as 0° to 360°). let end_of = |a: f64| if a == 0.0 { 360.0 } else { a }; let pie_of = |pie: (f64, f64)| { - let pie = (pie_start.unwrap_or(pie.0), pie_end.map_or(pie.1, end_of)); + let span = (pie.1 - pie.0).rem_euclid(360.0); + let pie = match (constrain, pie_start, pie_end) { + // The angle it already has: nothing moves. + (true, Some(a), _) if a == pie.0 => pie, + (true, _, Some(a)) if end_of(a) == pie.1 => pie, + // A whole ellipse (a span of 0) stays whole. + (true, Some(a), _) => (a, end_of((a + span).rem_euclid(360.0))), + (true, _, Some(a)) => ((a - span).rem_euclid(360.0), end_of(a)), + _ => (pie_start.unwrap_or(pie.0), pie_end.map_or(pie.1, end_of)), + }; if invert { (pie.1.rem_euclid(360.0), end_of(pie.0)) } else { pie } }; // When every value given is the current one, the document and its undo history stay as they // are. let st = s.doc()?; + // The lines that Line Length or Line Angle changes, as they become. A line that would reach + // past the document's coordinate limit is an error before anything changes. + let mut lines = std::collections::BTreeMap::new(); + if line_length.is_some() || line_angle.is_some() { + for id in &ids { + let Some(NodeKind::Path { live: Some(l), .. }) = st.doc.node(*id).map(|n| &n.kind) else { continue }; + if let Some(new) = line_edit(l, line_length, line_angle) { + let LiveShape::Line { a, b } = &new else { continue }; + if ![a.x, a.y, b.x, b.y].iter().all(|c| c.abs() <= MAX_COORD) { + return Err(bad("object.setLiveShape", format!("coordinate out of range (limit ±{MAX_COORD} pt)"))); + } + lines.insert(*id, new); + } + } + } let has_values = |id: &NodeId| { let Some(NodeKind::Path { path, live, .. }) = st.doc.node(*id).map(|n| &n.kind) else { return true }; + if lines.contains_key(id) { + return false; + } match live.as_deref() { Some(l @ LiveShape::Polygon { sides: now, .. }) if !(sides.is_none_or(|n| n.clamp(3, 1000) == u64::from(*now)) @@ -244,6 +306,12 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { } *path = l.to_path(); } + if let Some(new) = lines.get(id) + && let Some(l) = live.as_deref_mut() + { + *l = new.clone(); + *path = l.to_path(); + } if let Some(on) = relative_radii && let Some(l) = live.as_deref_mut() { diff --git a/crates/engine/src/cmd/object/transform.rs b/crates/engine/src/cmd/object/transform.rs index 25a831622e..7b1a97b4b3 100644 --- a/crates/engine/src/cmd/object/transform.rs +++ b/crates/engine/src/cmd/object/transform.rs @@ -125,9 +125,14 @@ fn apply_transform_moving_guides( let d = &s.doc()?.doc; let paths = d.index_paths(ids.iter().copied()); let none = paths.is_empty() && !has_guides; + // A move of direct-selected anchors may re-map the handles beside them (`interpolate`). + let mut interpolate = None; let ids = if anchors && objects && !copy && !s.doc()?.selection.anchors.is_empty() { + if c[..4] == [1.0, 0.0, 0.0, 1.0] { + interpolate = Some(crate::cmd::path::interpolates_handles(s, p, label)?); + } if xf != Affine::IDENTITY { - crate::cmd::path::transform_anchors(s, label, xf, sc)?; + crate::cmd::path::transform_anchors(s, label, xf, sc, interpolate.unwrap_or(false))?; } ids } else if none || (!copy && xf == Affine::IDENTITY) { @@ -195,6 +200,9 @@ fn apply_transform_moving_guides( options["strokes"] = json!(sc.strokes); options["corners"] = json!(!sc.keep_corners); } + if let Some(on) = interpolate { + options["interpolate"] = json!(on); + } st.last_transform = Some(LastTransform::Matrix(xf, options)); st.last_perspective = None; } @@ -248,7 +256,7 @@ fn resize_type_area(n: &mut Node, xf: Affine) -> bool { pub(super) fn transform(s: &mut Session, p: &Value) -> Result { check_switches(p, &TRANSFORM_SWITCHES, "object.transform")?; - check_switches(p, &["anchors", "releaseOutside"], "object.transform")?; + check_switches(p, &["anchors", "releaseOutside", "interpolate"], "object.transform")?; let m = matrix_param(p, "matrix").ok_or_else(|| bad("object.transform", "missing matrix [a,b,c,d,e,f]"))?; // An object selected in a symbol instance's art stays where the symbol puts it: the selection // is left as it is, and the reply's warning goes to the status bar. @@ -292,6 +300,7 @@ pub(super) fn transform(s: &mut Session, p: &Value) -> Result { pub(super) fn move_cmd(s: &mut Session, p: &Value) -> Result { check_numbers(p, &["dx", "dy"], "object.move")?; check_switches(p, &TRANSFORM_SWITCHES, "object.move")?; + check_switches(p, &["interpolate"], "object.move")?; let ids = selected_roots_to_transform(s)?; apply_transform(s, "Move", ids, Affine::translate((f64_or(p, "dx", 0.0), f64_or(p, "dy", 0.0))), p, true) } @@ -311,7 +320,7 @@ pub(crate) fn along_constrain_angle(dx: f64, dy: f64, deg: f64) -> (f64, f64) { pub(super) fn nudge(s: &mut Session, p: &Value) -> Result { check_numbers(p, &["dx", "dy"], "object.nudge")?; check_switches(p, &TRANSFORM_SWITCHES, "object.nudge")?; - check_switches(p, &["big"], "object.nudge")?; + check_switches(p, &["big", "interpolate"], "object.nudge")?; let k = s.prefs.keyboard_increment * if bool_or(p, "big", false) { 10.0 } else { 1.0 }; let (dx, dy) = (f64_or(p, "dx", 0.0) * k, f64_or(p, "dy", 0.0) * k); // Guides keep to the page's axes; art and anchors move along the constrain angle's. @@ -322,7 +331,7 @@ pub(super) fn nudge(s: &mut Session, p: &Value) -> Result { if dx == 0.0 && dy == 0.0 { return ok(); } - return crate::cmd::path::move_anchors(s, &json!({ "dx": dx, "dy": dy, "patterns": p.get("patterns") })); + return crate::cmd::path::move_anchors(s, &json!({ "dx": dx, "dy": dy, "patterns": p.get("patterns"), "interpolate": p.get("interpolate") })); } if s.doc()?.selection.is_empty() { let copy = bool_or(p, "copy", false); @@ -360,15 +369,22 @@ pub(super) fn scale(s: &mut Session, p: &Value) -> Result { check_switches(p, &TRANSFORM_SWITCHES, "object.scale")?; let ids = selected_roots_to_transform(s)?; let o = origin_of(s, p, &ids)?; - let sx = f64_req(p, "sx", "object.scale")? / 100.0; - let sy = f64_or(p, "sy", sx * 100.0) / 100.0; - if sx == 0.0 || sy == 0.0 { - return Err(bad("object.scale", "scale must be non-zero")); - } + let sx = f64_req(p, "sx", "object.scale")?; + let (sx, sy) = scale_factors(sx, f64_or(p, "sy", sx)).map_err(|e| bad("object.scale", e))?; let frame = basis_frame(s, p, "object.scale", &ids)?; apply_transform(s, "Scale", ids, about(o, frame.conjugate(Affine::scale_non_uniform(sx, sy))), p, true) } +/// The factors `object.scale` applies for `sx` and `sy` in percent, or the error it returns when +/// either factor is 0. +pub fn scale_factors(sx: f64, sy: f64) -> std::result::Result<(f64, f64), String> { + let (sx, sy) = (sx / 100.0, sy / 100.0); + if sx == 0.0 || sy == 0.0 { + return Err("scale must be non-zero".into()); + } + Ok((sx, sy)) +} + /// The frame that `object.scale` and a named `object.reflect` act in, from the `basis` param: /// `"box"` (the default) is the bounding box of `ids`, turned with rotated objects until Reset /// Bounding Box ([`Document::bbox_angle`]); `"page"` is the page's axes. Anchors selected with @@ -393,16 +409,7 @@ pub(super) fn reflect(s: &mut Session, p: &Value) -> Result { let ids = selected_roots_to_transform(s)?; let o = origin_of(s, p, &ids)?; // A named axis is the bounding box's own (see [`basis_frame`]); an angle is a line on the page. - let named = match p.get("axis") { - Some(Value::String(a)) if a == "horizontal" => Some(Affine::scale_non_uniform(1.0, -1.0)), - Some(Value::Number(_)) => None, - None | Some(Value::Null) => Some(Affine::scale_non_uniform(-1.0, 1.0)), - Some(Value::String(a)) if a == "vertical" => Some(Affine::scale_non_uniform(-1.0, 1.0)), - Some(v) => { - let given = v.as_str().map_or_else(|| v.to_string(), str::to_string); - return Err(bad("object.reflect", format!("axis must be \"vertical\", \"horizontal\" or an angle in degrees, not `{given}`"))); - } - }; + let named = reflect_axis(p.get("axis")).map_err(|e| bad("object.reflect", e))?; let m = match named { Some(m) => basis_frame(s, p, "object.reflect", &ids)?.conjugate(m), None => { @@ -414,22 +421,76 @@ pub(super) fn reflect(s: &mut Session, p: &Value) -> Result { apply_transform(s, "Reflect", ids, about(o, m), p, true) } +/// The reflection `object.reflect` applies for its `axis` param: the matrix for a named axis +/// (`"vertical"`, the default, or `"horizontal"`), in the bounding box's frame; `None` for an angle, +/// which is a line on the page; or the error for any other value. +pub fn reflect_axis(axis: Option<&Value>) -> std::result::Result, String> { + match axis { + Some(Value::String(a)) if a == "horizontal" => Ok(Some(Affine::scale_non_uniform(1.0, -1.0))), + Some(Value::Number(_)) => Ok(None), + None | Some(Value::Null) => Ok(Some(Affine::scale_non_uniform(-1.0, 1.0))), + Some(Value::String(a)) if a == "vertical" => Ok(Some(Affine::scale_non_uniform(-1.0, 1.0))), + Some(v) => { + let given = v.as_str().map_or_else(|| v.to_string(), str::to_string); + Err(format!("axis must be \"vertical\", \"horizontal\" or an angle in degrees, not `{given}`")) + } + } +} + +/// Angles closer than this many degrees to ±90 or ±270, or to 0 or ±180, count as those angles. It +/// is far above the rounding error of an angle up to 359° and below any angle a field shows. +const SHEAR_ANGLE_TOLERANCE: f64 = 1e-9; + +/// The slant `object.shear` applies for `angle` in degrees: its tangent, and 0 for 0 and ±180. An +/// angle outside -359 to 359, or ±90 or ±270, is an error. +pub fn shear_tangent(angle: f64) -> std::result::Result { + if !(-359.0..=359.0).contains(&angle) { + return Err(format!("`angle` must be from -359 to 359 degrees, not {angle}")); + } + // ±90 and ±270 slant an edge onto the shear axis: their tangent is unbounded. + let flat = angle.rem_euclid(180.0); + if (flat - 90.0).abs() < SHEAR_ANGLE_TOLERANCE { + return Err(format!("`angle` cannot be {angle}: ±90 and ±270 degrees have no shear")); + } + // 0 and ±180 have no slant, but the tangent of ±180° in radians is about 1e-16, not 0. + Ok(if flat < SHEAR_ANGLE_TOLERANCE || 180.0 - flat < SHEAR_ANGLE_TOLERANCE { 0.0 } else { angle.to_radians().tan() }) +} + pub(super) fn shear(s: &mut Session, p: &Value) -> Result { check_numbers(p, &["angle"], "object.shear")?; check_switches(p, &TRANSFORM_SWITCHES, "object.shear")?; + let t = shear_tangent(f64_or(p, "angle", 0.0)).map_err(|e| bad("object.shear", e))?; let ids = selected_roots_to_transform(s)?; let o = origin_of(s, p, &ids)?; - let t = f64_or(p, "angle", 0.0).clamp(-89.0, 89.0).to_radians().tan(); - let vertical = choice(p, "object.shear", "axis", &["horizontal", "vertical"])? == Some("vertical"); - let m = if vertical { Affine::new([1.0, t, 0.0, 1.0, 0.0, 0.0]) } else { Affine::new([1.0, 0.0, -t, 1.0, 0.0, 0.0]) }; + let horizontal = Affine::new([1.0, 0.0, -t, 1.0, 0.0, 0.0]); + // A named axis, or a line on the page at an angle in degrees, counter-clockwise from horizontal. + let m = match p.get("axis") { + None | Some(Value::Null) => horizontal, + Some(Value::String(a)) if a == "horizontal" => horizontal, + Some(Value::String(a)) if a == "vertical" => Affine::new([1.0, t, 0.0, 1.0, 0.0, 0.0]), + Some(Value::Number(n)) if n.as_f64().is_some_and(|a| (-SHEAR_AXIS_MAX..=SHEAR_AXIS_MAX).contains(&a)) => { + // y is down, so the page's counter-clockwise angle turns the other way on screen. + let r = -n.as_f64().unwrap_or(0.0).to_radians(); + Affine::rotate(r) * horizontal * Affine::rotate(-r) + } + Some(v) => { + let given = v.as_str().map_or_else(|| v.to_string(), str::to_string); + let range = format!("from -{SHEAR_AXIS_MAX} to {SHEAR_AXIS_MAX}"); + return Err(bad("object.shear", format!("axis must be \"horizontal\", \"vertical\" or an angle in degrees {range}, not `{given}`"))); + } + }; apply_transform(s, "Shear", ids, about(o, m), p, true) } +/// The largest angle, either way from horizontal, of the axis `object.shear` takes in degrees. +const SHEAR_AXIS_MAX: f64 = 359.0; + /// The last transform on the selection, with the options `last_transform` keeps for it; an option /// that `p` sets to true or false (a recorded Transform Again's) takes precedence. A Transform /// Each is repeated by running it again (its transform is per object, about each one's bounds). pub(super) fn transform_again(s: &mut Session, p: &Value) -> Result { check_switches(p, &TRANSFORM_SWITCHES, "object.transformAgain")?; + check_switches(p, &["interpolate"], "object.transformAgain")?; if let Some(again) = s.doc()?.last_perspective.clone() { return crate::cmd::distortcmds::transform_again(s, &again); } diff --git a/crates/engine/src/cmd/package.rs b/crates/engine/src/cmd/package.rs index cb22ac160d..e959f126c0 100644 --- a/crates/engine/src/cmd/package.rs +++ b/crates/engine/src/cmd/package.rs @@ -24,7 +24,7 @@ pub fn specs() -> Vec { "Package", [], None, - "{folder?, name?: (default: \" Folder\"), copyLinks?: true, linksFolder?: true (the linked files go in Links/, else next to the document), relink?: true (the packaged document links to the copies), copyFonts?: true (the fonts its type uses go in Fonts/; fonts whose licence doesn't allow embedding are left out), report?: true ( Report.txt)} copy the saved document as it is now into folder/name as .vectorcraft with its linked files and fonts; the open document doesn't change → {folder, files: [paths relative to folder/name], links, fonts (counts copied), missingLinks: [file names not found], skippedFonts: [{font, reason}], warnings: [nested files copied unchanged or cycles/depth stopped]}; no folder → the same with {name: \".zip\", dataBase64} (a zip of the files in /) instead of folder. The warnings and the report name a file outside the automation read roots by its file name. Under automation read roots, the package is refused, before any file is written, while the document, or a linked native document or a linked PDF, .ai or EPS file's native document, links a JavaScript file outside them (svgInteractivity; a URL is not checked)", + "{folder?, name?: (default: \" Folder\"), copyLinks?: true, linksFolder?: true (the linked files go in Links/, else next to the document), relink?: true (the packaged document links to the copies), copyFonts?: true (the fonts its type uses go in Fonts/; fonts whose licence doesn't allow embedding are left out), report?: true ( Report.txt)} copy the saved document as it is now into folder/name as .vectorcraft with its linked files and fonts; the open document doesn't change → {folder, files: [paths relative to folder/name], links, fonts (counts copied), missingLinks: [file names not found], skippedFonts: [{font, reason}], warnings: [nested files copied unchanged or cycles/depth stopped]}; no folder → the same with {name: \".zip\", dataBase64} (a zip of the files in /) instead of folder. The warnings and the report name a file outside the automation read roots by its file name. Under automation read roots, the package is refused, before any file is written, while the document, or a linked native document or a linked PDF, .ai or EPS file's native document, links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while a linked native document, or a linked PDF, .ai or EPS file that carries one, can't be read to check it (a damaged file, or a PDF that needs a password to open); a PDF or EPS file without editing data is copied", has_doc, package )] @@ -113,27 +113,86 @@ thread_local! { pub(crate) static PARTS_READ: std::cell::Cell = const { std::cell::Cell::new(0) }; } -/// The native document that the linked file `name` (`bytes`) is, or carries as the editing data of -/// a PDF, `.ai` or EPS file; `None` for other files and for data that can't be read. -fn carried_document(name: &str, bytes: &[u8]) -> Option { - if super::place::document::is_native(name, bytes) { - return vectorcraft_format::load_file(bytes).ok().map(|f| f.doc); - } - let data = - if super::place::document::is_pdf(name, bytes) { vectorcraft_pdf::editing(bytes).map(|e| e.data) } else { vectorcraft_eps::native(bytes) }; - vectorcraft_format::load(&data?).ok() +/// The native document a linked file is or carries ([`carried_document`]). +enum Carried { + /// The file is no native document and carries none: an image, or a PDF, `.ai` or EPS file + /// without editing data. + Absent, + /// The native document, read. + Readable(Box), + /// The file is a native document, or carries one, that can't be read: a damaged native file, + /// a PDF or `.ai` file that can't be opened without a password or can't be read at all, a PDF + /// or `.ai` file listing an editing file whose data can't be resolved, a PDF or `.ai` file + /// whose attachments are too many to search to their end, or editing data that doesn't read as + /// a native document. + Unreadable, } +/// The native document that the linked file `name` (`bytes`) is, or carries as the editing data of +/// a PDF, `.ai` or EPS file. +fn carried_document(name: &str, bytes: &[u8]) -> Carried { + let read = |data: &[u8]| vectorcraft_format::load(data).map_or(Carried::Unreadable, |d| Carried::Readable(Box::new(d))); + if super::place::document::is_native(name, bytes) { + return vectorcraft_format::load_file(bytes).map_or(Carried::Unreadable, |f| Carried::Readable(Box::new(f.doc))); + } + if super::place::document::is_pdf(name, bytes) { + // A PDF that can't be opened may carry editing data all the same. + return match vectorcraft_pdf::open_pdf(bytes, None) { + // Attachments left unsearched may list another editing file, which can't be checked. + Ok(opened) if opened.editing_search_cut() => Carried::Unreadable, + // An editing file listed whose data can't be resolved can't be checked either. + Ok(opened) => match opened.editing() { + Some(e) => read(&e.data), + None if opened.has_editing_file() => Carried::Unreadable, + None => Carried::Absent, + }, + Err(_) => Carried::Unreadable, + }; + } + if !vectorcraft_eps::has_native(bytes) { + return Carried::Absent; + } + vectorcraft_eps::native(bytes).map_or(Carried::Unreadable, |data| read(&data)) +} + +/// The error for a linked file the package would copy whose native document can't be read to +/// check the files and folders it names against the read roots. +const UNREADABLE: &str = "a linked file's editing data can't be read to check it against the read roots"; + /// Under read roots, the linked file `name` (`bytes`, found at `path`) is copied only when the -/// native document it is or carries ([`carried_document`]) links no JavaScript file outside them (a -/// relative path taken from the file's folder): the copy would name it. +/// native document it is or carries ([`carried_document`]) can be read and links no JavaScript file +/// outside them (a relative path taken from the file's folder): the copy would name it. A file +/// whose native document can't be read is refused, as its links can't be checked. The error names +/// no file or folder. fn check_carried_scripts(name: &str, bytes: &[u8], path: &str) -> Result<()> { if crate::file_access::current().is_none() { return Ok(()); } match carried_document(name, bytes) { - Some(carried) => super::fileio::check_scripts_of(C, &carried, Some(path), || true), - None => Ok(()), + Carried::Readable(carried) => super::fileio::check_scripts_of(C, &carried, Some(path), || true), + Carried::Unreadable => Err(bad(C, UNREADABLE)), + Carried::Absent => Ok(()), + } +} + +/// The error for a linked file the package would copy with an Export for Screens folder outside +/// the read roots in the native document it is or carries. +const FOLDER_OUTSIDE: &str = "a linked file's export folder is outside the read roots"; + +/// Under read roots, the linked file `name` (`bytes`, as the package writes it) is copied only when +/// the native document it is or carries ([`carried_document`]) keeps no Export for Screens folder +/// outside them: a file copied as it is, a PDF, `.ai` or EPS file or a native document not +/// rewritten, would name it. The error names no file or folder. +fn check_carried_folder(name: &str, bytes: &[u8]) -> Result<()> { + if crate::file_access::current().is_none() { + return Ok(()); + } + match carried_document(name, bytes) { + Carried::Readable(carried) if matches!(super::fileio::with_readable_settings_folder(&carried), std::borrow::Cow::Owned(_)) => { + Err(bad(C, FOLDER_OUTSIDE)) + } + Carried::Unreadable => Err(bad(C, UNREADABLE)), + _ => Ok(()), } } @@ -363,6 +422,7 @@ impl<'a> Collector<'a> { options.profiles = saved.profiles; options.compress = compressed; options.include_linked = include_linked; + let nested = super::fileio::with_readable_settings_folder(&nested); match vectorcraft_format::save_with(&nested, &options) { Ok(rewritten) => bytes = rewritten, Err(e) => self.warn( @@ -381,6 +441,7 @@ impl<'a> Collector<'a> { } } } + check_carried_folder(&file.name, &bytes)?; let copy = Copied { name: destination_file.clone(), size: Some(bytes.len() as u64), hash: Some(hash_bytes(&bytes)) }; self.copies.insert(found_path.to_string(), copy.clone()); local.insert(file.path.clone(), copy); @@ -478,6 +539,9 @@ pub struct Package { root: Option, info: Option, doc: std::sync::Arc, + /// The read roots in force where the package was prepared: [`Package::write`] collects under + /// them. + scope: crate::file_access::ScopeHandle, } impl Session { @@ -520,23 +584,26 @@ fn prepare(s: &mut Session, p: &Value) -> Result { } let root = folder.map(|f| Path::new(f).join(&name)); let info = if o.report { Some(super::docinfo::report(s, false)?) } else { None }; + // The package's document leaves out an Export for Screens folder outside the read roots. let doc = s.doc()?.doc.clone(); + let doc = if let std::borrow::Cow::Owned(kept) = super::fileio::with_readable_settings_folder(&doc) { std::sync::Arc::new(kept) } else { doc }; let links_from = s.doc()?.links_from.clone().unwrap_or_else(|| doc_path.clone()); - Ok(Package { o, doc_path, links_from, stem, name, root, info, doc }) + let scope = crate::file_access::ScopeHandle::capture(); + Ok(Package { o, doc_path, links_from, stem, name, root, info, doc, scope }) } impl Package { /// Collect the linked files and fonts and write the package's files with `write` into /// `folder/name`, making its folders first, or into the zip without a folder → the reply of - /// `file.package`. + /// `file.package`, with the read roots in force where it was prepared, on any thread. pub fn write(self, write: &mut dyn FnMut(&str, &[u8]) -> Result<()>) -> Result { - collect_and_write(self, write) + self.scope.clone().run(|| collect_and_write(self, write)) } } /// [`Package::write`]. fn collect_and_write(package: Package, write: &mut dyn FnMut(&str, &[u8]) -> Result<()>) -> Result { - let Package { o, doc_path, links_from, stem, name, root, info, doc: original } = package; + let Package { o, doc_path, links_from, stem, name, root, info, doc: original, scope: _ } = package; let mut doc = (*original).clone(); let doc_name = format!("{stem}.{}", vectorcraft_format::EXTENSION); let base = LinkBase { doc: Some(&doc_path), relative: Some(&links_from) }; diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 2421b71d77..fddd6cdd9c 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -48,7 +48,7 @@ pub fn specs() -> Vec { "Default Fill and Stroke", [], Some("D"), - "{ids?|id?} white fill and 1 pt black stroke for the selection and the defaults; type gets black fill and no stroke. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke, and on a graph label the black fill and no stroke of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (exceptions: docs/mcp.md)", + "{ids?|id?} white fill and 1 pt black stroke for the selection and the defaults (in a document whose Default Graphic Style differs from the shipped one, as a New Document profile can redefine it: that style's fills, strokes and effects, without its opacity or a link to it); type gets black fill and no stroke. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke, and on a graph label the black fill and no stroke of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (exceptions: docs/mcp.md)", has_doc, default_paint ), @@ -274,8 +274,9 @@ impl DocState { /// Whether the selected objects' fills and strokes differ as the proxies show them (a "?" /// proxy; a group whose contents differ counts). `item` (the Appearance panel's active item) /// stands for the proxy of its kind, as in [`Session::proxy_paints`]: that fill or stroke of - /// each selected object's own stack is compared. One walk of the document, so callers that ask - /// every frame cache it by revision. + /// each selected object's own stack is compared. The selected objects are found through the id + /// cache ([`vectorcraft_doc::Document::nodes_in_order`]); a large selection takes one walk + /// of the document, so callers that ask every frame cache it by revision. pub fn proxy_mixed(&self, item: Option) -> (bool, bool) { self.proxy_mixed_with(item, &[]) } @@ -290,15 +291,17 @@ impl DocState { if self.selection.symbol_part.is_some() { return (false, false); } - let ids: std::collections::HashSet = self.selection.objects.iter().copied().collect(); - let (mut selected, mut nodes) = (vec![], vec![]); - self.doc.walk(|n| { - if ids.contains(&n.id) { - selected.push(n); - painted(n, true, &mut nodes); - } - }); + // Looking the first object up builds the id cache when there is none. let first = self.selection.objects.first().and_then(|id| self.doc.node(*id)); + let (mut selected, mut nodes) = (vec![], vec![]); + // Every node with a selected id, in tree order: a repeated id (a damaged file) counts at each + // place it appears. + for n in self.doc.nodes_in_order(self.selection.objects.iter().copied()) { + #[cfg(test)] + tests::note_gathered(); + selected.push(n); + painted(n, true, &mut nodes); + } let differ = |stroke: bool| { let item = first.and_then(|f| f.appearance.item_of_kind(item, !stroke)); let set = if item.is_some() { &selected } else { &nodes }; @@ -1035,6 +1038,8 @@ fn default_paint(s: &mut Session, p: &Value) -> Result { if !ids.is_empty() { // When every object comes out as it was, the document and its undo history stay as they are. let before = s.doc()?.doc.clone(); + // A redefined Default Graphic Style gives other art its fills, strokes and effects, placed on each object. + let style = super::newart::redefined_default_style(&before).cloned(); super::overprint::edit_counted(s, "Default Fill and Stroke", |d| { for id in &ids { let Some(n) = d.node_mut(*id) else { continue }; @@ -1045,7 +1050,12 @@ fn default_paint(s: &mut Session, p: &Value) -> Result { r.style.stroke = Paint::None; } } - _ => n.appearance = Appearance::default_art().into(), + _ => { + n.appearance = match &style { + Some(g) => g.appearance_on(n).into_owned().into(), + None => Appearance::default_art().into(), + } + } } } let kept = super::appearance::capture_series_writes(&before, d, &ids, (true, true), (true, true), false, false); @@ -1316,3 +1326,6 @@ fn transparency(s: &mut Session, p: &Value) -> Result { } s.execute("object.setProps", &Value::Object(q)) } + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/paint/tests.rs b/crates/engine/src/cmd/paint/tests.rs new file mode 100644 index 0000000000..3da5d73d9e --- /dev/null +++ b/crates/engine/src/cmd/paint/tests.rs @@ -0,0 +1,335 @@ +//! The Fill/Stroke proxies' "?" ([`DocState::proxy_mixed`]) finds the selected objects through the +//! id cache: it answers as a walk of the whole document does, and with a few objects selected it +//! reads only those. + +use std::cell::Cell; +use std::collections::HashSet; +use std::sync::Arc; + +use serde_json::json; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, Document, LayerColor, Node, NodeId, NodeKind}; +use vectorcraft_geom::{Rect, shapes}; + +use super::{painted, picked_colors, proxy_paint, same_in_proxy}; +use crate::{DocState, Session}; + +thread_local! { + /// [`gathered`] of this thread. + static GATHERED: Cell = const { Cell::new(0) }; +} + +/// Adds one to [`gathered`]: `proxy_mixed_with` read a node while looking for the selected ones. +pub(super) fn note_gathered() { + GATHERED.set(GATHERED.get() + 1); +} + +/// How many nodes `proxy_mixed_with` has read on this thread while looking for the selected ones. +fn gathered() -> u64 { + GATHERED.get() +} + +/// `proxy_mixed_with` as it was when it found the selected objects by walking the whole document. +fn walked(st: &DocState, item: Option, points: &[(NodeId, Vec)]) -> (bool, bool) { + if st.selection.is_empty() { + return (false, false); + } + if st.selection.symbol_part.is_some() { + return (false, false); + } + let ids: HashSet = st.selection.objects.iter().copied().collect(); + let (mut selected, mut nodes) = (vec![], vec![]); + st.doc.walk(|n| { + if ids.contains(&n.id) { + selected.push(n); + painted(n, true, &mut nodes); + } + }); + let first = st.selection.objects.first().and_then(|id| st.doc.node(*id)); + let differ = |stroke: bool| { + let item = first.and_then(|f| f.appearance.item_of_kind(item, !stroke)); + let set = if item.is_some() { &selected } else { &nodes }; + let mut paints = set.iter().flat_map(|n| match picked_colors(n, if stroke || item.is_some() { &[] } else { points }) { + c if c.is_empty() => vec![proxy_paint(n, stroke, item)], + c => c.into_iter().map(Paint::solid).collect(), + }); + let Some(p0) = paints.next() else { return false }; + paints.any(|p| !same_in_proxy(&p0, &p)) + }; + (differ(false), differ(true)) +} + +/// `proxy_mixed_with` answers as [`walked`] does for `st`'s selection, for every Appearance item +/// and with and without `points`, with the id cache built and without it. +fn agree(st: &DocState, points: &[(NodeId, Vec)], what: &str) { + for cold in [true, false] { + if cold { + st.doc.drop_lookup_cache(); + } + for item in [None, Some(0), Some(1), Some(2), Some(3)] { + for points in [points, &[]] { + assert_eq!( + st.proxy_mixed_with(item, points), + walked(st, item, points), + "{what}: item {item:?}, {} picked points, cold cache {cold}", + points.len() + ); + } + } + } +} + +fn id_of(v: &serde_json::Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap()) +} + +fn rect(s: &mut Session, x: f64, fill: &str, stroke: &str) -> NodeId { + let id = id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 20, "height": 20})).unwrap()); + s.execute("paint.setFill", &json!({"ids": [id.0], "color": fill})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [id.0], "color": stroke})).unwrap(); + id +} + +/// Every case of [`DocState::proxy_mixed`]'s rule, each answered as a walk answers it: one object, +/// different fills or strokes, a group with different contents, a group with one of its objects, +/// objects on two layers, a hidden object, an object with two fills under an Appearance item, a +/// gradient mesh with points picked beside another object, ids not in the document and an id that +/// appears twice (a damaged file) with different paints. +#[test] +fn the_question_marks_match_a_walk_of_the_document() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + let a = rect(&mut s, 10.0, "#ff0000", "#000000"); + let b = rect(&mut s, 40.0, "#0000ff", "#000000"); + let c = rect(&mut s, 70.0, "#ff0000", "#00ff00"); + // Two fills: [Fill, Stroke, Fill]. + s.execute("select.set", &json!({"ids": [c.0]})).unwrap(); + s.execute("appearance.addFill", &json!({})).unwrap(); + s.execute("appearance.setItem", &json!({"index": 2, "color": "#0000ff"})).unwrap(); + let e = rect(&mut s, 100.0, "#ff0000", "#000000"); + let f = rect(&mut s, 130.0, "#00ff00", "#000000"); + let g = id_of(&s.execute("object.group", &json!({"ids": [e.0, f.0]})).unwrap()); + let mesh = rect(&mut s, 160.0, "#ff0000", "#000000"); + s.execute("object.mesh.create", &json!({"ids": [mesh.0], "rows": 2, "cols": 2})).unwrap(); + let hidden = rect(&mut s, 190.0, "#0000ff", "#000000"); + s.execute("object.hide", &json!({"ids": [hidden.0]})).unwrap(); + s.execute("layer.new", &json!({})).unwrap(); + let h = rect(&mut s, 220.0, "#ff0000", "#000000"); + let missing = NodeId(999_999); + let Some(NodeKind::Mesh(m)) = s.doc().unwrap().doc.node(mesh).map(|n| &n.kind) else { panic!("a gradient mesh") }; + let (p00, p01, p11) = (m.idx(0, 0), m.idx(0, 1), m.idx(1, 1)); + s.execute("object.mesh.setPointColor", &json!({"id": mesh.0, "index": p00, "color": "#00ff00"})).unwrap(); + let points = vec![(mesh, vec![p00, p01])]; + let points_alike = vec![(mesh, vec![p01, p11])]; + + let selections = [ + vec![a], + vec![a, b], + vec![b, a], + vec![a, h], + vec![g], + vec![g, e], + vec![e, g], + vec![f, e], + vec![c], + vec![c, a], + vec![a, c], + vec![mesh], + vec![mesh, a], + vec![a, mesh, h], + vec![hidden], + vec![hidden, b], + vec![missing], + vec![missing, a], + vec![a, missing, b], + vec![a, a], + ]; + let check = |s: &mut Session, what: &str| { + for sel in &selections { + let st = s.active_mut().unwrap(); + st.selection.objects = sel.clone(); + let st = s.active().unwrap(); + agree(st, &points, &format!("{what}: {sel:?}")); + agree(st, &points_alike, &format!("{what}: {sel:?}, alike points")); + } + s.execute("select.all", &json!({})).unwrap(); + agree(s.active().unwrap(), &points, &format!("{what}: Select All")); + }; + check(&mut s, "unique ids"); + + // A second node with a's id and another fill, at the end of the tree. + let st = s.active_mut().unwrap(); + let mut copy = st.doc.node(a).unwrap().clone(); + copy.appearance.set_fill(Paint::solid(Color::rgb(0.0, 0.0, 1.0))); + let doc = Arc::make_mut(&mut st.doc); + let last = doc.layers.len() - 1; + Arc::make_mut(&mut doc.layers[last]).children_mut().unwrap().push(Arc::new(copy)); + doc.drop_lookup_cache(); + check(&mut s, "a repeated id"); + let st = s.active_mut().unwrap(); + st.selection.objects = vec![a]; + assert_eq!(st.proxy_mixed_with(None, &[]), (true, false), "the two places of a's id differ in fill"); +} + +/// A document of `layers` layers, each with `groups` groups of `per_group` rectangles; every other +/// rectangle red, the rest blue. Returns it with the rectangles' ids, in tree order. +fn big(layers: usize, groups: usize, per_group: usize) -> (Document, Vec) { + let mut d = Document::new(612.0, 792.0); + d.layers.clear(); + let mut rects = vec![]; + for l in 0..layers { + let mut layer = Node::layer(d.alloc_id(), &format!("L{l}"), LayerColor::Preset(0)); + for _ in 0..groups { + let children = (0..per_group) + .map(|_| { + let id = d.alloc_id(); + let mut ap = Appearance::default_art(); + let red = rects.len() % 2 == 0; + ap.set_fill(Paint::solid(if red { Color::rgb(1.0, 0.0, 0.0) } else { Color::rgb(0.0, 0.0, 1.0) })); + rects.push(id); + Arc::new(Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), ap)) + }) + .collect(); + let group = Node::group(d.alloc_id(), children); + layer.children_mut().unwrap().push(Arc::new(group)); + } + d.layers.push(Arc::new(layer)); + } + (d, rects) +} + +fn state(doc: Document) -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 612, "height": 792})).unwrap(); + s.active_mut().unwrap().doc = Arc::new(doc); + s +} + +/// With one object selected, the "?" reads only that object, not every node of the document, and +/// does not walk the tree once the id cache is built; with every object selected it walks the tree +/// once. +#[test] +fn the_question_marks_read_only_the_selected_objects() { + let (doc, rects) = big(2, 40, 25); + let mut s = state(doc); + let st = s.active_mut().unwrap(); + st.selection.objects = vec![rects[777]]; + assert_eq!(st.proxy_mixed(None), (false, false)); + let (read, walks) = (gathered(), vectorcraft_doc::tree_walks()); + assert_eq!(st.proxy_mixed(None), (false, false)); + assert_eq!(gathered() - read, 1, "only the selected object is read"); + assert_eq!(vectorcraft_doc::tree_walks() - walks, 0, "the cached path answers"); + + st.selection.objects = vec![rects[3], rects[1500]]; + let (read, walks) = (gathered(), vectorcraft_doc::tree_walks()); + assert_eq!(st.proxy_mixed(None), (true, false)); + assert_eq!((gathered() - read, vectorcraft_doc::tree_walks() - walks), (2, 0)); + + st.selection.objects = rects.clone(); + let (read, walks) = (gathered(), vectorcraft_doc::tree_walks()); + assert_eq!(st.proxy_mixed(None), (true, false)); + assert_eq!(gathered() - read, rects.len() as u64); + assert!(vectorcraft_doc::tree_walks() - walks <= 1, "one walk for a large selection"); +} + +/// Random selections of a document with nested groups answer as a walk does. +#[test] +fn random_selections_match_a_walk_of_the_document() { + let (doc, rects) = big(3, 12, 6); + let mut s = state(doc); + let groups: Vec = s.active().unwrap().doc.layers.iter().flat_map(|l| l.children().unwrap().iter().map(|g| g.id)).collect(); + let layers: Vec = s.active().unwrap().doc.layers.iter().map(|l| l.id).collect(); + let all: Vec = rects.iter().chain(&groups).chain(&layers).copied().chain([NodeId(999_999)]).collect(); + let mut r = 0x2545_f491_4f6c_dd1d_u64; + let mut next = |n: usize| { + r ^= r << 13; + r ^= r >> 7; + r ^= r << 17; + (r % n as u64) as usize + }; + for round in 0..200 { + let count = 1 + next(if round % 10 == 0 { all.len() } else { 6 }); + let sel: Vec = (0..count).map(|_| all[next(all.len())]).collect(); + let st = s.active_mut().unwrap(); + st.selection.objects = sel.clone(); + agree(s.active().unwrap(), &[], &format!("round {round}: {sel:?}")); + } +} + +/// The CPU time this thread has used, from Linux's scheduler statistics; `None` elsewhere. +fn thread_cpu() -> Option { + let stat = std::fs::read_to_string("/proc/thread-self/schedstat").ok()?; + stat.split_whitespace().next()?.parse().ok().map(std::time::Duration::from_nanos) +} + +/// The time `f` takes: this thread's CPU time where Linux reports it, otherwise the wall clock. +fn time(f: impl FnOnce()) -> std::time::Duration { + match thread_cpu() { + Some(before) => { + f(); + thread_cpu().map_or(std::time::Duration::ZERO, |after| after.saturating_sub(before)) + } + None => { + let start = std::time::Instant::now(); + f(); + start.elapsed() + } + } +} + +/// The time of `proxy_mixed` against a walk of the document, on 50,000 rectangles in 500 groups on +/// 5 layers: `cargo test --release -p vectorcraft-engine --lib proxy_mixed_timing -- --ignored --nocapture`. +#[test] +#[ignore = "timing; run by hand"] +fn proxy_mixed_timing() { + let (doc, rects) = big(5, 100, 100); + let mut s = state(doc); + let groups: Vec = s.active().unwrap().doc.layers.iter().flat_map(|l| l.children().unwrap().iter().map(|g| g.id)).collect(); + let cases: [(&str, Vec); 5] = [ + ("1 object", vec![rects[25_000]]), + ("2 objects, different fills", vec![rects[10], rects[40_001]]), + ("a group of 100", vec![groups[250]]), + ("all 500 groups", groups.clone()), + ("all 50,000 objects", rects.clone()), + ]; + const CALLS: usize = 200; + let median = |mut v: Vec| { + v.sort_by(f64::total_cmp); + v[v.len() / 2] + }; + println!("proxy_mixed_timing: {}", if thread_cpu().is_some() { "thread CPU time" } else { "wall clock" }); + println!("| Selection | Id cache | Walk (µs/call) | Id cache (µs/call) | Runs (walk / id cache, µs) |"); + println!("|---|---|---|---|---|"); + for (name, sel) in &cases { + for cold in [false, true] { + let st = s.active_mut().unwrap(); + st.selection.objects = sel.clone(); + let st = s.active().unwrap(); + assert_eq!(st.proxy_mixed_with(None, &[]), walked(st, None, &[]), "{name}"); + let (mut old, mut new) = (vec![], vec![]); + let calls = if cold { CALLS / 10 } else { CALLS }; + for _ in 0..7 { + for (times, use_walk) in [(&mut old, true), (&mut new, false)] { + let d = time(|| { + for _ in 0..calls { + if cold { + st.doc.drop_lookup_cache(); + } + std::hint::black_box(if use_walk { walked(st, None, &[]) } else { st.proxy_mixed_with(None, &[]) }); + } + }); + times.push(d.as_secs_f64() * 1e6 / calls as f64); + } + } + let runs = |v: &[f64]| v.iter().map(|x| format!("{x:.1}")).collect::>().join(" "); + println!( + "| {name} | {} | {:.1} | {:.1} | {} / {} |", + if cold { "dropped before each call" } else { "built" }, + median(old.clone()), + median(new.clone()), + runs(&old), + runs(&new) + ); + } + } +} diff --git a/crates/engine/src/cmd/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index aa83466693..769cb530b0 100644 --- a/crates/engine/src/cmd/panelcmds.rs +++ b/crates/engine/src/cmd/panelcmds.rs @@ -67,14 +67,14 @@ 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), kurikaeshiMojiShori?: bool (Paragraph panel menu › Kurikaeshi Moji Shori: a repeat mark 々, ゝ, ゞ, ヽ or ヾ that starts a line is drawn as the character before it, the voiced marks ゞ and ヾ as its voiced form when it has one, and the text keeps the mark; 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, down the column for an upright character in vertical type), diacriticHorizontal?, diacriticVertical?: 1/1000 em -1000..1000 (Character panel › Adjust Horizontal and Vertical Diacritic Position, with Show Indic Options, as text.setRangeStyle: the mark glyphs among the characters move right or up relative to their letters), 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; a form other than \"default\" takes away their glyph choice), 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\"|\"standardSingleLine\"|\"standardEveryLine\" (line breaking, Every-line by default; singleLine and everyLine are the Middle Eastern & South Asian composers, which shape Indic, Arabic and Hebrew type; the standard ones set it glyph by glyph as the font maps its characters, for legacy fonts that keep a script on Latin character codes), 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), startNumber?: 1..999999999, restartNumbering?: bool (Bullets and Numbering…'s Start At, VectorCraft's own: startNumber gives the first numbered paragraph the call touches, the first that holds text or else the first, taking the type objects in the order of `ids` and passing over a threaded frame's first paragraph when it continues from the frame before, that number, and the numbered paragraphs after it at its level count on from it, through the story's threaded frames; restartNumbering true gives it 1, and false takes the number away from every paragraph the call touches but such a continued first paragraph, which then count on from the paragraph before; giving both fails the call, and when the call touches no numbered paragraph nothing changes; a paragraph made with Return does not take the number, a paragraph made bulleted keeps none, and a paragraph style made from the paragraph does not keep it, nor does a graph label when the graph is drawn again), 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), kurikaeshiMojiShori?: bool (Paragraph panel menu › Kurikaeshi Moji Shori: a repeat mark 々, ゝ, ゞ, ヽ or ヾ that starts a line is drawn as the character before it, the voiced marks ゞ and ヾ as its voiced form when it has one, and the text keeps the mark; 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, down the column for an upright character in vertical type), diacriticHorizontal?, diacriticVertical?: 1/1000 em -1000..1000 (Character panel › Adjust Horizontal and Vertical Diacritic Position, with Show Indic Options, as text.setRangeStyle: the mark glyphs among the characters move right or up relative to their letters), 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; a form other than \"default\" takes away their glyph choice), 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\"|\"standardSingleLine\"|\"standardEveryLine\" (line breaking, Every-line by default; singleLine and everyLine are the Middle Eastern & South Asian composers, which shape Indic, Arabic and Hebrew type; the standard ones set it glyph by glyph as the font maps its characters, for legacy fonts that keep a script on Latin character codes), 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 ), cmd!( "text.convertListToText", "Convert to Text", - [], + ["Type"], None, "{ids?|id?, start?: byte, end?: byte} (Type › Bullets and Numbering › Convert to Text: the paragraphs of the selected type, or of `ids`, or those a start/end range touches; after Select All in a frame of threaded text, without `ids`, `id` or a range, every paragraph of every frame of the story, locked and hidden frames included) the marker of each list paragraph becomes characters of its text: the bullet, or the number and its period as the paragraph showed it, then a tab, at the start of the paragraph in the marker's font, size and color; the list is turned off. When the marker's tab went to the left indent, the paragraph gets a left-aligned tab stop without a leader there, in place of any stop there, which keeps the text after the tab where it started; when it went to a tab stop and a stop there or past it has a leader or is not left-aligned, or a right, center or decimal stop lies between the marker and that place, the paragraph gets a left-aligned stop without a leader where the marker's tab ended, in place of any stop there and of those right, center and decimal stops before it (past the left indent only in a paragraph with no tab of its own). In threaded type the numbers are those counted through the story's frames, and a paragraph that continues into a later frame is converted where its text starts. An empty list paragraph has no marker and only leaves the list. A paragraph with no direction set gets the direction it ran in when the characters would change it (a letter or roman numeral before right-to-left text). With the Every-line Composer, a paragraph with a tab is broken line by line, so a converted paragraph can break its lines at other places. While the Type tool edits, its typing ends first and its anchor and caret move past the characters inserted at or before them (a whole story that Select All selected stays selected when the call converts all of it); in threaded type, when the caret's character moved to another frame, the tool edits that frame, which becomes the selection when it was not selected. One undo step → {ids, converted: paragraphs, inserted: [{id, at: byte before the change, length: bytes}]}", has_doc, @@ -482,6 +482,66 @@ fn list_level_param(p: &Value, cmd: &str) -> Result> { } } +/// The number a numbered paragraph is given, from `startNumber` (a whole number from 1 to +/// [`vectorcraft_doc::text::MAX_LIST_START`]) or `restartNumbering` (true: 1): `Some(Some(n))`, +/// or `Some(None)` for `restartNumbering` false, which numbers paragraphs on from the one before. +/// None without either; giving both is an error. +fn list_start_param(p: &Value, cmd: &str) -> Result>> { + let (key, other) = ("startNumber", "restartNumbering"); + let start = p.get(key).filter(|v| !v.is_null()); + let restart = p.get(other).filter(|v| !v.is_null()); + if start.is_some() && restart.is_some() { + return Err(bad(cmd, format!("give `{key}` or `{other}`, not both"))); + } + if let Some(v) = start { + let (min, max) = (1, vectorcraft_doc::text::MAX_LIST_START); + return match v.as_f64() { + Some(x) if x.fract() == 0.0 && (f64::from(min)..=f64::from(max)).contains(&x) => Ok(Some(Some(x as u32))), + Some(x) => Err(bad(cmd, format!("`{key}` must be a whole number between {min} and {max} (got {x})"))), + None => Err(bad(cmd, format!("`{key}` must be a whole number"))), + }; + } + // `check_switches` has already refused a value that is not true or false. + Ok(restart.and_then(Value::as_bool).map(|on| on.then_some(1))) +} + +/// Take the number its list gives a paragraph away from paragraphs `paras` of `t` (indices; +/// None: every paragraph), so they count on from the paragraph before. A first paragraph that +/// continues from the frame before ([`TextObject::first_para_continues`]) keeps its number: its +/// item begins in that frame. +/// +/// [`TextObject::first_para_continues`]: vectorcraft_doc::text::TextObject::first_para_continues +fn clear_list_start(t: &mut vectorcraft_doc::text::TextObject, paras: Option>) { + let mut paras = paras.unwrap_or(0..t.paragraph_count()); + if paras.start == 0 && t.first_para_continues { + paras.start = 1; + } + if paras.is_empty() { + return; + } + t.edit_paras(Some(paras), |p| { + if let Some(l) = p.list.as_mut() { + l.start = None; + } + }); +} + +/// Among paragraphs `paras` of `t` (indices; None: every paragraph), the first numbered paragraph +/// that holds text and the first numbered paragraph: where a number from [`list_start_param`] can go. +/// A first paragraph that continues from the frame before ([`TextObject::first_para_continues`]) is +/// skipped: its item begins in that frame. +/// +/// [`TextObject::first_para_continues`]: vectorcraft_doc::text::TextObject::first_para_continues +fn list_start_candidates(t: &vectorcraft_doc::text::TextObject, paras: Option>) -> (Option, Option) { + let paras = paras.unwrap_or(0..t.paragraph_count()); + let text = t.plain_text(); + let pieces: Vec<&str> = text.split('\n').collect(); + let mut numbered = paras.filter(|&i| !(i == 0 && t.first_para_continues) && t.para_at(i).list.is_some_and(|l| l.number.is_some())).peekable(); + let first = numbered.peek().copied(); + let with_text = numbered.find(|&i| pieces.get(i).is_some_and(|s| !s.is_empty())); + (with_text, first) +} + /// Set the Warichu and Warichu Settings of `st` that are given: Warichu on or off, Lines, Line Gap /// (in the type's own units), Scale and Alignment. fn set_warichu( @@ -523,6 +583,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result { "koreanLineBreakAnywhere", "bunriKinshi", "kurikaeshiMojiShori", + "restartNumbering", ], C, )?; @@ -582,6 +643,8 @@ fn set_format(s: &mut Session, p: &Value) -> Result { "number", "listAlign", "listLevel", + "startNumber", + "restartNumbering", "hyphenate", "wordsLongerThan", "afterFirst", @@ -762,6 +825,8 @@ fn set_format(s: &mut Session, p: &Value) -> Result { .map(|a| if a == "right" { vectorcraft_doc::text::ListAlign::Right } else { vectorcraft_doc::text::ListAlign::Left }); // …and `listLevel` the level of every list paragraph, 1 to 9. let list_level = list_level_param(p, C)?; + // …and `startNumber` or `restartNumbering` the number of the first numbered paragraph. + let list_start = list_start_param(p, C)?; let indents_given = num("leftIndent").is_some() || num("firstLineIndent").is_some(); let spacing = |k: &str| spacing_param(p, k, C); let (word_spacing, letter_spacing, glyph_scaling) = (spacing("wordSpacing")?, spacing("letterSpacing")?, spacing("glyphScaling")?); @@ -885,9 +950,11 @@ fn set_format(s: &mut Session, p: &Value) -> Result { // A numbered list for list "number", or without `list` for a number style. let numbered = list == Some("number") || (list.is_none() && number.is_some()); // The list's other settings (the marker's alignment) stay as they were. + // A paragraph made bulleted keeps no number of its own. para.list = on.then(|| vectorcraft_doc::text::ParaList { bullet: bullet.flatten().or(had.map(|l| l.bullet)).unwrap_or_default(), number: numbered.then(|| number.flatten().or(had.and_then(|l| l.number)).unwrap_or_default()), + start: had.and_then(|l| l.start).filter(|_| numbered), ..had.unwrap_or_default() }); // A paragraph that joins a list with no left or first-line indent gets a @@ -912,6 +979,9 @@ fn set_format(s: &mut Session, p: &Value) -> Result { let d = &mut doc; // The paragraph change, for the graph labels to keep. let mut para_change = None; + // Where the number `startNumber` or `restartNumbering` gives goes: the first numbered + // paragraph with text the call touches, through every target, else the first numbered one. + let (mut start_with_text, mut start_first) = (None, None); let out_of_order_error = |name: &str| bad(C, format!("`{name}`: Minimum must not exceed Desired, nor Desired Maximum")); for id in &ids { let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else { continue }; @@ -1021,14 +1091,36 @@ fn set_format(s: &mut Session, p: &Value) -> Result { para.composer = v; } }; - t.edit_paras(span, |para| paras(para, &mut out_of_order)); + t.edit_paras(span.clone(), |para| paras(para, &mut out_of_order)); if let Some(name) = out_of_order { return Err(out_of_order_error(name)); } + match list_start { + Some(None) => clear_list_start(t, span), + Some(Some(_)) if start_with_text.is_none() => { + let (with_text, first) = list_start_candidates(t, span); + start_with_text = with_text.map(|i| (*id, i)); + start_first = start_first.or(first.map(|i| (*id, i))); + } + _ => {} + } super::typecmd::refresh_bounds(t); changed |= *t != before; para_change = Some(paras); } + if let Some(Some(n)) = list_start + && let Some((id, i)) = start_with_text.or(start_first) + && let Some(NodeKind::Text(t)) = d.node_mut(id).map(|node| &mut node.kind) + { + let before = t.clone(); + t.edit_paras(Some(i..i + 1), |p| { + if let Some(l) = p.list.as_mut() { + l.start = Some(n); + } + }); + super::typecmd::refresh_bounds(t); + changed |= *t != before; + } // Graph labels keep a change made to all of their text through the graph being drawn again. if range.is_none() { let shift = num("baselineShift").map(|v| v.clamp(-1296.0, 1296.0)); diff --git a/crates/engine/src/cmd/params.rs b/crates/engine/src/cmd/params.rs index 8dc29b9704..50e73f5a0d 100644 --- a/crates/engine/src/cmd/params.rs +++ b/crates/engine/src/cmd/params.rs @@ -36,6 +36,9 @@ //! `channel` that the effect doesn't have are refused by `effect.apply` and `effect.setParams` //! themselves ([`check_effect_color`], [`check_effect_channel`]). +use std::collections::HashMap; +use std::sync::OnceLock; + use serde_json::Value; use vectorcraft_apischema::shown_key; @@ -43,7 +46,7 @@ use super::{bad, command_specs, find_command}; use crate::Result; /// What a params description says about the keys of the params object. -#[derive(Debug, Default, PartialEq)] +#[derive(Clone, Debug, Default, PartialEq)] pub struct ParamKeys<'a> { /// The keys it names. pub keys: Vec<&'a str>, @@ -107,6 +110,8 @@ pub(crate) fn is_key(s: &str) -> bool { /// The keys a params description names, or what in it doesn't read as one. pub fn doc_keys(doc: &str) -> std::result::Result, String> { + #[cfg(test)] + PARSES.with(|n| n.set(n.get() + 1)); let mut out = ParamKeys::default(); let (mut body, mut rest) = object_body(doc)?; let mut entries = split_top(body, ','); @@ -155,7 +160,12 @@ fn named_commands(more: &str) -> impl Iterator Option> { - let parsed = doc_keys(doc).ok()?; + resolve(doc, depth, &mut |doc| doc_keys(doc).ok()) +} + +/// [`accepted`], with `parse` reading each description it reaches. +fn resolve(doc: &'static str, depth: usize, parse: &mut dyn FnMut(&'static str) -> Option>) -> Option> { + let parsed = parse(doc)?; let mut keys = parsed.keys; for more in parsed.more { let mut named = named_commands(more).peekable(); @@ -168,22 +178,120 @@ fn accepted(doc: &'static str, depth: usize) -> Option> { if UNCHECKED.contains(&spec.id) { return None; } - keys.extend(accepted(spec.params, depth + 1)?); + keys.extend(resolve(spec.params, depth + 1, parse)?); } } Some(keys) } +/// What the params description of a built-in command says about its keys, read once per process +/// ([`known`]). +#[derive(Debug)] +struct Known { + /// The keys it names itself; none when it doesn't parse. + own: Vec<&'static str>, + /// [`accepted`] of it. + accepted: Option>, + /// [`id_stands_for_ids`] of it. + id_stands_for_ids: bool, +} + +impl Known { + /// [`takes_key`] of the description. + fn takes(&self, key: &str) -> bool { + self.own.contains(&key) || self.accepted.as_ref().is_some_and(|keys| keys.contains(&key)) + } +} + +/// The place and length of `doc`'s text: a description with the same words elsewhere (a plug-in's) +/// has another place. +fn text_key(doc: &str) -> (usize, usize) { + (doc.as_ptr().addr(), doc.len()) +} + +/// [`Known`] of each description in `docs`, each one and each one its `…` entries name parsed once. +/// A description is left out when one it reaches has a `…` entry naming a plug-in command, whose +/// keys change as plug-ins are installed and removed. +fn read_descriptions(docs: impl IntoIterator) -> HashMap<(usize, usize), Known> { + let names_plugin = + |more: &str| more.split_whitespace().any(|w| w.trim_matches(|c: char| !c.is_ascii_alphanumeric()).starts_with(vectorcraft_plugins::PREFIX)); + let mut parsed: HashMap<(usize, usize), (Option>, bool)> = HashMap::new(); + let mut table = HashMap::new(); + for doc in docs { + if table.contains_key(&text_key(doc)) { + continue; + } + let mut live = false; + let mut parse = |doc: &'static str| { + let (keys, plugin) = parsed.entry(text_key(doc)).or_insert_with(|| { + let keys = doc_keys(doc).ok(); + let plugin = keys.as_ref().is_some_and(|k| k.more.iter().any(|m| names_plugin(m))); + (keys, plugin) + }); + live |= *plugin; + keys.clone() + }; + let own = parse(doc).map(|p| p.keys).unwrap_or_default(); + let accepted = resolve(doc, 0, &mut parse); + if live { + continue; + } + let mut known = Known { own, accepted, id_stands_for_ids: false }; + known.id_stands_for_ids = known.takes("ids") && known.takes("id") && no_required_id_beside_ids(doc); + table.insert(text_key(doc), known); + } + table +} + +/// [`Known`] of `doc` when it is the params description of a built-in command. +fn known(doc: &str) -> Option<&'static Known> { + #[cfg(test)] + if UNCACHED.get() { + return None; + } + static TABLE: OnceLock> = OnceLock::new(); + TABLE.get_or_init(|| read_descriptions(command_specs().iter().map(|c| c.params))).get(&text_key(doc)) +} + +#[cfg(test)] +thread_local! { + /// The times [`doc_keys`] parsed a description on this thread. + pub(crate) static PARSES: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Whether [`known`] is skipped on this thread ([`uncached`]). + static UNCACHED: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Whether [`read_descriptions`] keeps what `doc` says. +#[cfg(test)] +pub(crate) fn read_once(doc: &'static str) -> bool { + read_descriptions([doc]).contains_key(&text_key(doc)) +} + +/// `f`'s result with every description parsed again where it is used, as without [`known`]. +#[cfg(test)] +pub(crate) fn uncached(f: impl FnOnce() -> T) -> T { + let before = UNCACHED.replace(true); + let out = f(); + UNCACHED.set(before); + out +} + /// Every key the description `doc` takes, those of the commands its `…` entries name included, or /// `None` when that isn't known: it doesn't parse, a `…` entry names no command, or one names a /// command in [`UNCHECKED`]. pub(crate) fn accepted_keys(doc: &'static str) -> Option> { - accepted(doc, 0) + match known(doc) { + Some(known) => known.accepted.clone(), + None => accepted(doc, 0), + } } /// Does the description `doc` name `key` as a parameter (its own keys, and those of the commands /// its `…` entries name)? pub fn takes_key(doc: &'static str, key: &str) -> bool { + if let Some(known) = known(doc) { + return known.takes(key); + } doc_keys(doc).is_ok_and(|parsed| parsed.keys.contains(&key)) || accepted(doc, 0).is_some_and(|keys| keys.contains(&key)) } @@ -191,12 +299,17 @@ pub fn takes_key(doc: &'static str, key: &str) -> bool { /// (instead of id)}`, `{id} or {ids: […]}`): it names both keys, and no params object of it names /// `ids` beside a required `id`, which is something else (`plugin.run {id, ids?}`: the plug-in's)? pub(crate) fn id_stands_for_ids(doc: &'static str) -> bool { + if let Some(known) = known(doc) { + return known.id_stands_for_ids; + } + takes_key(doc, "ids") && takes_key(doc, "id") && no_required_id_beside_ids(doc) +} + +/// No params object of `doc` names `ids` beside a required `id`. +fn no_required_id_beside_ids(doc: &str) -> bool { fn head(alternative: &str) -> &str { alternative.split([':', '=', '(']).next().unwrap_or_default().trim() } - if !takes_key(doc, "ids") || !takes_key(doc, "id") { - return false; - } let mut rest = doc; while let Ok((body, after)) = object_body(rest) { let entries = split_top(body, ','); @@ -249,20 +362,33 @@ pub fn check_keys(id: &str, doc: &'static str, params: &Value) -> Result<()> { if given.is_empty() { return Ok(()); } - let Some(keys) = accepted(doc, 0) else { return Ok(()) }; + let live; + let keys = match known(doc) { + Some(known) => known.accepted.as_deref(), + None => { + live = accepted(doc, 0); + live.as_deref() + } + }; + let Some(keys) = keys else { return Ok(()) }; match given.keys().find(|k| !keys.contains(&k.as_str())) { - Some(key) => Err(unknown(id, key, &keys)), + Some(key) => Err(unknown(id, key, keys)), None => Ok(()), } } /// Parameters a command takes instead of one another: (command, key, other key). Giving both, /// neither null, is a parameter error ([`check_exclusive_keys`]). -const EXCLUSIVE_KEYS: &[(&str, &str, &str)] = &[("addon.pathtools.cornerSet", "items", "ids"), ("addon.pathtools.cornerRemove", "items", "ids")]; +const EXCLUSIVE_KEYS: &[(&str, &str, &str)] = &[ + ("addon.pathtools.cornerSet", "items", "ids"), + ("addon.pathtools.cornerRemove", "items", "ids"), + ("links.unembed", "id", "ids"), + ("links.unembed", "path", "folder"), +]; /// `params` of command `id` give at most one of each pair in [`EXCLUSIVE_KEYS`], or the parameter /// error naming the pair. -fn check_exclusive_keys(id: &str, params: &Value) -> Result<()> { +pub(crate) fn check_exclusive_keys(id: &str, params: &Value) -> Result<()> { let given = |key: &str| params.get(key).filter(|v| !v.is_null()); for (_, key, other) in EXCLUSIVE_KEYS.iter().filter(|(c, ..)| *c == id) { if given(key).is_some() && given(other).is_some() { @@ -928,9 +1054,14 @@ fn check_params_in(id: &str, params: &Value, in_batch: bool) -> Result<()> { crate::schemas::check(spec, params, false)?; } if matches!(id, "command.batch" | "action.batch") && !in_batch { - for step in params.get("commands").and_then(Value::as_array).into_iter().flatten() { + for (i, step) in params.get("commands").and_then(Value::as_array).into_iter().flatten().enumerate() { if let Some(step_id) = step.get("command").and_then(Value::as_str) { - check_params_in(step_id, step.get("params").unwrap_or(&Value::Null), true)?; + let checked = check_params_in(step_id, step.get("params").unwrap_or(&Value::Null), true); + // An `action.batch` names the step it refuses by its place, from 1, as its own checks and its steps' errors do. + match checked { + Err(e) if id == "action.batch" => return Err(bad(id, super::fileio::action_step(i, step_id, &e.to_string()))), + checked => checked?, + } } } } diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index 6c06b52c6c..0960e5ca28 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -1,10 +1,10 @@ //! Path editing commands (used by the Pen and Direct Selection tools and Object → Path). -use std::collections::BTreeSet; +use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; use serde_json::{Value, json}; -use vectorcraft_doc::{Document, Node, NodeId, NodeKind, Scaling, Selection}; +use vectorcraft_doc::{AnchorRef, Document, Node, NodeId, NodeKind, Scaling, Selection}; use vectorcraft_geom::{Anchor, AnchorKind, Anchors, PathData, Point, SubPath, Vec2}; use super::create::anchor_from_json; @@ -41,7 +41,7 @@ pub fn specs() -> Vec { "Move Anchors", [], None, - "{dx, dy, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles)} move direct-selected anchors (whole paths if fully selected); refused while an object of a symbol instance's art is selected", + "{dx, dy, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), interpolate?: bool (Interpolate Control Points: the handles of each segment with one moved end are re-mapped by the turn, scale and move that take its old ends to its new ends; default: prefs interpolateControlPoints)} move direct-selected anchors (whole paths if fully selected); refused while an object of a symbol instance's art is selected", has_selection, move_anchors ), @@ -245,28 +245,43 @@ fn close(s: &mut Session, p: &Value) -> Result { pub(crate) fn move_anchors(s: &mut Session, p: &Value) -> Result { let d = Vec2::new(number_or(p, "dx", 0.0, "path.moveAnchors")?, number_or(p, "dy", 0.0, "path.moveAnchors")?); - check_switches(p, &["patterns"], "path.moveAnchors")?; + check_switches(p, &["patterns", "interpolate"], "path.moveAnchors")?; // An object selected in a symbol instance's art stays where the symbol puts it. super::edit::refuse_symbol_part(s)?; // Objects selected whole move as objects, and their pattern tiles move with them when // `patterns` (default: General › Transform Pattern Tiles) is on. let whole = s.doc()?.selection.whole(); let sc = Scaling { patterns: super::object::transform_patterns(s, p, &whole)?, ..Scaling::default() }; - transform_anchors(s, "Move", vectorcraft_geom::Affine::translate(d), sc)?; + let interpolate = interpolates_handles(s, p, "path.moveAnchors")?; + transform_anchors(s, "Move", vectorcraft_geom::Affine::translate(d), sc, interpolate)?; // Transform Again repeats a move that moved something; a drag records it when it commits. let st = s.doc_mut()?; if st.interaction.is_none() && (d.x != 0.0 || d.y != 0.0) { - let options = json!({ "copy": false, "patterns": sc.patterns }); + let options = json!({ "copy": false, "patterns": sc.patterns, "interpolate": interpolate }); st.last_transform = Some(crate::LastTransform::Matrix(vectorcraft_geom::Affine::translate(d), options)); st.last_perspective = None; } ok() } +/// Interpolate Control Points: does a move of direct-selected anchors re-map the handles of the +/// segments beside them (`interpolate` param, else General › Interpolate Control Points When +/// Moving Anchors)? Noted in the journal, so a replay re-maps them alike whatever the preference +/// is then. A saved step without `interpolate` ([`Session::replay`]) was recorded before the +/// preference existed, so it moves the handles as it did then, without re-mapping them. +pub(crate) fn interpolates_handles(s: &mut Session, p: &Value, cmd: &str) -> Result { + let default = s.prefs.interpolate_control_points && !s.replaying(); + let on = switch_or(p, "interpolate", default, cmd)?; + s.note_journal("interpolate", json!(on)); + Ok(on) +} + /// Apply `xf` to the direct-selected anchors, their handles with them, and (with `sc`) to the /// objects selected whole (those with no entry in the selection's `anchors`). An object inside /// another selected object, such as a path in a selected group, moves once, with that object. -pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_geom::Affine, sc: Scaling) -> Result<()> { +/// When `xf` is a move and `interpolate` is on, the handles of each segment with one moved end +/// are re-mapped ([`move_interpolating_handles`]). +pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_geom::Affine, sc: Scaling, interpolate: bool) -> Result<()> { let sel = s.doc()?.selection.clone(); let ids = super::edit::outermost(&s.doc()?.doc, sel.objects.clone()); let c = xf.as_coeffs(); @@ -277,9 +292,15 @@ pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_ge match sel.anchors.get(id) { Some(set) => { let path = path_mut(doc, *id)?; - for &(si, ai) in set { - if let Some(a) = path.anchor_mut(si, ai) { - *a = a.transform(xf); + // Only an exact move takes the interpolating path: a near-identity scale or + // turn still transforms the anchors as asked. + if interpolate && c[..4] == [1.0, 0.0, 0.0, 1.0] { + move_interpolating_handles(path, set, delta); + } else { + for &(si, ai) in set { + if let Some(a) = path.anchor_mut(si, ai) { + *a = a.transform(xf); + } } } // A pixel-aligned path, or the pixel-aligned compound path that holds it, snaps @@ -307,6 +328,129 @@ pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_ge }) } +/// Move the anchors `set` of `path` by `d`, their handles with them, then re-map the two handles +/// of each segment with exactly one moved end by the map that takes the segment's old ends to its +/// new ends: a turn, a uniform scale and a move. Between two corner anchors the segment keeps its +/// shape relative to its ends. A segment with both ends moved, or with its ends at the same place +/// before or after the move, moves as it does without the preference. A smooth anchor keeps its +/// two handles in line ([`line_up_handles`]). +fn move_interpolating_handles(path: &mut PathData, set: &BTreeSet, d: Vec2) { + // (subpath, anchor, outgoing handle?, new position) + let mut placed: Vec<(usize, usize, bool, Point)> = Vec::new(); + if d != Vec2::ZERO { + // Only the segments beside a moved anchor can have one moved end: (subpath, first anchor). + let mut segments: BTreeSet = BTreeSet::new(); + for &(si, ai) in set { + let Some(sp) = path.subpaths.get(si) else { continue }; + let n = sp.anchors.len(); + if ai >= n || n < 2 { + continue; + } + if ai > 0 || sp.closed { + segments.insert((si, (ai + n - 1) % n)); + } + if ai + 1 < n || sp.closed { + segments.insert((si, ai)); + } + } + for (si, from) in segments { + let Some(sp) = path.subpaths.get(si) else { continue }; + let to = (from + 1) % sp.anchors.len().max(1); + let (moved_from, moved_to) = (set.contains(&(si, from)), set.contains(&(si, to))); + if moved_from == moved_to { + continue; + } + let (Some(a), Some(b)) = (sp.anchors.get(from), sp.anchors.get(to)) else { continue }; + let old = b.p - a.p; + let len2 = old.hypot2(); + if len2 <= 1e-12 || !len2.is_finite() { + continue; + } + let start = if moved_from { a.p + d } else { a.p }; + let end = if moved_to { b.p + d } else { b.p }; + let new = end - start; + // A move that puts the two ends at the same place would collapse both handles onto + // them, past recovering by moving back. + if new.hypot2() <= 1e-12 { + continue; + } + // `new / old` as complex numbers: the turn and scale between the two chords. + let (re, im) = ((new.x * old.x + new.y * old.y) / len2, (new.y * old.x - new.x * old.y) / len2); + let map = |h: Point| { + let v = h - a.p; + start + Vec2::new(v.x * re - v.y * im, v.x * im + v.y * re) + }; + // A retracted handle goes to its anchor's new place exactly: mapped, it could land a + // rounding error away, which `line_up_handles` would read as a direction. + let h_out = if a.h_out == a.p { start } else { map(a.h_out) }; + let h_in = if b.h_in == b.p { end } else { map(b.h_in) }; + if h_out.is_finite() && h_in.is_finite() { + placed.push((si, from, true, h_out)); + placed.push((si, to, false, h_in)); + } + } + } + for &(si, ai) in set { + if let Some(a) = path.anchor_mut(si, ai) { + a.translate(d); + } + } + // For each anchor with a re-mapped handle: its handles as the plain move left them, and which + // of them (outgoing, incoming) were re-mapped. + let mut touched: BTreeMap = BTreeMap::new(); + for &(si, ai, out, pos) in &placed { + if let Some(a) = path.anchor_mut(si, ai) { + let e = touched.entry((si, ai)).or_insert((a.h_out, a.h_in, false, false)); + if out { + a.h_out = pos; + e.2 = true; + } else { + a.h_in = pos; + e.3 = true; + } + } + } + for ((si, ai), (rigid_out, rigid_in, out, inn)) in touched { + let Some(a) = path.anchor_mut(si, ai) else { continue }; + if a.kind == AnchorKind::Smooth && !line_up_handles(a, out, inn) { + a.h_out = rigid_out; + a.h_in = rigid_in; + } + } +} + +/// Put the handles of the smooth anchor `a` back in line after [`move_interpolating_handles`] +/// re-mapped its outgoing handle (`out`), its incoming handle (`inn`) or both. A re-mapped handle +/// turns to point away from the other handle, at its own new length; when both were re-mapped, +/// both point along the mean of their directions. A retracted handle is left as it is. False when +/// both were re-mapped to point the same way, which has no mean direction: the caller then moves +/// both handles with the anchor. +fn line_up_handles(a: &mut Anchor, out: bool, inn: bool) -> bool { + let (v_out, v_in) = (a.h_out - a.p, a.h_in - a.p); + let (l_out, l_in) = (v_out.hypot(), v_in.hypot()); + if l_out <= 0.0 || l_in <= 0.0 || !l_out.is_finite() || !l_in.is_finite() { + return true; + } + let dir = match (out, inn) { + (true, true) => v_out / l_out - v_in / l_in, + (true, false) => -v_in / l_in, + (false, true) => v_out / l_out, + (false, false) => return true, + }; + let l = dir.hypot(); + if l <= 1e-12 || !l.is_finite() { + return false; + } + let dir = dir / l; + if out { + a.h_out = a.p + dir * l_out; + } + if inn { + a.h_in = a.p - dir * l_in; + } + true +} + fn set_handle(s: &mut Session, p: &Value) -> Result { let id = object_param(p, "id", "path.setHandle")?.ok_or_else(|| bad("path.setHandle", "missing id"))?; let si = usize_opt(p, "subpath", "path.setHandle")?.unwrap_or(0); diff --git a/crates/engine/src/cmd/pathops.rs b/crates/engine/src/cmd/pathops.rs index 70de82fa65..cb60409f17 100644 --- a/crates/engine/src/cmd/pathops.rs +++ b/crates/engine/src/cmd/pathops.rs @@ -27,7 +27,7 @@ pub fn specs() -> Vec { "Unite", ["Window", "Pathfinder"], None, - "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}", + "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids, warning?: when a selected object is or holds a line or another open path that encloses no area once closed, and so does not change the result's shape (when such a path leaves the result empty, as in Intersect, the error says so)}", has_selection, |s, p| run_pf(s, p, PathfinderOp::Unite) ), @@ -36,7 +36,7 @@ pub fn specs() -> Vec { "Minus Front", ["Window", "Pathfinder"], None, - "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}", + "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids, warning?: when a selected object is or holds a line or another open path that encloses no area once closed, and so does not change the result's shape (when such a path leaves the result empty, as in Intersect, the error says so)}", has_selection, |s, p| run_pf(s, p, PathfinderOp::MinusFront) ), @@ -45,7 +45,7 @@ pub fn specs() -> Vec { "Intersect", ["Window", "Pathfinder"], None, - "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}", + "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids, warning?: when a selected object is or holds a line or another open path that encloses no area once closed, and so does not change the result's shape (when such a path leaves the result empty, as in Intersect, the error says so)}", has_selection, |s, p| run_pf(s, p, PathfinderOp::Intersect) ), @@ -54,7 +54,7 @@ pub fn specs() -> Vec { "Exclude", ["Window", "Pathfinder"], None, - "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}", + "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids, warning?: when a selected object is or holds a line or another open path that encloses no area once closed, and so does not change the result's shape (when such a path leaves the result empty, as in Intersect, the error says so)}", has_selection, |s, p| run_pf(s, p, PathfinderOp::Exclude) ), @@ -108,7 +108,7 @@ pub fn specs() -> Vec { "Minus Back", ["Window", "Pathfinder"], None, - "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}", + "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids, warning?: when a selected object is or holds a line or another open path that encloses no area once closed, and so does not change the result's shape (when such a path leaves the result empty, as in Intersect, the error says so)}", has_selection, |s, p| run_pf(s, p, PathfinderOp::MinusBack) ), @@ -285,6 +285,37 @@ impl Style { } } +/// The Shape Mode commands' warning, which the status bar shows, when a selected object is or holds +/// a line or another open path that encloses no area once closed, and so does not change the result's +/// shape (the result still takes its paint from the frontmost object, as without the warning). +pub const SHAPE_MODE_OPEN_PATH_NO_AREA: &str = "a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first"; + +/// `path` has an open subpath that encloses no area once closed (a straight line, or an evenodd +/// contour traced twice), by the area its fill rule gives, so a self-crossing path whose signed +/// area is zero (a bow tie) still counts as enclosing area, as Divide measures it. +fn has_open_subpath_without_area(path: &PathData, rule: FillRule) -> bool { + path.subpaths.iter().filter(|sp| !sp.closed).any(|sp| { + // A point or a straight two-anchor line needs no area measurement. + if sp.anchors.len() < 2 || (sp.anchors.len() == 2 && sp.anchors.iter().all(|a| a.h_in == a.p && a.h_out == a.p)) { + return true; + } + let mut closed = sp.clone(); + closed.closed = true; + // The signed-area test alone only holds for nonzero: evenodd can fill nothing where the + // signed area is not zero (a contour traced twice). + !(rule == FillRule::NonZero && po::encloses_area(sp)) && po::area(&PathData::single(closed), rule) <= 0.0 + }) +} + +/// The area `path` fills with its open subpaths closed, as the Shape Modes fill it. +fn closed_area(path: &PathData, rule: FillRule) -> f64 { + let mut closed = path.clone(); + for sp in &mut closed.subpaths { + sp.closed = true; + } + po::area(&closed, rule) +} + /// All subpaths of a path or compound path node, in document coordinates, with its fill rule. pub(crate) fn node_path(n: &Node) -> Option<(PathData, FillRule)> { match &n.kind { @@ -685,8 +716,9 @@ fn run_pf(s: &mut Session, p: &Value, op: PathfinderOp) -> Result { let keeps_hidden = matches!(op, PathfinderOp::Intersect | PathfinderOp::MinusFront | PathfinderOp::MinusBack | PathfinderOp::Crop); let label = pf_label(op); let options = pf_options(s, p, &format!("object.pathfinder.{}", pf_id(op)))?; - let ids = s.edit(label, |d, sel| { + let (ids, no_area) = s.edit(label, |d, sel| { // Build the stack (back → front); names are separate from paint/style identity. + let mut no_area = false; let mut styles: Vec, env: EnvId }, Native { f: NativeFn, kind: NativeKind, constructor: bool, name: &'static str }, + Pausable { f: crate::interp::PausableFn, name: &'static str }, Host { f: Rc, name: Rc }, Data { f: DataFn, name: Rc, read: crate::host::ArgRead }, Eval { f: DataFn, end: Rc, strict_writes: Rc Option>, name: Rc }, diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index fb980843e8..4c18d0f76f 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -447,7 +447,12 @@ impl Interp { Ok(units) => self.prepare_source(units.len().saturating_sub(floor)), Err(_) => Ok(()), }; - rest.map(|()| units.and_then(|units| self.compile_source_writes(&units, false, writes, crate::bytecode::CodeKind::Eval))) + rest.map(|()| { + units.and_then(|units| { + self.observe_code(&units); + self.compile_source_writes(&units, false, writes, crate::bytecode::CodeKind::Eval) + }) + }) }); let code = code.and_then(|c| c); self.source_tag = tag; diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 700efddfb2..21cd2c0bc5 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -673,6 +673,24 @@ fn error_sources_count_from_the_last_script_and_code_from_an_earlier_one_is_unkn assert_eq!(r.error_source(), 0, "a syntax error is in the script"); } +#[test] +fn the_code_observer_sees_every_source_evaluated_at_run_time() { + let mut r = realm(10_000_000); + let seen = Rc::new(RefCell::new(Vec::::new())); + let s = seen.clone(); + r.observe_code(move |units| s.borrow_mut().push(String::from_utf16_lossy(units))); + let source: HostFunction = Rc::new(|_| Ok(Data::String("40 + 2".into()))); + let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None) }; + r.define_host_object("host", vec![("load".into(), load)]).unwrap(); + let out = r.run("function f() { return eval('1 + 1'); } f() + (0, eval)('2') + Function('a', 'return a')(3) + host.load()").unwrap(); + assert_eq!(out, JsValue::Number(49.0)); + let want = ["1 + 1", "2", "(function anonymous(a\n) {\nreturn a\n})", "40 + 2"]; + assert_eq!(*seen.borrow(), want, "the script's own text is not observed"); + seen.borrow_mut().clear(); + r.run("eval(7); Function.prototype.toString.call(f)").unwrap(); + assert!(seen.borrow().is_empty(), "eval of a value that is not a string compiles nothing"); +} + #[test] fn error_tags_stay_the_same_from_run_to_run_and_are_never_shared() { let mut r = realm(10_000_000); diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 7e21bf9fdf..d81e12f3ac 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -162,6 +162,34 @@ pub(crate) struct Frame { /// Where the exception being thrown was raised: the code and the instruction. type ThrowSite = (Rc, usize); +/// What [`crate::Realm::observe_code`] calls with each source evaluated at run time. +pub(crate) type CodeObserver = Rc; + +/// A built-in function that may wait for the host ([`crate::heap::Func::Pausable`]): it is given +/// `this` and the arguments, and gives the host call it makes. +pub(crate) type PausableFn = fn(&mut Interp, Value, &[Value]) -> JsResult; + +/// What a [`PausableFn`] does with the host's answer: it is given the values it kept and the +/// answer, and gives the result of its call. +pub(crate) type ResumeFn = fn(&mut Interp, &[Value], Value) -> JsResult; + +/// The host call a [`PausableFn`] makes: the host function `host` with `args`. Its answer goes to +/// `resume` with `keep`, at once when the host answers at once. When the host waits +/// ([`crate::HostError::Wait`]), the run pauses at the call, and `resume` runs when the run goes on +/// after [`crate::Realm::answer`]; a run ended while it waits ([`crate::Realm::end`]) drops it. +pub(crate) struct Pause { + pub(crate) host: Value, + pub(crate) args: Vec, + pub(crate) keep: Vec, + pub(crate) resume: ResumeFn, +} + +/// A [`Pause`] whose host call waits for its answer. +pub(crate) struct Resumption { + resume: ResumeFn, + keep: Vec, +} + pub(crate) struct Interp { pub(crate) heap: Heap, pub(crate) stack: Vec, @@ -222,6 +250,9 @@ pub(crate) struct Interp { pub(crate) can_wait: Rc>, /// A host function's call waits for its result: the value on top of the stack stands in for it. pub(crate) waiting: bool, + /// The built-in that waits with the host's call ([`Pause::Ask`]): it takes the answer before + /// the next instruction runs. + pub(crate) resuming: Option, /// The message of the uncatchable error a host function ended the run with. pub(crate) host_abort: Option, /// How much a value passed to or from a host function may carry. @@ -230,6 +261,9 @@ pub(crate) struct Interp { pub(crate) source_tag: u32, /// The sources [`crate::HostItem::Evaluator`] functions have given in this realm. pub(crate) evaluated: u32, + /// Called with the source text given to `eval`, `Function` and evaluator functions, before it + /// is compiled ([`crate::Realm::observe_code`]). + pub(crate) code_observer: Option, /// The tag of the source the last run's error was raised in. pub(crate) error_tag: u32, /// Where `$.line` and `$.stack` find the file and line of a compiled line. @@ -470,10 +504,12 @@ impl Interp { in_slice: false, can_wait: Rc::default(), waiting: false, + resuming: None, host_abort: None, data_limits: crate::DataLimits::default(), source_tag: crate::realm::UNKNOWN_SOURCE, evaluated: 0, + code_observer: None, error_tag: crate::realm::UNKNOWN_SOURCE, locator: None, thrown_mark: None, @@ -679,6 +715,7 @@ impl Interp { let mut roots = Roots::default(); roots.values.extend(self.stack.iter()); roots.values.extend(self.temp_roots.iter()); + roots.values.extend(self.resuming.iter().flat_map(|r| r.keep.iter())); roots.values.push(&self.last_thrown); roots.values.push(&self.last_error); roots.values.push(&self.passing); @@ -743,6 +780,14 @@ impl Interp { fn step(&mut self) -> JsResult> { self.tick()?; + // A built-in that waited for the host takes the answer on top of the stack before the + // instruction after its call runs; what it throws is thrown at that call. + if let Some(r) = self.resuming.take() { + let answer = self.pop()?; + let v = self.resume(r, answer)?; + self.push(v)?; + return Ok(None); + } let frame = self.frame_mut()?; let Some(&op) = frame.code.ops.get(frame.pc) else { return internal("ran past the end of the code") }; frame.pc += 1; @@ -2162,6 +2207,16 @@ impl Interp { self.temp_roots.truncate(mark); return Ok(Prepared::Done(r?)); } + Func::Pausable { f: native, .. } => { + let mark = self.temp_roots.len(); + self.temp_roots.push(this.clone()); + self.temp_roots.extend(args.iter().cloned()); + let held = self.held_bytes; + let r = native(self, this, &args).and_then(|p| self.ask(p)); + self.held_bytes = held; + self.temp_roots.truncate(mark); + return Ok(Prepared::Done(r?)); + } Func::Data { f, name, read } => { // The arguments are read before the function runs, and a result being built // keeps itself reachable. @@ -2387,6 +2442,41 @@ impl Interp { Ok(a) } + /// Makes the host call a [`PausableFn`] gave, whose answer goes to its resume function. A host + /// function is called as the script's own code calls it, so it may wait; then the resume + /// function is kept for the answer [`crate::Realm::answer`] gives, and the value that stands + /// in for that answer is the call's result for now. + fn ask(&mut self, p: Pause) -> JsResult { + let Pause { host, args, keep, resume } = p; + let mark = self.temp_roots.len(); + self.temp_roots.push(host.clone()); + self.temp_roots.extend(args.iter().cloned()); + self.temp_roots.extend(keep.iter().cloned()); + let was_waiting = self.waiting; + let answer = match self.func_of(&host) { + Some(Func::Data { f, name, read }) => self.call_data(&f, &name, &args, &read), + _ => self.call(&host, &Value::Undefined, &args), + }; + self.temp_roots.truncate(mark); + let answer = answer?; + let r = Resumption { resume, keep }; + if self.waiting && !was_waiting { + self.resuming = Some(r); + return Ok(answer); + } + self.resume(r, answer) + } + + /// Gives a [`PausableFn`]'s kept values and the host's `answer` to its resume function. + fn resume(&mut self, r: Resumption, answer: Value) -> JsResult { + let mark = self.temp_roots.len(); + self.temp_roots.push(answer.clone()); + self.temp_roots.extend(r.keep.iter().cloned()); + let v = (r.resume)(self, &r.keep, answer); + self.temp_roots.truncate(mark); + v + } + /// Calls `f` from Rust and returns its result, running the loop again for a function written /// in JavaScript. pub(crate) fn call(&mut self, f: &Value, this: &Value, args: &[Value]) -> JsResult { @@ -2435,6 +2525,13 @@ impl Interp { crate::to_utf16(text, &self.remaining_source_options()).map_err(CompileError::Syntax) } + /// Gives `units`, source a script evaluates at run time, to the realm's code observer. + pub(crate) fn observe_code(&self, units: &[u16]) { + if let Some(f) = &self.code_observer { + f(units); + } + } + /// Parses and compiles source for eval code or a script, counting it against the source /// limit. pub(crate) fn compile_source(&mut self, units: &[u16], strict: bool, kind: CodeKind) -> Result, CompileError> { @@ -2473,6 +2570,7 @@ impl Interp { self.check_source_units(s.len()).map_err(|e| self.compile_error_to_abrupt(e))?; self.prepare_source(s.len())?; let units = self.flat_reserved(s)?; + self.observe_code(&units); let code = self.compile_source(&units, strict, CodeKind::Eval).map_err(|e| self.compile_error_to_abrupt(e))?; self.charge_code(&code, declaration_bytes(&code).saturating_add(ENV_BYTES))?; let frame = self.frame()?; diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index 4146ae891b..0a1006a23c 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -251,6 +251,7 @@ impl Realm { interp.last_error = Value::Null; interp.host_abort = None; interp.waiting = false; + interp.resuming = None; interp.error_tag = UNKNOWN_SOURCE; interp.thrown_mark = None; interp.finally_marks.clear(); @@ -286,6 +287,7 @@ impl Realm { interp.temp_roots.clear(); interp.join_stack.clear(); interp.waiting = false; + interp.resuming = None; interp.passing = Value::Undefined; match result { Ok(v) => Ok(interp.to_js_value(&v)), @@ -375,7 +377,9 @@ impl Realm { } /// Gives the call that waits ([`crate::HostError::Wait`]) its result `d`; the next - /// [`Realm::advance`] goes on from there. A result past the heap limit ends the run with that + /// [`Realm::advance`] goes on from there. When a built-in such as `File.openDialog` made the + /// call, the built-in takes `d` first and gives its own result, and what it throws is thrown + /// at its call. A result past the heap limit ends the run with that /// limit, and with no call waiting this gives an internal error. pub fn answer(&mut self, d: crate::Data) -> Result<(), RunError> { let interp = &mut self.interp; @@ -468,10 +472,12 @@ impl Realm { /// Adds the global constructors `File` and `Folder`, whose file system work the host functions /// in `items` do: `parse`, `relative`, `tempName`, `stat`, `open`, `close`, `read`, `readln`, /// `readch`, `seek`, `tell`, `eof`, `encoding`, `setEncoding`, `list`, `resolve`, `execute`, - /// `encode`, `decode`, `encodingAvailable`, `current` and `locations`, with the values `system` - /// and `lineFeed` and the messages `text.notOpen`, `text.noWrites`, `text.noPicker` and - /// `text.badMode`. Each object keeps its path, its `error` text, its open file's id, its - /// encoding and its line feed in properties that are not enumerable. + /// `write`, `copy`, `remove`, `rename`, `create`, `setLength`, `setReadonly`, `pick` (the file + /// dialogs, where a run may wait), `encode`, `decode`, `encodingAvailable`, `current` and + /// `locations`, with the values `system` and `lineFeed` and the messages `text.notOpen`, + /// `text.badMode`, `text.noAlias` and `text.noHidden`. Each object keeps its path, its `error` + /// text, its open file's id, its encoding and its line feed in properties that are not + /// enumerable. pub fn define_file_classes(&mut self, items: Vec<(String, crate::HostItem)>) -> Result<(), RunError> { match crate::file_classes::install(&mut self.interp, items) { Ok(()) => Ok(()), @@ -543,6 +549,14 @@ impl Realm { self.interp.date_host.offset = std::rc::Rc::new(offset); } + /// Calls `observe` with the text of each source the realm's scripts evaluate at run time, before + /// it is compiled: a string given to `eval` (direct or indirect), the parameters and body + /// `Function` joins, and a source an evaluator host function + /// ([`crate::HostItem::Evaluator`]) gives. Replaces an earlier observer. + pub fn observe_code(&mut self, observe: impl Fn(&[u16]) + 'static) { + self.interp.code_observer = Some(std::rc::Rc::new(observe)); + } + /// Collects garbage now and returns the heap's estimated size in bytes afterwards. pub fn collect_garbage(&mut self) -> usize { self.interp.collect_garbage(); diff --git a/crates/mcp/src/headless.rs b/crates/mcp/src/headless.rs index 8bd8afc2e5..db6c51d47d 100644 --- a/crates/mcp/src/headless.rs +++ b/crates/mcp/src/headless.rs @@ -45,10 +45,15 @@ const HOST_COMMANDS: &[(&str, &str, &str)] = &[ "{folder?, zip?, artboards? | range? | fullDocument? | assets?, includeBleed?, includeArtboardFill?, subfolders?, preset?, formats?, settings?, prefix?} = document.exportForScreens (no folder → the files, or one zip, as dataBase64)", ), ("tool.select", "Select Tool", "{tool} e.g. selection, directSelection, pen, rectangle, ellipse, polygon, star, lineSegment"), + ( + "tool.selectLastSelection", + "Select Last Selection Tool", + "{} choose the selection tool chosen last (Selection, Direct Selection or Group Selection; none yet: the Selection tool) → {tool}", + ), ( "tool.setOption", "Tool Option", - "{key?, value? | values?: {key: value…}, tool?: id (default: the active tool)} → the tool's options (`{}` reads them); kept options last across tool switches", + "{key?, value? | values?: {key: value…}, tool?: id (default: the active tool)} → the tool's options (`{}` or no params reads them; params that are not an object are an error); kept options last across tool switches", ), ]; @@ -165,6 +170,7 @@ impl Headless { "file.export" => self.export(params), "file.exportForScreens" => self.session.execute("document.exportForScreens", params).map_err(|e| e.to_string()), "tool.select" => self.select_tool(params), + "tool.selectLastSelection" => self.select_last_selection_tool(), "tool.setOption" => self.session.set_tool_option_cmd(params), _ => self.session.execute(id, params).map_err(|e| e.to_string()), } @@ -208,6 +214,15 @@ impl Headless { Ok(json!({"tool": self.session.tool_id()})) } + /// `tool.selectLastSelection`: the selection tool chosen last, kept when it is already active. + fn select_last_selection_tool(&mut self) -> Result { + let id = self.session.last_selection_tool(); + if self.session.tool_id() != id { + self.session.select_tool(id, self.view).map_err(|e| e.to_string())?; + } + Ok(json!({"tool": self.session.tool_id()})) + } + fn apply_ui_requests(&mut self, reqs: Vec, out: &mut Vec) -> Result<(), String> { for r in reqs { match r { @@ -215,6 +230,7 @@ impl Headless { self.session.select_tool(&t, self.view).map_err(|e| e.to_string())?; } UiRequest::Dialog(k, p) => out.push(json!({"dialog": k, "params": p})), + UiRequest::Panel(panel) => out.push(json!({"panel": panel})), UiRequest::Status(msg) => out.push(json!({"status": msg})), // The place cursor's file, placed at once. UiRequest::Place(p) => { diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index a6d1fe6c5d..a8d6cc86e6 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -17,10 +17,12 @@ mod limits; mod links; mod liquify; mod livepaint; +mod move_offsets; mod pen; mod persp; mod place; mod protocol; +mod shapewidgets; mod svg; fn server() -> Server { @@ -1634,6 +1636,54 @@ fn doc_json(s: &mut Server) -> Value { serde_json::from_str(&text_of(&r)).unwrap() } +#[test] +fn transform_refused_by_a_later_operation_changes_nothing() { + let mut s = server(); + let count = |s: &mut Server| -> u64 { + let r = call(s, 90, "inspect_document", json!({})); + serde_json::from_str::(&text_of(&r)).unwrap()["objects"].as_u64().unwrap() + }; + let base = count(&mut s); + let r = id_of(&call(&mut s, 1, "draw_shape", json!({"shape": "rectangle", "x": 100, "y": 100, "width": 100, "height": 50}))); + let before = doc_json(&mut s); + for (id, args, says) in [ + (2, json!({"ids": [r], "scale": 50, "shear": 90}), "object.shear"), + (3, json!({"ids": [r], "dx": 10, "rotate": 30, "shear": -270}), "object.shear"), + (4, json!({"ids": [r], "scale": 50, "shear": 400}), "object.shear"), + (5, json!({"ids": [r], "scale": 50, "reflect": "diagonal"}), "object.reflect"), + (6, json!({"ids": [r], "dx": 10, "rotate": 30, "scaleX": 0}), "object.scale"), + ] { + let t = call(&mut s, id, "transform", args.clone()); + assert_eq!(t["isError"], true, "{args}: {t}"); + assert!(text_of(&t).contains(says), "{args}: {t}"); + assert_eq!(doc_json(&mut s), before, "{args}"); + } + // No undo step was recorded: one undo removes the rectangle. + assert_eq!(call(&mut s, 7, "undo", json!({}))["isError"], false); + assert_eq!(count(&mut s), base, "one undo removes the rectangle"); +} + +#[test] +fn add_text_rejects_invalid_path_effects_before_editing() { + let mut s = server(); + let path = id_of(&call(&mut s, 1, "draw_path", json!({"d": "M40 400 C150 300 250 500 360 400 Z"}))); + let before = call(&mut s, 2, "doc_inspect", json!({})); + for (args, message) in [ + (json!({"text": "Type", "path": path, "pathEffect": "not-an-effect"}), "not-an-effect"), + (json!({"text": "Type", "path": path, "pathEffect": 42}), "must be a string"), + (json!({"text": "Type", "path": path, "mode": "area", "pathEffect": "skew"}), "requires type on a path"), + (json!({"text": "Type", "x": 10, "y": 20, "pathEffect": "skew"}), "requires type on a path"), + ] { + let reply = call(&mut s, 3, "add_text", args); + assert_eq!(reply["isError"], true, "{reply}"); + assert!(text_of(&reply).contains(message), "{reply}"); + assert_eq!(call(&mut s, 4, "doc_inspect", json!({})), before, "path, selection and history must stay intact"); + } + let made = call(&mut s, 5, "add_text", json!({"text": "Type", "path": path, "pathEffect": "skew"})); + assert_eq!(made["isError"], false, "{made}"); + assert!(doc_json(&mut s).to_string().contains("\"pathEffect\":\"skew\"")); +} + #[test] fn text_effect_pathfinder_transform_graph_and_wrap_tools() { let mut s = server(); @@ -1893,6 +1943,30 @@ fn e_during_a_marquee_gesture_selects_only_the_objects_inside() { assert_eq!(serde_json::from_str::(&text_of(&r)).unwrap()["handledBy"], "tool.select", "{r}"); } +/// `run_command tool.selectLastSelection` headless: the Selection tool before any selection tool +/// is chosen, then the selection tool chosen last; Magic Wand doesn't count. `list_commands` +/// lists it as a command the headless backend runs. +#[test] +fn select_last_selection_tool_runs_headless() { + let mut s = server(); + let mut id = 0; + let mut run = |s: &mut Server, command: &str, params: Value| { + id += 1; + let r = call(s, id, "run_command", json!({"command": command, "params": params})); + assert_eq!(r["isError"], false, "{command}: {r}"); + serde_json::from_str::(&text_of(&r)).unwrap() + }; + run(&mut s, "tool.select", json!({"tool": "pen"})); + assert_eq!(run(&mut s, "tool.selectLastSelection", json!({})), json!({"tool": "selection"})); + run(&mut s, "tool.select", json!({"tool": "groupSelection"})); + run(&mut s, "tool.select", json!({"tool": "magicWand"})); + assert_eq!(run(&mut s, "tool.selectLastSelection", json!({})), json!({"tool": "groupSelection"})); + let r = call(&mut s, 99, "list_commands", json!({"filter": "selectLastSelection"})); + let v: Value = serde_json::from_str(&text_of(&r)).unwrap(); + let listed = v["commands"].as_array().unwrap().iter().find(|c| c["id"] == "tool.selectLastSelection").cloned().unwrap_or_default(); + assert_eq!((listed["host"].clone(), listed["label"].clone()), (json!(true), json!("Select Last Selection Tool")), "{v}"); +} + /// `press_key {key: "c"}` and `{key: "f"}` while an arc is being dragged go to the Arc tool, and /// the release draws one arc. With nothing dragged, C is a shortcut again. #[test] @@ -2185,3 +2259,55 @@ fn add_text_reports_overflow_and_takes_a_fit() { let point = made(&call(&mut s, 3, "add_text", json!({"text": "NEON DRIVE", "x": 0, "y": 300, "size": 60}))); assert!(point.get("overflow").is_none(), "{point}"); } + +#[test] +fn transform_rejects_nonnumeric_steps_before_editing() { + let inspect = |s: &mut Server, id| serde_json::from_str::(&text_of(&call(s, id, "doc_inspect", json!({})))).unwrap(); + let mut s = server(); + let first = id_of(&call(&mut s, 1, "draw_path", json!({"d": "M10 10 L30 10 L30 25 Z"}))); + let second = id_of(&call(&mut s, 2, "draw_path", json!({"d": "M40 40 L60 40 L60 55 Z"}))); + let before = inspect(&mut s, 3); + assert_eq!(before["selection"], json!([second])); + + let cases = [ + ("rotate", json!({"dx": 10, "rotate": "bad"})), + ("scale", json!({"dx": 10, "scale": "bad"})), + ("scaleX", json!({"dx": 10, "scaleX": "bad", "scaleY": 150})), + ("scaleY", json!({"dx": 10, "scaleX": 150, "scaleY": "bad"})), + ("shear", json!({"dx": 10, "shear": "bad"})), + ]; + for (index, (field, mut args)) in cases.into_iter().enumerate() { + args["ids"] = json!([first]); + let request_id = 4 + index as u64 * 2; + let rejected = call(&mut s, request_id, "transform", args); + assert_eq!(rejected["isError"], true, "{field}: {rejected}"); + assert!(text_of(&rejected).contains(field), "{field}: {rejected}"); + assert_eq!(inspect(&mut s, request_id + 1), before, "{field}"); + } + + let applied = call(&mut s, 14, "transform", json!({"ids": [first], "dx": 10, "rotate": null, "scale": 150, "scaleX": 125})); + assert_eq!(applied["isError"], false, "{applied}"); + let applied: Value = serde_json::from_str(&text_of(&applied)).unwrap(); + assert_eq!(applied["applied"], json!(["move", "scale"])); + let after = inspect(&mut s, 15); + assert_ne!(after, before); + assert_eq!(after["objects"], before["objects"]); + assert_eq!(after["selection"], json!([first])); + let bounds = &after["selectionBounds"]; + assert!((bounds["width"].as_f64().unwrap() - 25.0).abs() < 1e-6, "{bounds}"); + assert!((bounds["height"].as_f64().unwrap() - 22.5).abs() < 1e-6, "{bounds}"); + assert!(after["history"].as_array().unwrap().contains(&json!("Move"))); + assert!(after["history"].as_array().unwrap().contains(&json!("Scale"))); + + let applied = call(&mut s, 16, "transform", json!({"ids": [second], "dx": 10, "rotate": 90, "origin": [0, 0]})); + assert_eq!(applied["isError"], false, "{applied}"); + let applied: Value = serde_json::from_str(&text_of(&applied)).unwrap(); + assert_eq!(applied["applied"], json!(["move", "rotate"])); + let after = inspect(&mut s, 17); + assert_eq!(after["selection"], json!([second])); + let bounds = &after["selectionBounds"]; + for (field, expected) in [("x", 40.0), ("y", -70.0), ("width", 15.0), ("height", 20.0)] { + assert!((bounds[field].as_f64().unwrap() - expected).abs() < 1e-6, "{field}: {bounds}"); + } + assert!(after["history"].as_array().unwrap().ends_with(&[json!("Move"), json!("Rotate")])); +} diff --git a/crates/mcp/src/tests/liquify.rs b/crates/mcp/src/tests/liquify.rs index 4760380bc2..793f16efee 100644 --- a/crates/mcp/src/tests/liquify.rs +++ b/crates/mcp/src/tests/liquify.rs @@ -28,6 +28,36 @@ fn tool_options_are_set_headless_and_kept_across_tool_switches() { assert_eq!(command(&mut h, "tool.setOption", json!({}))["detail"], json!(6.0)); } +/// A value the tool refuses is an error result naming the tool and the option, and the options +/// stay as they were, the good value given with it included. +#[test] +fn a_refused_option_value_is_an_error_result() { + let mut h = Headless::with_document(); + command(&mut h, "tool.select", json!({"tool": "warp"})); + let before = command(&mut h, "tool.setOption", json!({})); + for values in [json!({"width": 64, "detail": 99}), json!({"width": 64, "detail": "fine"})] { + let r = call_tool(&mut h, "run_command", &json!({"command": "tool.setOption", "params": {"values": values}})); + assert!(r.is_error, "{r:?}"); + assert!(format!("{:?}", r.content).contains("tool `warp`: `detail` must be a number from 1 to 10"), "{r:?}"); + } + assert_eq!(command(&mut h, "tool.setOption", json!({})), before); +} + +/// `tool.setOption` with params that are not an object is an error result that sets nothing; +/// without params it reads the options, as `{}` does. +#[test] +fn set_option_params_that_are_not_an_object_are_an_error_result() { + let mut h = Headless::with_document(); + command(&mut h, "tool.select", json!({"tool": "warp"})); + let before = command(&mut h, "tool.setOption", json!({})); + for params in [json!(true), json!(7), json!([]), json!("x")] { + let r = call_tool(&mut h, "run_command", &json!({"command": "tool.setOption", "params": params})); + assert!(r.is_error, "{params}: {r:?}"); + } + assert_eq!(ok(&mut h, "run_command", json!({"command": "tool.setOption"})), before); + assert_eq!(command(&mut h, "tool.setOption", json!({})), before); +} + #[test] fn pointer_gestures_carry_pen_pressure() { let bloat = |pressure: f64| { diff --git a/crates/mcp/src/tests/move_offsets.rs b/crates/mcp/src/tests/move_offsets.rs new file mode 100644 index 0000000000..77fb8860a2 --- /dev/null +++ b/crates/mcp/src/tests/move_offsets.rs @@ -0,0 +1,67 @@ +use serde_json::{Value, json}; + +use super::{Server, call, id_of, server, text_of}; + +fn inspect(s: &mut Server, id: u64) -> Value { + serde_json::from_str(&text_of(&call(s, id, "doc_inspect", json!({})))).unwrap() +} + +fn path(s: &mut Server, id: u64, d: &str) -> u64 { + id_of(&call(s, id, "draw_path", json!({"d": d}))) +} + +fn child(doc: &Value, id: u64) -> Value { + doc["layers"][0]["children"].as_array().unwrap().iter().find(|node| node["id"] == id).unwrap().clone() +} + +#[test] +fn transform_rejects_malformed_move_offsets_before_selection_or_copy() { + let mut s = server(); + let first = path(&mut s, 1, "M40 40 L60 40 L60 60 L40 60 Z"); + let second = path(&mut s, 2, "M100 100 L130 100 L130 140 L100 140 Z"); + let before = inspect(&mut s, 3); + assert_eq!(before["selection"], json!([second])); + + let cases = [("dx", json!({"ids": [first], "dx": "bad", "copy": true})), ("dy", json!({"ids": [first], "dx": 10, "dy": "bad", "copy": true}))]; + for (index, (field, args)) in cases.into_iter().enumerate() { + let request_id = 4 + index as u64 * 2; + let result = call(&mut s, request_id, "transform", args); + assert_eq!(result["isError"], true, "{field}: {result}"); + assert!(text_of(&result).contains(field), "{field}: {result}"); + assert_eq!(inspect(&mut s, request_id + 1), before, "{field}"); + } + + // The recorded request omits dx and must still move a copy down by 10 points. + let result = call(&mut s, 8, "transform", json!({"ids": [first], "dy": 10, "copy": true})); + assert_eq!(result["isError"], false, "{result}"); + let reply: Value = serde_json::from_str(&text_of(&result)).unwrap(); + assert_eq!(reply["applied"], json!(["move"])); + let after = inspect(&mut s, 9); + let copied = after["selection"][0].as_u64().unwrap(); + assert_ne!(copied, first); + assert_ne!(copied, second); + let original_before = child(&before, first); + let original_after = child(&after, first); + let second_after = child(&after, second); + let copy_after = child(&after, copied); + assert_eq!(original_after["bounds"], original_before["bounds"]); + assert_eq!(second_after["bounds"], child(&before, second)["bounds"]); + assert_eq!(copy_after["bounds"]["x"], original_before["bounds"]["x"]); + assert_eq!(copy_after["bounds"]["y"], original_before["bounds"]["y"].as_f64().unwrap() + 10.0); + assert_eq!(copy_after["bounds"]["width"], original_before["bounds"]["width"]); + assert_eq!(copy_after["bounds"]["height"], original_before["bounds"]["height"]); + let before_history = before["history"].as_array().unwrap(); + let after_history = after["history"].as_array().unwrap(); + assert_eq!(after_history.len(), before_history.len() + 1); + assert_eq!(after_history.last(), Some(&json!("Move"))); + + // Null keeps the engine's optional-number default while a negative numeric offset is applied. + let result = call(&mut s, 10, "transform", json!({"ids": [second], "dx": null, "dy": -7})); + assert_eq!(result["isError"], false, "{result}"); + let after_null = inspect(&mut s, 11); + let moved = child(&after_null, second); + let second_before = child(&before, second); + assert_eq!(moved["bounds"]["x"], second_before["bounds"]["x"]); + assert_eq!(moved["bounds"]["y"], second_before["bounds"]["y"].as_f64().unwrap() - 7.0); + assert_eq!(after_null["history"].as_array().unwrap().last(), Some(&json!("Move"))); +} diff --git a/crates/mcp/src/tests/shapewidgets.rs b/crates/mcp/src/tests/shapewidgets.rs new file mode 100644 index 0000000000..3ef209efab --- /dev/null +++ b/crates/mcp/src/tests/shapewidgets.rs @@ -0,0 +1,30 @@ +//! A shape tool's double-click on a selected live shape's corner widget through MCP: the +//! gesture's `requests` carry the Transform panel. + +use serde_json::{Value, json}; +use vectorcraft_tools::corners::CornerWidgets; + +use crate::{Backend, Headless, call_tool}; + +fn ok(h: &mut Headless, name: &str, args: Value) -> Value { + let r = call_tool(h, name, &args); + assert!(!r.is_error, "{name} {args}: {r:?}"); + serde_json::from_str(r.content[0]["text"].as_str().unwrap()).unwrap_or(Value::Null) +} + +#[test] +fn a_corner_widget_double_click_with_a_shape_tool_requests_the_transform_panel() { + let mut h = Headless::new(); + h.call("engine.execute", json!({"command": "file.new", "params": {"width": 300, "height": 300}})).unwrap(); + ok(&mut h, "draw_shape", json!({"shape": "rectangle", "x": 100, "y": 100, "width": 100, "height": 100})); + let st = h.session.doc().unwrap(); + let w = CornerWidgets::showing(&st.doc, &st.selection, h.view.zoom, false, true, 180.0).expect("corner widgets show"); + let at = w.visible().next().expect("a widget"); + let steps = st.history.undo.len(); + let dbl = ok(&mut h, "pointer_gesture", json!({"tool": "rectangle", "events": [{"kind": "doubleclick", "x": at.x, "y": at.y}]})); + assert_eq!(dbl["requests"], json!([{"panel": "transform"}]), "{dbl}"); + assert_eq!(h.session.doc().unwrap().history.undo.len(), steps, "no undo step"); + // Off the widgets, the double-click asks for nothing. + let off = ok(&mut h, "pointer_gesture", json!({"events": [{"kind": "doubleclick", "x": 280, "y": 280}]})); + assert_eq!(off["requests"], json!([]), "{off}"); +} diff --git a/crates/mcp/src/tools/definitions.rs b/crates/mcp/src/tools/definitions.rs index 1b86095c6e..d730f8deaf 100644 --- a/crates/mcp/src/tools/definitions.rs +++ b/crates/mcp/src/tools/definitions.rs @@ -466,7 +466,7 @@ pub fn tool_definitions() -> Vec { tool( "transform", "Transform", - "Move, rotate, scale, reflect or shear the selection (or `ids`); several may be combined and run in that order. Angles in degrees (counter-clockwise), scale in %. Scale and reflect act along the selection's bounding box, turned with rotated objects until Reset Bounding Box. `origin` [x,y] defaults to the selection centre; `copy` transforms a copy.", + "Move, rotate, scale, reflect or shear the selection (or `ids`); several may be combined and run in that order. Angles in degrees (counter-clockwise), scale in %. Scale and reflect act along the selection's bounding box, turned with rotated objects until Reset Bounding Box. `origin` [x,y] defaults to the selection centre; `copy` transforms a copy. A scale, reflect or shear its command refuses returns that error before any step runs, and nothing changes.", obj( json!({ "ids": {"type": "array", "items": {"type": "integer"}}, diff --git a/crates/mcp/src/tools/dispatch.rs b/crates/mcp/src/tools/dispatch.rs index 2ee9f01759..95c8e8671d 100644 --- a/crates/mcp/src/tools/dispatch.rs +++ b/crates/mcp/src/tools/dispatch.rs @@ -275,7 +275,15 @@ fn dispatch(b: &mut dyn Backend, name: &str, a: &Args) -> Result j(transform(b, a)?), + "transform" => { + // Validate all numeric steps before the handler changes selection or runs a step. + for field in ["dx", "dy", "rotate", "scale", "scaleX", "scaleY", "shear"] { + if a.get(field).is_some_and(|value| !value.is_null() && value.as_f64().is_none()) { + return Err(format!("`{field}` must be a number")); + } + } + j(transform(b, a)?) + } "create_graph" => { let mut p = Value::Object(a.clone()); if p.get("type").is_none() { diff --git a/crates/mcp/src/tools/handlers.rs b/crates/mcp/src/tools/handlers.rs index 717c641e19..619af2e12e 100644 --- a/crates/mcp/src/tools/handlers.rs +++ b/crates/mcp/src/tools/handlers.rs @@ -247,6 +247,16 @@ pub(super) fn select_ids(b: &mut dyn Backend, a: &Args) -> Result<(), String> { pub(super) fn add_text(b: &mut dyn Backend, a: &Args) -> Result { let text = a.get("text").and_then(Value::as_str).ok_or("missing string argument `text`")?; + // Creating type on a path replaces the path. Refuse an invalid effect before editing. + let path_effect = match a.get("pathEffect") { + None | Some(Value::Null) => None, + Some(Value::String(effect)) if vectorcraft_doc::PathEffect::parse(effect).is_some() => Some(effect), + Some(Value::String(effect)) => return Err(format!("unknown path effect `{effect}`")), + Some(_) => return Err("`pathEffect` must be a string".into()), + }; + if path_effect.is_some() && (!a.contains_key("path") || a.get("mode").is_some_and(|m| !matches!(m.as_str(), Some("onPath" | "path")))) { + return Err("`pathEffect` requires type on a path".into()); + } let mut style = json!({}); for k in ["size", "font", "color", "justify", "vertical"] { if let Some(v) = a.get(k) { @@ -276,12 +286,12 @@ pub(super) fn add_text(b: &mut dyn Backend, a: &Args) -> Result { } exec(b, "text.create", p)? }; - if let Some(e) = a.get("pathEffect").and_then(Value::as_str) { + if let Some(e) = path_effect { exec(b, "type.pathOptions", json!({"effect": e}))?; } let mut made = json!({"id": r.get("id")}); // A path effect is applied after the text is made: ask again how it fits then. - let overflow = match r.get("id").filter(|_| a.get("pathEffect").is_some()) { + let overflow = match r.get("id").filter(|_| path_effect.is_some()) { Some(id) => exec(b, "document.node", json!({"id": id, "summary": true}))?.get("overflow").and_then(Value::as_bool) == Some(true), None => r.get("overflow").is_some(), }; @@ -292,6 +302,24 @@ pub(super) fn add_text(b: &mut dyn Backend, a: &Args) -> Result { } pub(super) fn transform(b: &mut dyn Backend, a: &Args) -> Result { + // Each operation is its own command: check the params the later ones refuse before the first + // runs, so a refused request changes nothing. + fn bad(cmd: &'static str) -> impl Fn(String) -> String { + move |e| format!("invalid parameters for `{cmd}`: {e}") + } + let s = a.get("scale").and_then(Value::as_f64); + let (sx, sy) = (a.get("scaleX").and_then(Value::as_f64).or(s), a.get("scaleY").and_then(Value::as_f64).or(s)); + if sx.is_some() || sy.is_some() { + vectorcraft_engine::cmd::scale_factors(sx.unwrap_or(100.0), sy.unwrap_or(100.0)).map_err(bad("object.scale"))?; + } + let reflect = a.get("reflect").and_then(Value::as_str); + if let Some(axis) = reflect { + vectorcraft_engine::cmd::reflect_axis(Some(&json!(axis))).map_err(bad("object.reflect"))?; + } + let shear = a.get("shear").and_then(Value::as_f64); + if let Some(sh) = shear { + vectorcraft_engine::cmd::shear_tangent(sh).map_err(bad("object.shear"))?; + } select_ids(b, a)?; // With `copy`, the first operation duplicates and the rest transform the copy (the new selection). let copy = std::cell::Cell::new(a.get("copy").and_then(Value::as_bool).unwrap_or(false)); @@ -312,17 +340,15 @@ pub(super) fn transform(b: &mut dyn Backend, a: &Args) -> Result exec(b, "object.rotate", with(json!({"angle": r})))?; done.push("rotate"); } - let s = a.get("scale").and_then(Value::as_f64); - let (sx, sy) = (a.get("scaleX").and_then(Value::as_f64).or(s), a.get("scaleY").and_then(Value::as_f64).or(s)); if sx.is_some() || sy.is_some() { exec(b, "object.scale", with(json!({"sx": sx.unwrap_or(100.0), "sy": sy.unwrap_or(100.0)})))?; done.push("scale"); } - if let Some(axis) = a.get("reflect").and_then(Value::as_str) { + if let Some(axis) = reflect { exec(b, "object.reflect", with(json!({"axis": axis})))?; done.push("reflect"); } - if let Some(sh) = a.get("shear").and_then(Value::as_f64) { + if let Some(sh) = shear { exec(b, "object.shear", with(json!({"angle": sh})))?; done.push("shear"); } diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index b6da21331e..4ff7aacecd 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -143,7 +143,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} opens SVG Options; with params = document.export {path?, svg?: {…SVG options}, range?…} (a .svgz path writes it gzipped)", ), - ("file.export.png", "Export As PNG…", "", "{path?, …document.export options}; no path: pick the file, then PNG Options"), + ( + "file.export.png", + "Export As PNG…", + "", + "{path?, …document.export options}; no path: pick the file, then PNG Options with supplied options retained and defaults for omitted options", + ), ( "file.exportForScreens", "Export for Screens…", @@ -161,6 +166,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ ("app.home", "Home", "", "{} shows the Home screen (new file presets, Open) over the open documents; choosing a document tab returns to it"), ("edit.preferences", "Preferences…", "Cmd+K", "{category?} open Preferences (engine: prefs.get / prefs.set / prefs.list)"), ("edit.keyboardShortcuts", "Keyboard Shortcuts…", "Cmd+Alt+Shift+K", "{}"), + ( + "view.refreshMonitorProfile", + "Refresh Monitor Profile", + "", + "{} read the display's profile for Use Monitor Profile for Canvas (monitorProfileDisplay) again on the next frame, without waiting for the 10-second reading or the 1-second display check; while a reading runs, the request waits for it to end → {requested: true}, before the profile is read (ui.inspect › displayProfile reports the reading, and readRequested while it waits); an error while the preference is off, and where nothing reads the display's profile (the web build)", + ), ( "edit.autoSpellCheck", "Auto Spell Check", @@ -233,7 +244,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} toggle drawing the gaps of the selected Live Paint groups (those livePaint.info lists) in each group's Gap Preview Color while edges show → true when on", ), - ("type.hiddenCharacters", "Show Hidden Characters", "Cmd+Alt+I", "{} toggle markers for spaces, paragraph ends and story ends"), + ( + "type.hiddenCharacters", + "Show Hidden Characters", + "Cmd+Alt+I", + "{} toggle markers for spaces, tabs, nonbreaking and fixed-width spaces, discretionary hyphens, forced line breaks, paragraph ends and story ends", + ), ("type.alignLeft", "Align left", "Cmd+Shift+L", "{} align the selected type's paragraphs (or those the Type tool's selection touches) left"), ( "type.alignCenter", @@ -260,7 +276,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.bulletsAndNumbering", "Bullets and Numbering…", "", - "{tab?: \"bullets\"|\"numbers\"} open Bullets and Numbering (More Options in the Paragraph panel's Bullets and Numbered List presets) on the paragraphs the Paragraph panel acts on, filled in with the values it shows, on that tab (without it, Numbers when the paragraphs are a numbered list, else Bullets) (dialog `bulletsAndNumbering`: tab (bullets|numbers), list (none|bullet|number: the kind of the preset picked), bullet (dot|dash|circle|square), number (arabic|upperLetters|lowerLetters|upperRoman|lowerRoman|twoDigits|threeDigits), listAlign (left|right), listLevel (1..9; 1 for paragraphs in no list), leftIndent, firstLineIndent (pt)): the type shows the dialog's values while it is open, OK runs text.setFormat with the values that changed (and the indents it shows when a preset puts the paragraphs in a list), as one undo step, and Cancel puts the type back; a preset picked for paragraphs in no list whose indents are 0 fills in 18 and -18 pt; an error with no type selected or an unknown tab", + "{tab?: \"bullets\"|\"numbers\"} open Bullets and Numbering (More Options in the Paragraph panel's Bullets and Numbered List presets) on the paragraphs the Paragraph panel acts on, filled in with the values it shows, on that tab (without it, Numbers when the paragraphs are a numbered list, else Bullets) (dialog `bulletsAndNumbering`: tab (bullets|numbers), list (none|bullet|number: the kind of the preset picked), bullet (dot|dash|circle|square), number (arabic|upperLetters|lowerLetters|upperRoman|lowerRoman|twoDigits|threeDigits), listAlign (left|right), listLevel (1..9; 1 for paragraphs in no list), leftIndent, firstLineIndent (pt), startAt (bool: the Numbers tab's Start at box, on when the paragraphs have the same number of their own, blank when those differ; on sends startNumber, off sends restartNumbering false), startNumber (1..999999999: its number, 1 until one is typed)): the type shows the dialog's values while it is open, OK runs text.setFormat with the values that changed (and the indents it shows when a preset puts the paragraphs in a list), as one undo step, and Cancel puts the type back; a preset picked for paragraphs in no list whose indents are 0 fills in 18 and -18 pt; an error with no type selected or an unknown tab", ), ( "type.convertListToText", @@ -376,6 +392,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "Cmd+Alt+Shift+F", "{} show the Character panel if it is hidden and open its font family menu, whose search field takes the keyboard focus: type to search, Enter applies the highlighted font → {field: \"fontName\"}. Without selected type (or text the Type tool edits) the panel shows, and the error says to select type first", ), + ( + "type.highlightFontSize", + "Highlight Font Size", + "", + "{} (Type › Size › Other…) show the Character panel if it is hidden and give its Font Size field the keyboard focus with its value selected (blank where the selected sizes differ): type a size and press Enter → {field: \"fontSize\"}. Without selected type (or text the Type tool edits) the panel shows, and the error says to select type first", + ), ( "type.highlightKerning", "Highlight Kerning", @@ -506,7 +528,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "window.toolsBesideCanvas", "Keep Tools Beside the Canvas", "", - "{on?: bool} dock the Tools panel between the left-side panels and the canvas (true) or at the window's left edge (false, the default), or toggle (omitted or null; any other value is an error); a floating Tools panel stays floating and docks at the chosen place when it is docked again. Kept with the workspace; a workspace saved without it docks Tools at the window's edge. Returns the new state", + "{on?: bool} dock the Tools panel between the left-side panels and the canvas (true) or at the window's left edge (false, the default), or toggle (omitted or null; any other value is an error); a floating Tools panel stays floating and docks at the chosen place when it is docked again. Dropping a floating Tools panel on the canvas's left edge, right of panels docked on the left, turns it on, and on the window's left edge turns it off; with no panels docked on the left, or in the column both edges share beside panels collapsed to icons, a drop leaves it as it is. Kept with the workspace; a workspace saved without it docks Tools at the window's edge. Returns the new state", ), ( "window.floatTools", @@ -792,7 +814,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "window.arrange.tile", "Tile", "", - "{} show every open document and each further view of one (window.newWindow) at once, edge to edge in the document area, one pane each in a grid (columns: the square root of the number of panes, rounded up), each fitted to its pane; the current window's pane takes the tools, a click in another pane makes its window the current one; the tabs stay; windows floating come back under the tabs first; with fewer than two windows open the view stays as it is; returns {tiled, panes}", + "{layout?: grid|vertical|horizontal|2up|3up|4up|6up} show the open documents and each further view of one (window.newWindow) at once, edge to edge in the document area, one pane each, each fitted to its pane: `grid` (the default) in a grid (columns: the square root of the number of panes, rounded up), `vertical` side by side in one row (Tile All Vertically), `horizontal` stacked in one column (Tile All Horizontally), `2up`, `3up`, `4up` and `6up` at most that many panes (2up and 3up side by side, 4up two by two, 6up three by two) with the other windows under their tabs: the first windows in tab order, the current window in the last pane when it is not among them; the current window's pane takes the tools, a click in another pane makes its window the current one; the tabs stay; windows floating come back under the tabs first; with fewer than two windows open the view and the layout stay as they are; any other `layout` is an error; returns {tiled, panes, layout}", ), ( "window.arrange.floatInWindow", @@ -825,11 +847,17 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "{} make the open document before the current one in tab order the current one, as a click on its tab does (before the first document it goes to the last, and from the Home screen to the last); each view window.newWindow opened is a step of its own; returns {index}, with `view` for a document with more than one view", ), ("tool.select", "Select Tool", "", "{tool: id} (see tools) → {tool}; a tool that cannot be chosen returns the error"), + ( + "tool.selectLastSelection", + "Select Last Selection Tool", + "Cmd+~", + "{} choose the selection tool chosen last (Selection, Direct Selection or Group Selection; none yet: the Selection tool), keeping the active tool when it is that tool; choosing Magic Wand, Lasso or any other tool does not change which one it chooses → {tool}. Default shortcut Ctrl+` on Windows and Linux, none on macOS, where Cmd+` switches windows", + ), ( "tool.setOption", "Tool Option", "", - "{key, value} | {values: {key: value…}}, tool?: id (default: the active tool) → the tool's options (`{}` reads them). The options a tool keeps (Liquify brush and tool options, Mirror & Cut, Puppet Warp, drawing tools…) last across tool switches and are saved with the preferences; another tool's are stored for when it is chosen", + "{key, value} | {values: {key: value…}}, tool?: id (default: the active tool) → the tool's options (`{}` or no params reads them; params that are not an object are an error). The options a tool keeps (Liquify brush and tool options, Mirror & Cut, Puppet Warp, drawing tools…) last across tool switches and are saved with the preferences; another tool's are stored for when it is chosen. Every option is checked before any is set: an option the tool doesn't have, a value of the wrong type, a number out of the tool's range or an unknown choice is an error naming the tool and the option, and nothing changes. The Live Paint tools' width and the Shape Builder's gapLength are set to the nearest end of their range instead", ), ( "tool.toggleTouchMode", @@ -872,6 +900,25 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ ("help.about", "About VectorCraft", "", "{}"), ("help.checkForUpdates", "Check for Updates…", "", "{}"), ("help.commandPalette", "Search Commands…", "Cmd+Shift+/", "{}"), + ( + "help.discover", + "VectorCraft Help…", + "F1", + "{query?: string (at most 1024 characters, VectorCraft's limit)} show the Help panel without toggling it closed; a supplied query searches tools, menu commands, and built-in tutorials; omission keeps the current search. Returns {query, results: [{kind: tool|command|tutorial, id, label, path, shortcut}], selected: index|null}", + ), + ( + "help.discover.search", + "Search", + "", + "{query: string (at most 1024 characters, VectorCraft's limit)} search tools, menu commands, and built-in tutorials and show the Help panel; empty or whitespace-only text clears the results. Returns the help.discover result", + ), + ( + "help.discover.choose", + "Select", + "", + "{index: zero-based result index} show a tool's location, a tutorial's steps in Help, or a command's menu path and shortcut without running it; an invalid index is an error. Returns {result: chosen result, location: tool location, tutorial id, or command path}", + ), + ("help.discover.back", "Back", "", "{} return from a Help result to its search results without changing the query"), ( "help.safeMode", "Safe Mode…", @@ -925,7 +972,13 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.brushOptions", "Brush Options…", "", - "{name?} (default: the selected path's brush, else the current brush) open its Brush Options, what double-clicking a brush in the Brushes panel opens (dialog `brushOptions`): Calligraphic (fields name, angle −180..180, roundness 0..100, size 0..1296 pt, angleMode/roundnessMode/sizeMode: fixed|random|pressure, angleVariation/roundnessVariation/sizeVariation), Bristle (fields name, shape, size, length, density, thickness, opacity, stiffness), Scatter (fields sizeMin/sizeMax/sizeMode, spacingMin/spacingMax/spacingMode, scatterMin/scatterMax/scatterMode, rotationMin/rotationMax/rotationMode with modes fixed|random|pressure, rotationRelativeTo: page|path), Art (fields width %, scaleMode: proportional|stretch|betweenGuides, guideStart/guideEnd % of the art length, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flipAlong, flipAcross) or Pattern (fields scale %, spacing %, fit: stretch|addSpace|approximate, flipAlong, flipAcross); Scatter, Art and Pattern also colorization: none|tints|tintsAndShades|hueShift, keyColor, and tips: true opens Colorization Tips (what each method does, beside a sample of the brush painted with it), as the Tips button beside Method does; OK runs brush.options", + "{name?} (default: the selected path's brush, else the current brush) open its Brush Options, what double-clicking a brush in the Brushes panel opens (dialog `brushOptions`): Calligraphic (fields name, angle −180..180, roundness 0..100, size 0..1296 pt, angleMode/roundnessMode/sizeMode: fixed|random|pressure, angleVariation/roundnessVariation/sizeVariation), Bristle (fields name, shape, size, length, density, thickness, opacity, stiffness), Scatter (fields sizeMin/sizeMax/sizeMode, spacingMin/spacingMax/spacingMode, scatterMin/scatterMax/scatterMode, rotationMin/rotationMax/rotationMode with modes fixed|random|pressure, rotationRelativeTo: page|path, hueJitter 0..180°), Art (fields width %, scaleMode: proportional|stretch|betweenGuides, guideStart/guideEnd % of the art length, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flipAlong, flipAcross) or Pattern (fields scale %, spacing %, fit: stretch|addSpace|approximate, flipAlong, flipAcross); Scatter, Art and Pattern also colorization: none|tints|tintsAndShades|hueShift, keyColor, and tips: true opens Colorization Tips (what each method does, beside a sample of the brush painted with it), as the Tips button beside Method does; OK runs brush.options", + ), + ( + "ui.brushObjectOptions", + "Options of Selected Object…", + "", + "{} open the Brushes panel menu's Options of Selected Object (dialog `brushOptions` with `__object`): the Brush Options of the brush that the first selected brushed path paints with, at that path's own settings, without the name field; Art shows width, widthMax/widthMode, flipAlong, flipAcross and overlap, and Pattern scale, spacing, flipAlong, flipAcross and fit, each with colorization; OK runs brush.objectOptions on the brushed paths selected when it opened, with the values changed since it opened (one end of a range or one colorization field changed leaves each path's other values as they are), and the brush stays as it is. An error with nothing painted with a brush selected, for paths painted with brushes of different types and for a bristle brush", ), ( "ui.graphicStyleOptions", @@ -973,7 +1026,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.symbolOptions", "Symbol Options…", "F8", - "{name?} open Symbol Options (dialog `symbolOptions`, fields `name`, `exportType`: movieClip|graphic, `registration` 0..8). Without `name` and with a selection: New Symbol (default name the first free \"New Symbol\"/\"New Symbol N\", Export Type Movie Clip, Registration centre); OK runs symbol.new {name, exportType, registration}. With `edit: true` or `name`: edit that symbol; OK runs symbol.options {name, newName?, exportType, registration}", + "{name?, edit?, keepArt?: false} open Symbol Options (dialog `symbolOptions`, fields `name`, `exportType`: movieClip|graphic, `registration` 0..8). Without `name` and with a selection: New Symbol (default name the first free \"New Symbol\"/\"New Symbol N\", Export Type Movie Clip, Registration centre); OK runs symbol.new {name, exportType, registration}, with keepArt: true when it was opened with keepArt: true (the selection stays ordinary art). With `edit: true` or `name`: edit that symbol; OK runs symbol.options {name, newName?, exportType, registration}; keepArt: true is then an error", ), ( "tool.options", @@ -1097,7 +1150,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.navigatorPanelOptions", "Panel Options…", "", - "{color?: #rrggbb or a preset name (Light Red, the default, then the layer colors such as \"Light Blue\"), solidDashes?: bool (Draw Dashed Lines as Solid Lines, off by default: the Navigator's thumbnail draws dashed strokes without their dashes; the canvas, printing and exports keep them)} set the Navigator panel's options, the color its view box is drawn in and solid dashes (kept with the UI state) → {color, solidDashes}; with neither, open its Panel Options (dialog `navigatorPanelOptions`, fields color, solidDashes; OK sets them); an error for a value that is not a color or not true or false, which changes nothing", + "{color?: #rrggbb or a preset name (Light Red, the default, then the layer colors such as \"Light Blue\"), solidDashes?: bool (Draw Dashed Lines as Solid Lines, off by default: the Navigator's thumbnail draws dashed strokes without their dashes; the canvas, printing and exports keep them), viewArtboardContentsOnly?: bool (View Artboard Contents Only in the panel menu, on by default and for UI state saved without it: the thumbnail fits the artboards and draws only the art inside them, cut at each artboard's edges; off, it also shows the art on the pasteboard)} set the Navigator panel's options, the color its view box is drawn in, solid dashes and artboard contents only (kept with the UI state) → {color, solidDashes, viewArtboardContentsOnly}; with none, open its Panel Options (dialog `navigatorPanelOptions`, fields color, solidDashes; OK sets them); an error for a value that is not a color or not true or false, which changes nothing", ), ( "ui.layersExpand", @@ -1147,6 +1200,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{highlight?: none|rasterizedRegions|transparentObjects|allAffected|expandedPatterns|outlinedStrokes|outlinedText|allRasterized, overprints?: preserve|simulate|discard, preset?: name (loads its options), options?: {option keys, over the preset's}, showOptions?} set the Flattener Preview panel (ui.inspect: ui.flattener_preview), show it and refresh its snapshot → what flattener.preview answers for it", ), + ( + "ui.foldPreview", + "Fold Preview", + "", + "{amount?: 0..1 (how far the blank is folded), view?: front|back|left|right|top|bottom|threeQuarter, rotateX?: deg -180..180 (the top toward the viewer), rotateY?: deg -180..180 (the right side toward the viewer), zoom?: 0.1..8 (1 fits the folded blank), perspective?: deg 0..160 (field of view; 0 for none), inside?: #rrggbb, the name of a swatch with a plain color, or empty for white (the board's inside), showFoldLines?: bool, base?: [x, y] (the panel under this point stays in place; an error when it is in no panel) or null (the largest panel)} set the Fold Preview window (ui.inspect: ui.fold_preview), which folds the blank that the document's shown fold lines make (addon.packaging.fold) with the document's art printed on the outside, show it and draw it again; view and zoom also center the view. A value of the wrong kind or out of range is an error and sets nothing → the window's settings and frame: the last frame's {width, height (pixels), foldMs, drawMs} or null", + ), ( "ui.copyScriptConsole", "Copy Script Console", @@ -1264,7 +1323,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.expandDialog", "Expand…", "", - "{} open Expand for the selection (dialog `expand`, fields object, fill, stroke (all on; one the selection has nothing for is disabled, see object.expand.info), gradient: objects|mesh, steps 1..1000 (255)): OK runs object.expand with them as one undo step; dimmed, and an error, while the selection has an appearance effect.expandAppearance expands (object.expand.info's appearance)", + "{immediate?: bool (false)} open Expand for the selection (dialog `expand`, fields object, fill, stroke (all on; one the selection has nothing for is disabled, see object.expand.info), gradient: objects|mesh, steps 1..1000 (255), or the choices OK last expanded with since the app started): OK runs object.expand with them as one undo step and keeps them until the app quits; immediate: true (the menu item chosen with Alt/Option) runs object.expand at once with those choices (the defaults before any OK), and opens the dialog instead when none of them has something to expand in the selection; dimmed, and an error, while the selection has an appearance effect.expandAppearance expands (object.expand.info's appearance)", ), ( "attributes.openUrl", @@ -1380,6 +1439,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} switch the Color panel's R, G and B between percent and 0 to 255, as a double-click right of an RGB field does (ui.colorPanel {rgbPercent}); the color does not change, and the choice is kept with the preferences; a parameter is an error and changes nothing → true when they show in percent", ), + ( + "ui.colorWheel", + "Color Wheel Options", + "", + "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, and pick the box's channel, as Box Channel does: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); keys left out keep their values, params that are not an object, another key or a value off the list are an error and change nothing, both are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel}", + ), ( "ui.savePdfDialog", "Save PDF Dialog", @@ -1635,6 +1700,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{path? | data?: the file's text} read an action set file (.vcactions) at path, else a picked one, and add its set after the Actions panel's sets; a set named like one in the panel gets the next free number (Print 2), and the other sets stay. Files of another version, over 8 MiB, with more than 1,000 actions or with an action of more than 10,000 steps are refused, and so is any set, .aia ones too, that Save Actions… would write larger than 8 MiB (a file with less white space, or a name that gets a number); the panel menu's Load Actions… (disabled where there is no open dialog, the web) → {set: index, name, actions: n}. An action set another app saved as text (.aia, starting /version; read with actionSet.read) comes in with its actions. A step with a label and no recorded values comes in when exactly one menu command has that label (in English or the interface language, any case, no final …), and that command is directly in a top menu, can be recorded in actions, is what its menu bar item runs with no values and opens no dialog (never a submenu's item, a file or document command, Paste, Undo, Redo or an add-on's command), with no params and excluded from playback when it is off in the file. A Set Selection step (found by its internal name, whatever its label) comes in as select.byNote {note, caseSensitive, wholeWord} when it has exactly three recorded values: text (ustring, UTF-8; 1 to 1,024 bytes once trimmed), word and case (boolean, 0 or 1); with any other values it is left out. The other steps, every other step with no label and every other step recorded with values (a recorded menu item too) among them, are left out → {set, name, actions, skipped: [{action, step: its label, else its name}] (the first 1,000), leftOut: n}, and the status bar says how many were left out; a set with no name takes the file's name, else Actions; a file actionSet.read marks truncated is refused, and text that starts /version and isn't an action set gives \"not an action set file\"", ), + ( + "ui.actionSet.replace", + "Replace Actions…", + "", + "{path? | data?: the file's text} read an action set file at path, else a picked one, as ui.actionSet.load reads it (.vcactions and .aia, with the same limits, errors and reports of left-out steps and unknown commands), and replace every set in the Actions panel, the built-in Default Actions set included, with the file's set, which keeps its name. The set becomes current and selected, the panel's selected action and step and its expanded actions are cleared, and an open Set Options, New Action, Batch or step dialog that names a set closes; when the panel already holds only a set that saves alike, in that state, nothing changes, the set keeps its ids and changed is false. Omitted params count as {}. Params of another type, another key, a path or data that is not a string, a file that can't be read or is refused, a canceled pick, or a replace while an action records or plays (also while it waits at a stop) is an error and changes nothing. No undo step is recorded. The panel menu's Replace Actions… (disabled where there is no open dialog, the web, and while an action records or plays) → {changed, set: 0, name, actions: n, unknownCommands?, unknownCount?, skipped?, leftOut?}", + ), ( "ui.actionSet.delete", "Delete Action Sets", @@ -1664,7 +1735,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.epsOptionsDialog", "EPS Options Dialog", "", - "{path?, useArtboards?, range?, …document.exportEps options} open EPS Options (dialog `epsOptions`: fields = these options over the ones used last); OK checks them, remembers them and writes path (else asks). Export As… → EPS opens it too", + "{path?, useArtboards?, range?, …document.exportEps options} open EPS Options (dialog `epsOptions`: fields = these options over the ones used last; Custom… sets `flattener`, which a flattenerPreset given without it drops); OK checks them, remembers them and writes path (else asks). Export As… → EPS opens it too", ), ( "file.saveForWeb", diff --git a/crates/metafile/src/lib.rs b/crates/metafile/src/lib.rs index 1ba560d05e..8e5f53ce41 100644 --- a/crates/metafile/src/lib.rs +++ b/crates/metafile/src/lib.rs @@ -1,6 +1,7 @@ //! Windows metafiles: hand-written EMF and WMF writers and readers. //! -//! [`export`] writes the visible art over one region of a document (an artboard) as a metafile: +//! [`export`] writes the visible art over one region of a document (an artboard) as a metafile, +//! and [`export_regions`] one metafile per region: //! //! - **EMF**: paths keep their Bézier curves, fills are solid brushes, strokes geometric pens with //! their width, caps, joins, miter limit and dashes; strokes a pen can't draw (aligned inside or @@ -81,20 +82,36 @@ pub struct Output { /// not); template layers, hidden objects and guides are left out. Raster effects should be turned /// into images before (the engine does); the ones left are reported and left out. pub fn export(doc: &Document, region: Rect, kind: Kind) -> Result { - let r = region.abs(); - if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) || r.width() <= 0.0 || r.height() <= 0.0 { + Ok(export_regions(doc, &[region], kind)?.pop().unwrap_or_default()) +} + +/// Write the visible art of `doc` over each of `regions` as `kind`, one metafile per region in the +/// same order, each as [`export`] writes it over that region. The live effects are applied once +/// for all of them. When any region is empty, nothing is written and the result is an error. +pub fn export_regions(doc: &Document, regions: &[Rect], kind: Kind) -> Result, String> { + let regions: Vec = regions.iter().map(|r| r.abs()).collect(); + if regions.iter().any(|r| ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) || r.width() <= 0.0 || r.height() <= 0.0) { return Err("the export region is empty".into()); } + if regions.is_empty() { + return Ok(Vec::new()); + } // The scene writes layers that do not print and leaves hidden layers and objects out. let layers = vectorcraft_effects::WrittenLayers { hidden: false, non_printing: true, hidden_objects: false }; let baked = vectorcraft_effects::bake_document_placing_symbols(doc, kind == Kind::Emf, layers); let doc = baked.as_ref().unwrap_or(doc); - let (ops, mut warnings) = scene::Scene::new(doc, r, kind == Kind::Emf).run(); - let bytes = match kind { - Kind::Emf => emf::write(&ops, r, doc.info_title()), - Kind::Wmf => wmf::write(&ops, r, &mut warnings), - }; - Ok(Output { bytes, warnings }) + let outputs = regions + .into_iter() + .map(|r| { + let (ops, mut warnings) = scene::Scene::new(doc, r, kind == Kind::Emf).run(); + let bytes = match kind { + Kind::Emf => emf::write(&ops, r, doc.info_title()), + Kind::Wmf => wmf::write(&ops, r, &mut warnings), + }; + Output { bytes, warnings } + }) + .collect(); + Ok(outputs) } /// A metafile read into a document. diff --git a/crates/metafile/src/tests.rs b/crates/metafile/src/tests.rs index 2314ccb637..658628f107 100644 --- a/crates/metafile/src/tests.rs +++ b/crates/metafile/src/tests.rs @@ -396,6 +396,177 @@ fn hidden_and_offboard_art_is_left_out() { assert!(export(&d, Rect::new(0.0, 0.0, 0.0, 10.0), Kind::Emf).is_err(), "an empty region"); } +/// One metafile of `doc` over `region`, applying the live effects for this region alone: what +/// [`export`] did for each region before [`export_regions`] applied them once for all regions. +fn export_baking_each_region(doc: &Document, region: Rect, kind: Kind) -> Result { + let r = region.abs(); + if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) || r.width() <= 0.0 || r.height() <= 0.0 { + return Err("the export region is empty".into()); + } + let layers = vectorcraft_effects::WrittenLayers { hidden: false, non_printing: true, hidden_objects: false }; + let baked = vectorcraft_effects::bake_document_placing_symbols(doc, kind == Kind::Emf, layers); + let doc = baked.as_ref().unwrap_or(doc); + let (ops, mut warnings) = crate::scene::Scene::new(doc, r, kind == Kind::Emf).run(); + let bytes = match kind { + Kind::Emf => crate::emf::write(&ops, r, doc.info_title()), + Kind::Wmf => crate::wmf::write(&ops, r, &mut warnings), + }; + Ok(Output { bytes, warnings }) +} + +/// A Zig Zag effect with its default settings. +fn zig_zag() -> vectorcraft_doc::Effect { + vectorcraft_doc::Effect { id: "distort.zigZag".into(), params: Default::default(), visible: true } +} + +/// `boards` 100 pt squares side by side, each holding `paths` rectangles with a live Zig Zag +/// and a gradient-filled one, and every second one an instance of a symbol whose art has a Zig +/// Zag too; `boards` regions, one over each square. +fn zig_zag_boards(boards: usize, paths: usize) -> (Document, Vec) { + let mut d = Document::new(100.0 * boards as f64, 100.0); + let mut art = path(shapes::rectangle(Rect::new(0.0, 0.0, 30.0, 20.0)), blue(), red(), 1.0); + art.appearance.effects.push(zig_zag()); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Zig".into(), art: Arc::new(art) }); + let g = Paint::Gradient(Box::new(GradientPaint::new(Gradient::default()))); + for b in 0..boards { + let x = 100.0 * b as f64; + for i in 0..paths { + let at = (i % 9) as f64 * 9.0; + let mut n = path(shapes::rectangle(Rect::new(x + at + 2.0, at + 2.0, x + at + 20.0, at + 15.0)), red(), blue(), 0.5); + n.appearance.effects.push(zig_zag()); + add(&mut d, n); + } + add(&mut d, path(shapes::rectangle(Rect::new(x + 60.0, 60.0, x + 90.0, 90.0)), g.clone(), Paint::None, 0.0)); + if b % 2 == 1 { + let inst = Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: "Zig".into(), xf: Affine::translate((x + 50.0, 10.0)) }); + add(&mut d, inst); + } + } + let regions = (0..boards).map(|b| Rect::new(100.0 * b as f64, 0.0, 100.0 * (b + 1) as f64, 100.0)).collect(); + (d, regions) +} + +/// Each region's metafile is byte for byte, and warning for warning, what a separate export of +/// that region writes, in EMF and WMF, in the regions' order and in reverse. +#[test] +fn export_regions_writes_what_each_region_writes_alone() { + let (d, mut regions) = zig_zag_boards(3, 2); + let layers = vectorcraft_effects::WrittenLayers { hidden: false, non_printing: true, hidden_objects: false }; + assert!(vectorcraft_effects::bake_document_placing_symbols(&d, true, layers).is_some(), "the document has live effects to apply"); + for _ in 0..2 { + for kind in [Kind::Emf, Kind::Wmf] { + let outs = export_regions(&d, ®ions, kind).unwrap(); + assert_eq!(outs.len(), regions.len()); + for (r, out) in regions.iter().zip(&outs) { + let alone = export_baking_each_region(&d, *r, kind).unwrap(); + assert!(out.bytes == alone.bytes, "{kind:?} over {r:?}: the bytes differ"); + assert_eq!(out.warnings, alone.warnings, "{kind:?} over {r:?}"); + let one = export(&d, *r, kind).unwrap(); + assert!(one.bytes == alone.bytes, "{kind:?} over {r:?}: export's bytes differ"); + assert_eq!(one.warnings, alone.warnings, "{kind:?} over {r:?}"); + } + if kind == Kind::Wmf { + assert!(outs.iter().all(|o| o.warnings.iter().any(|w| w.contains("gradients"))), "{:?}", outs[0].warnings); + } + } + regions.reverse(); + } +} + +/// An empty region among valid ones writes nothing and is the one error; no region writes no +/// metafile. +#[test] +fn export_regions_with_an_empty_region_writes_nothing() { + let (d, regions) = zig_zag_boards(2, 1); + for kind in [Kind::Emf, Kind::Wmf] { + for empty in [Rect::new(10.0, 10.0, 10.0, 50.0), Rect::new(0.0, 0.0, f64::NAN, 10.0), Rect::new(0.0, 0.0, f64::INFINITY, 10.0)] { + let with_empty = [regions[0], empty, regions[1]]; + assert_eq!(export_regions(&d, &with_empty, kind).map(|o| o.len()), Err("the export region is empty".to_string()), "{kind:?}"); + } + assert!(export_regions(&d, &[], kind).unwrap().is_empty(), "{kind:?}"); + // A region given right to left or bottom to top is the same region. + let flipped = Rect::new(regions[1].x1, regions[1].y1, regions[1].x0, regions[1].y0); + let outs = export_regions(&d, &[flipped], kind).unwrap(); + assert!(outs[0].bytes == export(&d, regions[1], kind).unwrap().bytes, "{kind:?}"); + } +} + +/// The CPU time all of this process's threads have used, from Linux's scheduler statistics; `None` +/// elsewhere. +fn process_cpu() -> Option { + let mut ns = 0u64; + for task in std::fs::read_dir("/proc/self/task").ok()? { + let stat = std::fs::read_to_string(task.ok()?.path().join("schedstat")).ok()?; + ns += stat.split_whitespace().next()?.parse::().ok()?; + } + Some(std::time::Duration::from_nanos(ns)) +} + +/// The time `f` takes: this process's CPU time where Linux reports it, otherwise the wall clock. +fn time(f: impl FnOnce() -> T) -> (std::time::Duration, T) { + match process_cpu() { + Some(before) => { + let t = f(); + (process_cpu().map_or(std::time::Duration::ZERO, |after| after.saturating_sub(before)), t) + } + None => { + let start = std::time::Instant::now(); + let t = f(); + (start.elapsed(), t) + } + } +} + +/// Timings of an export of 1, 2 and 8 artboards that applies the live effects once for each +/// artboard and of [`export_regions`], which applies them once, in EMF and WMF: 500 rectangles with +/// a live Zig Zag on each artboard. The two take turns going first, 7 runs each, and every run's +/// files are compared. Ignored by default; it prints the median, fastest and slowest run and sets +/// no bound on them: +/// `cargo test --release -p vectorcraft-metafile --lib export_regions_perf -- --ignored --nocapture`. +#[test] +#[ignore = "a benchmark: run with --ignored --nocapture"] +fn export_regions_perf() { + const RUNS: usize = 7; + let ms = |d: std::time::Duration| d.as_secs_f64() * 1000.0; + eprintln!("export_regions_perf: {}", if process_cpu().is_some() { "process CPU time" } else { "wall clock" }); + eprintln!("export_regions_perf: {:>6} {:<4} {:>32} {:>32}", "boards", "kind", "bake per board ms (min-max)", "bake once ms (min-max)"); + for boards in [1, 2, 8] { + let (d, regions) = zig_zag_boards(boards, 500); + for kind in [Kind::Emf, Kind::Wmf] { + let each = || regions.iter().map(|r| export_baking_each_region(&d, *r, kind).unwrap()).collect::>(); + let once = || export_regions(&d, ®ions, kind).unwrap(); + let (mut old, mut new) = (Vec::new(), Vec::new()); + for run in 0..RUNS { + let ((to, a), (tn, b)) = if run % 2 == 0 { + let o = time(each); + (o, time(once)) + } else { + let n = time(once); + (time(each), n) + }; + old.push(to); + new.push(tn); + assert_eq!(a.len(), b.len()); + for (a, b) in a.iter().zip(&b) { + assert!(a.bytes == b.bytes && a.warnings == b.warnings, "{boards} boards, {kind:?}"); + } + } + old.sort(); + new.sort(); + eprintln!( + "export_regions_perf: {boards:>6} {:<4} {:>12.1} ({:>8.1}-{:>8.1}) {:>12.1} ({:>8.1}-{:>8.1})", + kind.id(), + ms(old[RUNS / 2]), + ms(old[0]), + ms(old[RUNS - 1]), + ms(new[RUNS / 2]), + ms(new[0]), + ms(new[RUNS - 1]), + ); + } + } +} + #[test] fn an_instance_whose_art_reaches_the_artboard_is_written() { // The symbol's red rectangle, (100, 100) to (140, 140), drawn from (-50, -50): on the artboard, diff --git a/crates/pathops/src/addons/pathtools.rs b/crates/pathops/src/addons/pathtools.rs index 87cc5ba56f..d8ad6ae8e4 100644 --- a/crates/pathops/src/addons/pathtools.rs +++ b/crates/pathops/src/addons/pathtools.rs @@ -4,10 +4,12 @@ //! tool shows over a path, open paths lengthened or shortened at an end ([`extend`]), the places //! where paths cross ([`crossings`]), the stretches between them ([`spans`]), anchors slid along //! their path ([`slide`]), touching edges merged ([`shared_edge`]), paths divided into dashes -//! ([`divide_dashes`]), the common tangents of two convex outlines ([`common_tangents`]), the +//! ([`divide_dashes`]), two circles joined by a smooth bridge ([`smooth_bridge`]), the common +//! tangents of two convex outlines ([`common_tangents`]), the //! Parametric Shape Tool's shapes ([`shapes`]) and the circles that touch two or three shapes //! ([`tangent_circles`]). +mod bridge; mod crossings; mod dashes; mod extend; @@ -25,6 +27,7 @@ use std::collections::BTreeSet; use kurbo::{CubicBez, ParamCurve, ParamCurveArclen, ParamCurveNearest, Point, Vec2}; use vectorcraft_geom::{Anchor, AnchorKind, PathData, SubPath}; +pub use bridge::{BridgeError, circle_of, smooth_bridge}; pub use crossings::{MAX_CROSSED_BY_SEGMENTS, MAX_CROSSING_SEGMENTS, Place, Work, crossings, crossings_on, crossings_on_within, insert_at}; pub use dashes::{DashSpec, Piece, divide_dashes}; pub use extend::{ExtendMode, extend_length_to, extend_open}; diff --git a/crates/pathops/src/addons/pathtools/bridge.rs b/crates/pathops/src/addons/pathtools/bridge.rs new file mode 100644 index 0000000000..43ee629a91 --- /dev/null +++ b/crates/pathops/src/addons/pathtools/bridge.rs @@ -0,0 +1,365 @@ +//! Smooth Bridge: two circles joined into one outline by two concave arcs, each touching both +//! circles from outside, so the outline runs on smoothly from each circle into the bridge. + +use std::f64::consts::{FRAC_PI_2, PI, SQRT_2, TAU}; + +use kurbo::{CubicBez, ParamCurve, Point, Shape, Vec2}; +use vectorcraft_geom::{Anchor, AnchorKind, PathData, SubPath}; + +use super::Circle; + +/// How far (as a share of the radius) a path's outline may stray from a circle and still be read +/// as that circle. +const ROUND: f64 = 1e-3; +/// Points [`circle_of`] checks on each segment, its ends included. +const SAMPLES: usize = 9; + +/// Why [`smooth_bridge`] makes no outline. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BridgeError { + /// One circle is inside the other (or they share a center). + Inside, + /// The circles are too far apart for the radius: the two arcs would not reach both circles, + /// or would cross before they do. + TooFar, + /// A radius or circle that is not a finite size above 0, or an outline too large for `f64`. + Bad, +} + +/// The circle `path` draws: one closed subpath whose outline stays within 0.1% of its radius of +/// a circle all the way around, once. `None` for any other path. +pub fn circle_of(path: &PathData) -> Option { + let [sp] = path.subpaths.as_slice() else { return None }; + if !sp.closed || sp.anchors.len() < 2 { + return None; + } + let b = path.bounds()?; + let (w, h) = (b.width(), b.height()); + if !(w > 0.0 && h > 0.0 && w.is_finite() && h.is_finite()) || (w - h).abs() > ROUND * w.max(h) { + return None; + } + let (center, radius) = (b.center(), (w + h) / 4.0); + let off = |q: Point| (q.distance(center) - radius).abs() > ROUND * radius; + for k in 0..sp.segment_count() { + let seg = sp.segment(k); + if (0..SAMPLES).any(|i| off(seg.eval(i as f64 / (SAMPLES - 1) as f64))) { + return None; + } + } + // Around once: a path going around twice, or back on itself, encloses a different area. + let area = path.to_bezpath().area().abs(); + ((area - PI * radius * radius).abs() <= 4.0 * ROUND * area).then_some(Circle { center, radius }) +} + +/// The outline of circles `a` and `b` joined by two arcs of radius `radius` (pt), one on each +/// side of the line through their centers, each touching both circles from outside. The outline +/// runs around `a` on its side away from `b`, along one arc, around `b` on its side away from `a` +/// and back along the other arc; every anchor is smooth, as each arc and the circle it meets share +/// a tangent there. Overlapping and touching circles are joined too. A larger radius makes a wider, +/// gentler bridge; farther apart circles make a narrower one, until the arcs would cross. +pub fn smooth_bridge(a: Circle, b: Circle, radius: f64) -> Result { + let finite = |x: f64| x.is_finite() && x > 0.0; + let points = [a.center, b.center].iter().all(|c| c.x.is_finite() && c.y.is_finite()); + if !finite(radius) || !finite(a.radius) || !finite(b.radius) || !points { + return Err(BridgeError::Bad); + } + let axis = b.center - a.center; + // `f64::hypot`: `Vec2::hypot` squares the length, which overflows above about 1e154 pt. + let d = axis.x.hypot(axis.y); + if d + a.radius.min(b.radius) <= a.radius.max(b.radius) * (1.0 + 1e-9) { + return Err(BridgeError::Inside); + } + // The arcs' centers are `radius` outside both circles: where circles about the two centers, + // `radius` larger than each, cross. + let (ra, rb) = (radius + a.radius, radius + b.radius); + if !ra.is_finite() || !rb.is_finite() { + return Err(BridgeError::Bad); + } + // Halves and no squares, so no step overflows while the lengths fit in `f64`. + let half = ra / 2.0 + rb / 2.0; + if d / 2.0 > half { + return Err(BridgeError::TooFar); + } + let along = d / 2.0 + (ra - rb) / d * half; + let across = (ra - along).max(0.0).sqrt() * (ra / 2.0 + along / 2.0).max(0.0).sqrt() * SQRT_2; + if !along.is_finite() || !across.is_finite() { + return Err(BridgeError::Bad); + } + // Each arc runs between its points on `a` and `b`, which lie towards the two centers from the + // arc's center. Its point nearest the axis is the foot of its center on the axis when that foot + // is between the two centers, else one of its ends, which are off the axis. So the two arcs + // cross, leaving no neck, only when that foot is between the centers and nearer to the arc's + // center than its radius. + if along > 0.0 && along < d && across <= radius * (1.0 + 1e-9) { + return Err(BridgeError::TooFar); + } + let u = axis / d; + let n = Vec2::new(-u.y, u.x); + let mut segs = vec![]; + // Each side's arc center and where its arc touches `a` and `b`. + let side = |s: f64| { + let p = a.center + u * along + n * (s * across); + (p, a.center + (p - a.center) * (a.radius / ra), b.center + (p - b.center) * (b.radius / rb)) + }; + let ((p1, a1, b1), (p2, a2, b2)) = (side(1.0), side(-1.0)); + arc(&mut segs, a.center, a.radius, a1, a2, Some(-u)); + arc(&mut segs, p2, radius, a2, b2, None); + arc(&mut segs, b.center, b.radius, b2, b1, Some(u)); + arc(&mut segs, p1, radius, b1, a1, None); + let count = segs.len(); + let anchors: Vec = (0..count) + .map(|i| { + let (prev, seg) = (segs[(i + count - 1) % count], segs[i]); + Anchor { p: seg.p0, h_in: prev.p2, h_out: seg.p1, kind: AnchorKind::Smooth } + }) + .collect(); + let finite_point = |p: Point| p.x.is_finite() && p.y.is_finite(); + if !anchors.iter().all(|q| finite_point(q.p) && finite_point(q.h_in) && finite_point(q.h_out)) { + return Err(BridgeError::Bad); + } + Ok(SubPath::new(anchors, true)) +} + +/// Append to `out` the arc of the circle about `center` with radius `r` from `from` to `to` (both +/// on it): through the direction `through` from the center when given, else the shorter way. In +/// cubics of at most a quarter turn each, `from` exactly at the start and `to` at the end. +fn arc(out: &mut Vec, center: Point, r: f64, from: Point, to: Point, through: Option) { + let angle = |q: Vec2| q.y.atan2(q.x); + let start = angle(from - center); + // The turn from `from` to `to` counter-clockwise (in the y-up sense), 0 to 2π. + let ccw = (angle(to - center) - start).rem_euclid(TAU); + let sweep = match through { + Some(dir) if (angle(dir) - start).rem_euclid(TAU) <= ccw => ccw, + Some(_) => ccw - TAU, + None if ccw > PI => ccw - TAU, + None => ccw, + }; + let pieces = (sweep.abs() / FRAC_PI_2).ceil().max(1.0) as usize; + let step = sweep / pieces as f64; + // Handle length that makes a cubic follow the arc of `step`, signed with its direction. + let k = 4.0 / 3.0 * (step / 4.0).tan() * r; + let on = |t: f64| center + Vec2::new(t.cos(), t.sin()) * r; + let tangent = |t: f64| Vec2::new(-t.sin(), t.cos()); + for i in 0..pieces { + let (t0, t1) = (start + step * i as f64, start + step * (i + 1) as f64); + let p0 = if i == 0 { from } else { on(t0) }; + let p3 = if i + 1 == pieces { to } else { on(t1) }; + out.push(CubicBez::new(p0, p0 + tangent(t0) * k, p3 - tangent(t1) * k, p3)); + } +} + +#[cfg(test)] +mod tests { + use vectorcraft_geom::shapes; + + use super::*; + + fn circle(x: f64, y: f64, r: f64) -> Circle { + Circle { center: Point::new(x, y), radius: r } + } + + /// Every point the outline passes through, 32 to a segment. + fn outline(sp: &SubPath) -> Vec { + (0..sp.segment_count()).flat_map(|k| (0..32).map(move |i| sp.segment(k).eval(i as f64 / 32.0))).collect() + } + + /// The outline crosses the vertical line at `x` at these y values, top to bottom. + fn crossings_at(sp: &SubPath, x: f64) -> Vec { + let pts = outline(sp); + let mut ys: Vec = (0..pts.len()) + .filter_map(|i| { + let (p, q) = (pts[i], pts[(i + 1) % pts.len()]); + ((p.x - x) * (q.x - x) <= 0.0 && p.x != q.x).then(|| p.y + (q.y - p.y) * (x - p.x) / (q.x - p.x)) + }) + .collect(); + ys.sort_by(f64::total_cmp); + ys + } + + /// The bridge's width at `x`, from the outline's crossings there. + fn width_at(sp: &SubPath, x: f64) -> f64 { + let ys = crossings_at(sp, x); + ys.last().unwrap() - ys.first().unwrap() + } + + fn assert_smooth(sp: &SubPath) { + for a in sp.anchors.iter() { + let (i, o) = (a.p - a.h_in, a.h_out - a.p); + assert!(i.hypot() > 1e-6 && o.hypot() > 1e-6, "both handles at {a:?}"); + assert!(i.cross(o).abs() <= 1e-9 * i.hypot() * o.hypot() && i.dot(o) > 0.0, "the outline turns at {a:?}"); + assert_eq!(a.kind, AnchorKind::Smooth); + } + } + + /// Each point of the outline is on circle `c` or outside it. + fn outside(sp: &SubPath, c: Circle) -> bool { + outline(sp).iter().all(|p| p.distance(c.center) >= c.radius - 1e-3) + } + + #[test] + fn two_equal_circles_join_with_a_neck_narrower_than_the_circles() { + let (a, b) = (circle(0.0, 0.0, 20.0), circle(60.0, 0.0, 20.0)); + let sp = smooth_bridge(a, b, 20.0).unwrap(); + assert!(sp.closed); + assert_smooth(&sp); + // The arcs' centers are 40 from each circle's center: (30, ±√700), so the neck at x = 30 is + // 2 × (√700 − 20) wide. + let neck = 2.0 * (700f64.sqrt() - 20.0); + assert!((width_at(&sp, 30.0) - neck).abs() < 1e-2, "{}", width_at(&sp, 30.0)); + assert!(width_at(&sp, 30.0) < width_at(&sp, 10.0)); + // Around each circle on its far side, and symmetric. + let ys = crossings_at(&sp, -10.0); + assert!((ys[0] + 300f64.sqrt()).abs() < 1e-2 && (ys[1] - 300f64.sqrt()).abs() < 1e-2, "{ys:?}"); + assert!((width_at(&sp, 50.0) - width_at(&sp, 10.0)).abs() < 1e-2); + let b = PathData::single(sp).bounds().unwrap(); + // Within the cubics' own error from a true circle (about 0.03% of the radius). + assert!((b.x0 + 20.0).abs() < 1e-2 && (b.x1 - 80.0).abs() < 1e-2 && (b.y1 - 20.0).abs() < 1e-2, "{b:?}"); + } + + #[test] + fn the_arcs_touch_both_circles_and_run_on_from_them() { + for (a, b, r) in [ + (circle(0.0, 0.0, 20.0), circle(60.0, 0.0, 20.0), 20.0), + (circle(10.0, 5.0, 30.0), circle(70.0, 40.0, 8.0), 40.0), + (circle(0.0, 0.0, 20.0), circle(30.0, 0.0, 15.0), 10.0), + ] { + let sp = smooth_bridge(a, b, r).unwrap(); + assert_smooth(&sp); + // The outline goes around the outside of both circles, never into either. + assert!(outside(&sp, a) && outside(&sp, b)); + // On each circle the outline leaves along the circle's tangent, where an arc takes over + // as well: two anchors on each circle are where an arc meets it. + for c in [a, b] { + let on: Vec<_> = sp.anchors.iter().filter(|q| (q.p.distance(c.center) - c.radius).abs() < 1e-6).collect(); + assert!(on.len() >= 2, "{}", on.len()); + for q in on { + let radial = q.p - c.center; + assert!(radial.dot(q.h_out - q.p).abs() <= 1e-6 * radial.hypot() * (q.h_out - q.p).hypot(), "{q:?}"); + } + } + assert!(sp.anchors.len() <= 12, "{}", sp.anchors.len()); + // Every segment off the two circles is part of an arc of radius `r` that touches both + // circles from outside: its center is `r` farther than each circle's radius from it. + let on = |q: Point, c: Circle| (q.distance(c.center) - c.radius).abs() < 1e-3; + let mut arcs = 0; + for k in 0..sp.segment_count() { + let seg = sp.segment(k); + let (p0, pm, p1) = (seg.eval(0.0), seg.eval(0.5), seg.eval(1.0)); + if on(pm, a) || on(pm, b) { + continue; + } + arcs += 1; + let (center, radius) = circumcircle(p0, pm, p1); + assert!((radius - r).abs() < 1e-2 * r, "radius {radius} for {r}"); + assert!((center.distance(a.center) - (r + a.radius)).abs() < 1e-2 * r, "touches {a:?}"); + assert!((center.distance(b.center) - (r + b.radius)).abs() < 1e-2 * r, "touches {b:?}"); + } + assert!((2..=4).contains(&arcs), "{arcs}"); + } + } + + /// The circle through three points: its center and radius. + fn circumcircle(p: Point, q: Point, s: Point) -> (Point, f64) { + let d = 2.0 * (p.x * (q.y - s.y) + q.x * (s.y - p.y) + s.x * (p.y - q.y)); + let sq = |v: Point| v.x * v.x + v.y * v.y; + let x = (sq(p) * (q.y - s.y) + sq(q) * (s.y - p.y) + sq(s) * (p.y - q.y)) / d; + let y = (sq(p) * (s.x - q.x) + sq(q) * (p.x - s.x) + sq(s) * (q.x - p.x)) / d; + let c = Point::new(x, y); + (c, c.distance(p)) + } + + #[test] + fn unequal_circles_join_round_both() { + let (a, b) = (circle(0.0, 0.0, 30.0), circle(70.0, 0.0, 10.0)); + let sp = smooth_bridge(a, b, 40.0).unwrap(); + assert_smooth(&sp); + let bounds = PathData::single(sp.clone()).bounds().unwrap(); + assert!((bounds.x0 + 30.0).abs() < 1e-2 && (bounds.x1 - 80.0).abs() < 1e-2 && (bounds.y0 + 30.0).abs() < 1e-2, "{bounds:?}"); + // The neck narrows from the big circle towards the small one. + assert!(width_at(&sp, 35.0) > width_at(&sp, 50.0)); + assert!(width_at(&sp, 50.0) < 20.0); + } + + #[test] + fn unequal_circles_join_at_large_radii_overlapping_or_not() { + // With a large radius the arcs' centers lie beyond the smaller circle, so the arcs never + // reach the axis even though their centers are nearer to it than their radius. + for (a, b, r) in [ + (circle(0.0, 0.0, 10.0), circle(25.0, 0.0, 30.0), 100.0), + (circle(0.0, 0.0, 30.0), circle(25.0, 0.0, 10.0), 30.0), + (circle(0.0, 0.0, 30.0), circle(25.0, 0.0, 10.0), 50.0), + (circle(0.0, 0.0, 30.0), circle(60.0, 0.0, 8.0), 300.0), + ] { + let sp = smooth_bridge(a, b, r).unwrap_or_else(|e| panic!("{a:?} {b:?} {r}: {e:?}")); + assert_smooth(&sp); + assert!(outside(&sp, a) && outside(&sp, b)); + // The outline crosses the axis only at the two far ends: it does not cross itself. + let pts = outline(&sp); + let crossings = (0..pts.len()).filter(|&i| (pts[i].y > 0.0) != (pts[(i + 1) % pts.len()].y > 0.0)).count(); + assert_eq!(crossings, 2, "{a:?} {b:?} {r}"); + // It encloses more than the larger circle. + let area = PathData::single(sp).to_bezpath().area().abs(); + assert!(area > PI * a.radius.max(b.radius).powi(2), "{area}"); + } + } + + #[test] + fn overlapping_and_touching_circles_are_joined() { + let (a, b) = (circle(0.0, 0.0, 20.0), circle(30.0, 0.0, 20.0)); + let sp = smooth_bridge(a, b, 10.0).unwrap(); + assert_smooth(&sp); + // The circles cross at x = 15, y = ±√175; the bridge fills in the notch there. + assert!(width_at(&sp, 15.0) > 2.0 * 175f64.sqrt()); + assert!(width_at(&sp, 15.0) < 40.0); + let touching = smooth_bridge(circle(0.0, 0.0, 20.0), circle(40.0, 0.0, 20.0), 10.0).unwrap(); + assert_smooth(&touching); + assert!(width_at(&touching, 20.0) > 1.0); + } + + #[test] + fn far_apart_circles_and_nested_ones_make_no_bridge() { + let (a, b) = (circle(0.0, 0.0, 10.0), circle(100.0, 0.0, 10.0)); + assert_eq!(smooth_bridge(a, b, 5.0), Err(BridgeError::TooFar), "arcs don't reach"); + // The arcs reach both circles (gap 80 < 2 × 45) but cross before they do. + assert_eq!(smooth_bridge(a, b, 45.0), Err(BridgeError::TooFar), "no neck left"); + // A large enough radius bridges them: the neck stays open above (d/2)² − r² over 2r = 120. + assert!(smooth_bridge(a, b, 130.0).is_ok()); + assert_eq!(smooth_bridge(circle(0.0, 0.0, 30.0), circle(5.0, 0.0, 10.0), 10.0), Err(BridgeError::Inside)); + assert_eq!(smooth_bridge(circle(0.0, 0.0, 30.0), circle(0.0, 0.0, 30.0), 10.0), Err(BridgeError::Inside)); + assert_eq!(smooth_bridge(a, b, 0.0), Err(BridgeError::Bad)); + assert_eq!(smooth_bridge(a, b, f64::NAN), Err(BridgeError::Bad)); + assert_eq!(smooth_bridge(circle(f64::INFINITY, 0.0, 10.0), b, 10.0), Err(BridgeError::Bad)); + } + + #[test] + fn huge_circles_bridge_with_finite_anchors_or_are_refused() { + // Squaring these lengths overflows f64. + let (a, b) = (circle(0.0, 0.0, 5e153), circle(1.5e154, 0.0, 5e153)); + let sp = smooth_bridge(a, b, 5e153).unwrap(); + assert!(sp.anchors.iter().all(|q| [q.p, q.h_in, q.h_out].iter().all(|p| p.x.is_finite() && p.y.is_finite()))); + assert_smooth(&sp); + // The two radius sums fit in f64, but not their total. + let (a, b) = (circle(-5e307, 0.0, 1e307), circle(5e307, 0.0, 1e307)); + let sp = smooth_bridge(a, b, 1.5e308).unwrap(); + assert!(sp.anchors.iter().all(|q| [q.p, q.h_in, q.h_out].iter().all(|p| p.x.is_finite() && p.y.is_finite()))); + // The arcs' centers would lie beyond the largest f64. + let (a, b) = (circle(0.0, 0.0, 1e308), circle(1.5e308, 0.0, 1e308)); + assert_eq!(smooth_bridge(a, b, 1e308), Err(BridgeError::Bad)); + } + + #[test] + fn circles_are_told_from_other_paths() { + let round = shapes::ellipse(kurbo::Rect::new(10.0, 20.0, 50.0, 60.0)); + let c = circle_of(&round).unwrap(); + assert!(c.center.distance(Point::new(30.0, 40.0)) < 1e-9 && (c.radius - 20.0).abs() < 1e-9); + let oval = shapes::ellipse(kurbo::Rect::new(0.0, 0.0, 50.0, 40.0)); + assert_eq!(circle_of(&oval), None); + let square = PathData::single(SubPath::polyline(&[Point::ZERO, Point::new(10.0, 0.0), Point::new(10.0, 10.0), Point::new(0.0, 10.0)], true)); + assert_eq!(circle_of(&square), None); + let mut open = round.clone(); + open.subpaths[0].closed = false; + assert_eq!(circle_of(&open), None); + let two = PathData::new(vec![round.subpaths[0].clone(), round.subpaths[0].clone()]); + assert_eq!(circle_of(&two), None); + } +} diff --git a/crates/pdf/src/editing.rs b/crates/pdf/src/editing.rs index a8dd48628c..2fccfb393c 100644 --- a/crates/pdf/src/editing.rs +++ b/crates/pdf/src/editing.rs @@ -27,8 +27,8 @@ const DESCRIPTION: &str = "VectorCraft editing data; page hash "; /// Stands for the hash while the PDF is written: as long as a hash, so writing the hash over it /// keeps every offset. const PLACEHOLDER: &str = "0000000000000000"; -/// Deepest name tree searched for the editing file. -const MAX_DEPTH: usize = 16; +/// The most name tree nodes searched for the editing file. +const MAX_NODES: usize = 1 << 16; /// The native document a PDF carries ([`crate::PdfSettings::preserve_editing`]). #[derive(Clone, Debug, PartialEq, Eq)] @@ -77,12 +77,50 @@ pub fn editing_with(bytes: &[u8], password: Option<&str>) -> Option { editing_in(&crate::pages::open(bytes, password).ok()?) } +/// What the search of a parsed PDF's attachments for the editing file found ([`editing_file_spec`]). +struct Search<'a> { + /// The editing file's file specification, if one was found. + spec: Option>, + /// A name tree key searched names the editing file (set also when its file specification + /// can't be read). + keyed: bool, + /// The name tree has more than [`MAX_NODES`] nodes, so nodes were left unsearched. + cut: bool, +} + +/// The search of a parsed PDF's attachments for the editing file. +fn editing_file_spec(pdf: &Pdf) -> Search<'_> { + let xref = pdf.xref(); + let Some(tree) = xref + .get::>(xref.root_id()) + .and_then(|catalog| catalog.get::>(b"Names")) + .and_then(|names| names.get::>(b"EmbeddedFiles")) + else { + return Search { spec: None, keyed: false, cut: false }; + }; + let (mut keyed, mut cut) = (false, false); + let spec = editing_spec(tree, &mut keyed, &mut cut, xref); + Search { spec, keyed, cut } +} + +/// Does a parsed PDF list the editing file among its attachments, also when [`editing_in`] can't +/// read it (its file specification, its `EF` dictionary or its `F` or `UF` stream can't be +/// resolved)? Also true when the name tree is too large to search to its end. +pub(crate) fn has_editing_file_in(pdf: &Pdf) -> bool { + let search = editing_file_spec(pdf); + search.spec.is_some() || search.keyed || search.cut +} + +/// Is a parsed PDF's attachment name tree too large to search to its end (more than [`MAX_NODES`] +/// nodes)? It may then list an editing file that [`editing_in`] doesn't find, besides the one it +/// reads. +pub(crate) fn editing_search_cut_in(pdf: &Pdf) -> bool { + editing_file_spec(pdf).cut +} + /// [`editing`] of a parsed PDF. pub(crate) fn editing_in(pdf: &Pdf) -> Option { - let xref = pdf.xref(); - let catalog = xref.get::>(xref.root_id())?; - let tree = catalog.get::>(b"Names")?.get::>(b"EmbeddedFiles")?; - let spec = editing_spec(&tree, 0, &mut HashSet::new(), xref)?; + let spec = editing_file_spec(pdf).spec?; let files = spec.get::>(b"EF")?; let stream = files.get::>(b"F").or_else(|| files.get::>(b"UF"))?; let data = stream.decoded().map(|d| d.into_owned()).unwrap_or_default(); @@ -96,10 +134,59 @@ pub(crate) fn editing_in(pdf: &Pdf) -> Option { Some(Editing { data, intact }) } -/// The file specification of the editing file in the name tree node `node`. `seen` holds the indirect -/// nodes already searched, so a node shared by many `Kids` arrays is searched once, not once per path. -fn editing_spec<'a>(node: &Dict<'a>, depth: usize, seen: &mut HashSet, xref: &'a XRef) -> Option> { +/// The first file specification of the editing file in the name tree `tree`, searched in order at +/// any depth, [`MAX_NODES`] nodes at most. After the editing file is found, the walk goes on to the +/// end of the tree, or to the node limit, without reading the nodes' `Names`. An indirect node is +/// searched once, so a node shared by many `Kids` arrays is not searched once per path. `keyed` is +/// set when a key searched names the editing file, and `cut` when nodes are left unsearched. +fn editing_spec<'a>(tree: Dict<'a>, keyed: &mut bool, cut: &mut bool, xref: &'a XRef) -> Option> { + let mut seen = HashSet::::new(); + let mut nodes = vec![tree]; + let mut found = None; + // Nodes still to be searched, counting the ones waiting in `nodes`. + let mut left = MAX_NODES - 1; + while let Some(node) = nodes.pop() { + // Once the editing file is found, only the `Kids` are read, to learn whether the tree is cut. + if found.is_none() { + found = node_spec(&node, keyed, xref); + } + let Some(kids) = node.get::>(b"Kids") else { continue }; + // Only a referenced kid can be shared (a direct kid's `obj_id` is the object holding it). The + // reference is checked before the kid is read, so a shared kid is read once. + let mut kids: Vec> = items(&kids) + .filter_map(|raw| match raw { + MaybeRef::Ref(r) if seen.insert(r.into()) => xref.get::>(r.into()), + MaybeRef::NotRef(Object::Dict(kid)) => Some(kid), + _ => None, + }) + .take(left.saturating_add(1)) + .collect(); + if kids.len() > left { + *cut = true; + kids.truncate(left); + } + left -= kids.len(); + nodes.extend(kids.into_iter().rev()); + } + found +} + +/// The file specification of the editing file among the name tree node `node`'s own `Names`. +/// `keyed` is set when a key names the editing file. +fn node_spec<'a>(node: &Dict<'a>, keyed: &mut bool, xref: &'a XRef) -> Option> { if let Some(names) = node.get::>(b"Names") { + // The keys read as written, so a value that can't be resolved doesn't shift the pairs. + let mut raw = items(&names); + while let (Some(key), Some(_)) = (raw.next(), raw.next()) { + let key = match key { + MaybeRef::NotRef(Object::String(key)) => Some(key), + MaybeRef::Ref(r) => xref.get::>(r.into()), + MaybeRef::NotRef(_) => None, + }; + if key.is_some_and(|key| is_editing_name(&key)) { + *keyed = true; + } + } let mut items = names.iter::>(); while let (Some(_), Some(spec)) = (items.next(), items.next()) { if let Object::Dict(spec) = spec @@ -109,29 +196,19 @@ fn editing_spec<'a>(node: &Dict<'a>, depth: usize, seen: &mut HashSet= MAX_DEPTH { - return None; - } - let kids = node.get::>(b"Kids")?; - // Only a referenced kid can be shared (a direct kid's `obj_id` is the object holding it). The - // reference is checked before the kid is read, so a shared kid is read once. - items(&kids).find_map(|raw| { - let kid = match raw { - MaybeRef::Ref(r) if seen.insert(r.into()) => xref.get::>(r.into())?, - MaybeRef::NotRef(Object::Dict(kid)) => kid, - _ => return None, - }; - editing_spec(&kid, depth + 1, seen, xref) - }) + None } /// A file specification naming the editing file (current or legacy name), in any text string /// encoding. fn is_editing_file(spec: &Dict<'_>) -> bool { - [&b"UF"[..], b"F"].into_iter().filter_map(|k| spec.get::>(k)).any(|name| { - let name = text_string(name.as_bytes()); - name == EDITING_FILE || name == LEGACY_EDITING_FILE - }) + [&b"UF"[..], b"F"].into_iter().filter_map(|k| spec.get::>(k)).any(|name| is_editing_name(&name)) +} + +/// A text string that is the editing file's name (current or legacy), in any encoding. +fn is_editing_name(name: &PdfString<'_>) -> bool { + let name = text_string(name.as_bytes()); + name == EDITING_FILE || name == LEGACY_EDITING_FILE } /// The most decoded page content [`page_hash`] reads in all (bytes). diff --git a/crates/pdf/src/export/writer.rs b/crates/pdf/src/export/writer.rs index e11cda9acd..bd241421c7 100644 --- a/crates/pdf/src/export/writer.rs +++ b/crates/pdf/src/export/writer.rs @@ -64,14 +64,16 @@ pub(crate) struct Sheet<'a> { impl Writer { /// A PDF with `set`'s version, standard, compression and colour output, and `doc`'s metadata - /// under `title`, created at `created` (Unix seconds). With `cmyk`, transparency blends in - /// CMYK (unless the colours are converted to RGB). + /// and language under `title`, created at `created` (Unix seconds). With `cmyk`, transparency + /// blends in CMYK (unless the colours are converted to RGB). pub(crate) fn new(doc: &Document, set: &crate::PdfSettings, title: &str, created: Option, cmyk: bool) -> Result { let out = ColorOut::new(doc, set)?; let mut warnings = out.profile_notes.clone(); - // Tagged CMYK colours need the profile (PDF/A tags every colour). - let cmyk_profile = if out.tagged { out.cmyk_icc() } else { None }; - if out.tagged && cmyk_profile.is_none() { + // Tagged CMYK colours need the profile (PDF/A tags every colour). When CMYK colors are + // DeviceCMYK (`device_cmyk`), the writer gets no CMYK profile. + let tags_cmyk = out.tagged && !out.device_cmyk(); + let cmyk_profile = if tags_cmyk { out.cmyk_icc() } else { None }; + if tags_cmyk && cmyk_profile.is_none() { warnings.push(format!("the CMYK profile {} can't be embedded: CMYK colours are written untagged", out.cmyk_profile())); } let version = match set.compatibility { @@ -109,7 +111,11 @@ impl Writer { created: created.map(date_time), modified: None, }; - let pdf = write::Writer::new(settings, metadata); + // The document language (Document Setup) as the catalog's `Lang` and the XMP packet's + // `dc:language` (ISO 32000-1, 14.9.2): its BCP 47 tag. A language without a tag writes + // none rather than a guess. + let language = vectorcraft_doc::setup::language_tag(&doc.setup.language).map(str::to_string); + let pdf = write::Writer::new_with_language(settings, metadata, language); Ok(Self { pdf, cmyk: out.blends_cmyk(cmyk), @@ -271,8 +277,15 @@ impl Writer { PdfError::from(e) })?; if self.cmyk { - let profile = self.out.tagged.then(|| vectorcraft_color::cms::icc_bytes(self.out.cmyk_profile()).ok()).flatten(); - cmyk_blending(&mut bytes, self.out.tagged, profile.as_deref(), self.out.standard != Standard::PdfA2b); + let device = self.out.device_cmyk(); + let profile = (self.out.tagged && !device).then(|| vectorcraft_color::cms::icc_bytes(self.out.cmyk_profile()).ok()).flatten(); + let without = match (&profile, self.out.standard != Standard::PdfA2b) { + _ if device => Without::AlwaysDeviceCmyk, + (None, _) => Without::FirstCmyk, + (Some(_), true) => Without::DeviceCmyk, + (Some(_), false) => Without::Rgb, + }; + cmyk_blending(&mut bytes, self.out.tagged, profile.as_deref(), without); } let lab = !self.lab_spots.is_empty() && !self.out.standard.cmyk_only(); let bytes = if lab { crate::lab_spot::lab_alternates(bytes, &self.lab_spots) } else { bytes }; @@ -287,19 +300,12 @@ impl Writer { /// are rewritten in place to DeviceCMYK (or the CMYK profile's space), keeping their length so the /// cross-reference offsets stay valid. Luminosity masks' groups keep RGB: mask luminance is that /// of screen colours, as on screen. Tagged groups blend in the space of CMYK profile `profile` -/// (the one that tags CMYK colours) when the file has one. When its only CMYK spaces are of other -/// profiles (images' own), they blend in DeviceCMYK where `device` allows it, else they keep RGB; -/// without `profile`, they blend in the first CMYK space. -fn cmyk_blending(pdf: &mut [u8], tagged: bool, profile: Option<&[u8]>, device: bool) { +/// (the one that tags CMYK colours) when the file has one; otherwise they blend as `without` says. +fn cmyk_blending(pdf: &mut [u8], tagged: bool, profile: Option<&[u8]>, without: Without) { let masks = luminosity_mask_groups(pdf); let mut spaces = vec![("/CS/DeviceRGB".to_string(), "/CS/DeviceCMYK".to_string())]; if tagged { let own = profile.and_then(|icc| crate::output::tagging_stream(pdf, &crate::patch::Xref::read(pdf)?, icc)); - let without = match (profile, device) { - (None, _) => Without::FirstCmyk, - (Some(_), true) => Without::DeviceCmyk, - (Some(_), false) => Without::Rgb, - }; spaces.extend(icc_spaces(pdf, own, without)); } let mut from = 0; @@ -316,11 +322,15 @@ fn cmyk_blending(pdf: &mut [u8], tagged: bool, profile: Option<&[u8]>, device: b /// What tagged groups blend in when the file holds no space of the document's CMYK profile. #[derive(Clone, Copy, Debug, PartialEq)] enum Without { - /// The first ICC-based CMYK space of the file. + /// The first ICC-based CMYK space of the file (the document's profile isn't known). FirstCmyk, + /// DeviceCMYK when the file has an ICC-based CMYK space (images' own profiles), outside PDF/A. DeviceCmyk, - /// The RGB space they have. + /// The RGB space they have (PDF/A, which allows no DeviceCMYK next to images' own profiles). Rgb, + /// DeviceCMYK, also when the file has no ICC-based CMYK space: CMYK colors are DeviceCMYK + /// ([`crate::output::ColorOut::device_cmyk`]). + AlwaysDeviceCmyk, } /// The ICC-based RGB colour spaces of `pdf`, each with the ICC-based CMYK one to blend in instead, @@ -352,6 +362,7 @@ fn icc_spaces(pdf: &[u8], own: Option, without: Without) -> Vec<(String, St Without::FirstCmyk => cmyk, Without::DeviceCmyk => cmyk.map(|_| "/CS/DeviceCMYK".to_string()), Without::Rgb => None, + Without::AlwaysDeviceCmyk => Some("/CS/DeviceCMYK".to_string()), }); let Some(cmyk) = cmyk else { return vec![] }; rgb.into_iter().map(|r| (r, cmyk.clone())).collect() @@ -435,6 +446,11 @@ mod tests { // profile's space; the first CMYK space when the document's profile isn't known. assert_eq!(icc_spaces(SPACES, None, Without::DeviceCmyk), [(rgb.clone(), "/CS/DeviceCMYK".to_string())]); assert_eq!(icc_spaces(SPACES, None, Without::Rgb), []); - assert_eq!(icc_spaces(SPACES, None, Without::FirstCmyk), [(rgb, "/CS 2 0 R".to_string())]); + assert_eq!(icc_spaces(SPACES, None, Without::FirstCmyk), [(rgb.clone(), "/CS 2 0 R".to_string())]); + // CMYK colors written as DeviceCMYK: groups blend there, with or without a CMYK ICC space. + assert_eq!(icc_spaces(SPACES, None, Without::AlwaysDeviceCmyk), [(rgb.clone(), "/CS/DeviceCMYK".to_string())]); + let rgb_only = b"%PDF-1.7\n1 0 obj\n[/ICCBased 4 0 R]\nendobj\n4 0 obj\n<>stream\n\nendstream\nendobj\n"; + assert_eq!(icc_spaces(rgb_only, None, Without::DeviceCmyk), []); + assert_eq!(icc_spaces(rgb_only, None, Without::AlwaysDeviceCmyk), [(rgb, "/CS/DeviceCMYK".to_string())]); } } diff --git a/crates/pdf/src/import/builder.rs b/crates/pdf/src/import/builder.rs index a9cd9ada7c..eb8742f2db 100644 --- a/crates/pdf/src/import/builder.rs +++ b/crates/pdf/src/import/builder.rs @@ -43,6 +43,7 @@ impl<'p> Builder<'p> { image_keys: HashMap::new(), raster_scales: HashMap::new(), cmyk_keys: HashSet::new(), + intent_cmyk: None, separation_paints: HashMap::new(), opaque: HashSet::new(), warnings: vec![], diff --git a/crates/pdf/src/import/device.rs b/crates/pdf/src/import/device.rs index 45ca7f7081..452090c6b6 100644 --- a/crates/pdf/src/import/device.rs +++ b/crates/pdf/src/import/device.rs @@ -1,4 +1,4 @@ -use super::entry::{INVISIBLE_TEXT_NOTE, MAX_NESTED, OUTLINED_TEXT_NOTE, UNSORTED, WHITE_KEY}; +use super::entry::{INTENT_KEY, INVISIBLE_TEXT_NOTE, MAX_NESTED, OUTLINED_TEXT_NOTE, UNSORTED, WHITE_KEY}; use super::state::{ Builder, Decoded, Frame, FrameKind, GlyphRun, blend, fill_rule, gray_png, line_width, mean_scale, resize_alpha, rgb_png, rgba_png, same_outline, stroke_layer, stroke_outline, @@ -242,8 +242,11 @@ impl<'a> Device<'a> for Builder<'_> { match image { Image::Raster(r) => { let white = self.white_images; + // A DeviceCMYK image takes the output intent's profile only where no DefaultCMYK + // replaces DeviceCMYK, so it is cached apart from the same image drawn where one does. + let intent = !white && self.intent_cmyk.is_some() && self.scan.cmyk_defaults.get(&r.stream().dict().obj_id()) == Some(&false); // Inside an alpha mask the same image is read again, white (its own cache key). - let key = craft_pdf::interpret::CacheKey::cache_key(&r) ^ if white { WHITE_KEY } else { 0 }; + let key = craft_pdf::interpret::CacheKey::cache_key(&r) ^ if white { WHITE_KEY } else { 0 } ^ if intent { INTENT_KEY } else { 0 }; let st = r.stream(); let (w, h) = (r.width(), r.height()); // CMYK images keep their samples (read once per image). @@ -251,7 +254,8 @@ impl<'a> Device<'a> for Builder<'_> { let cmyk = if known || white { None } else { - crate::import_image::cmyk(st, w, h).unwrap_or_else(|why| { + let intent = self.intent_cmyk.as_deref().filter(|_| intent); + crate::import_image::cmyk(st, w, h, intent).unwrap_or_else(|why| { self.warn(why); None }) diff --git a/crates/pdf/src/import/entry.rs b/crates/pdf/src/import/entry.rs index 8f84b9a332..5b945c6b25 100644 --- a/crates/pdf/src/import/entry.rs +++ b/crates/pdf/src/import/entry.rs @@ -9,6 +9,9 @@ use super::{ /// Mixed into an image's cache key when it is read white inside an alpha soft mask. pub(super) const WHITE_KEY: u128 = 0x7717_e000_a1fa; +/// Mixed into an image's cache key when a DeviceCMYK image there takes the output intent's profile. +pub(super) const INTENT_KEY: u128 = 0x1e7e_0c3c_0b5a; + /// The name of the paths text imports as. pub(super) const TEXT_OUTLINES: &str = ""; @@ -281,6 +284,7 @@ fn read_opened( b.unsure = route && ocgs.list.iter().any(|g| (all_on && !g.on) || !g.print); b.taken = taken; b.warnings = notes; + b.intent_cmyk = crate::import_image::output_intent_cmyk(pdf); b.colors.uncalibrated_rgb = opts.uncalibrated_rgb && picked.iter().filter_map(|&n| pages.get(n)).any(crate::pages::has_private_data); let cache = InterpreterCache::new(); let mut x = 0.0; diff --git a/crates/pdf/src/import/state.rs b/crates/pdf/src/import/state.rs index ba0c23a808..d8068279cf 100644 --- a/crates/pdf/src/import/state.rs +++ b/crates/pdf/src/import/state.rs @@ -103,6 +103,9 @@ pub(super) struct Builder<'p> { pub(super) raster_scales: HashMap, /// The images kept with their CMYK samples ([`crate::import_image`]). pub(super) cmyk_keys: HashSet, + /// The file's PDF/X output intent profile of CMYK, which DeviceCMYK images are tagged with + /// ([`crate::import_image::output_intent_cmyk`]). + pub(super) intent_cmyk: Option>, /// Images in a Separation space, by key: the paint of their ink, or `None` when they open in /// RGB (an ink that can't be told, tints that can't be read). pub(super) separation_paints: HashMap>, diff --git a/crates/pdf/src/import_image.rs b/crates/pdf/src/import_image.rs index cafae6d448..ecab9e6e08 100644 --- a/crates/pdf/src/import_image.rs +++ b/crates/pdf/src/import_image.rs @@ -5,15 +5,17 @@ //! ([`ImageBlob::cmyk_tiff`]). An ICC-based image keeps the CMYK profile its color space holds //! ([`icc_profile`]): the TIFF carries it, and a kept JPEG carries it in place of its own //! ([`jpeg_with_icc`]), or, when its segments can't hold it, is stored as a CMYK TIFF carrying it. +//! In a file with a PDF/X output intent of CMYK, a DeviceCMYK image keeps that intent's profile +//! the same way ([`output_intent_cmyk`]), since the intent describes DeviceCMYK there. //! A mask (`/SMask`, `/Mask`) doesn't change that: the importer //! carries it as the image's opacity mask ([`has_mask`]). A DeviceN image of process plates only //! keeps them the same way, as a CMYK image ([`process_devicen`]). An image of one ink (a //! Separation, or a DeviceN of one colorant) keeps it: its tints are read as a grayscale image //! ([`tint_gray`]) that the ink colorizes. Every other image is read as RGB by the interpreter. -use craft_pdf::syntax::Filter; use craft_pdf::syntax::object::stream::{ImageColorSpace, ImageDecodeParams}; use craft_pdf::syntax::object::{Array, Dict, Name, Stream}; +use craft_pdf::syntax::{Filter, Pdf}; use vectorcraft_doc::ImageBlob; use vectorcraft_doc::cmyk::{Inks, MAX_CMYK_PIXELS, jpeg_components, jpeg_with_icc}; @@ -55,7 +57,11 @@ fn icc_profile(d: &Dict<'_>) -> Option> { if it.next::>()?.as_ref() != b"ICCBased" { return None; } - let s = it.next::>()?; + cmyk_profile(&it.next::>()?) +} + +/// The four-component CMYK profile stream `s` holds, when an image can be tagged with it. +fn cmyk_profile(s: &Stream<'_>) -> Option> { if s.dict().get::(b"N") != Some(4) { return None; } @@ -64,6 +70,23 @@ fn icc_profile(d: &Dict<'_>) -> Option> { valid_icc(&icc, *b"CMYK").then(|| icc.into_owned()) } +/// The CMYK profile of the catalog's PDF/X output intent (`/S /GTS_PDFX` with a four-component +/// `DestOutputProfile`), which DeviceCMYK colors are in. `None` without one. +pub(crate) fn output_intent_cmyk(pdf: &Pdf) -> Option> { + let xref = pdf.xref(); + let intents = xref.get::>(xref.root_id())?.get::>(b"OutputIntents")?; + let pdfx = intents.iter::>().take(MAX_INTENTS).find(|i| i.get::>(b"S").is_some_and(|s| s.as_ref() == b"GTS_PDFX"))?; + cmyk_profile(&pdfx.get::>(b"DestOutputProfile")?) +} + +/// The output intents read before giving up on finding the PDF/X one. +const MAX_INTENTS: usize = 16; + +/// Is the image's color space DeviceCMYK (or its inline abbreviation)? +fn device_cmyk(d: &Dict<'_>) -> bool { + d.get::>(key(d, b"ColorSpace", b"CS")).is_some_and(|n| matches!(n.as_ref(), b"DeviceCMYK" | b"CMYK")) +} + /// Each component's Decode range (`[0 1]` each when the array is missing or malformed). fn decode_ranges(d: &Dict<'_>) -> [(f32, f32); 4] { let mut out = [(0.0, 1.0); 4]; @@ -78,14 +101,15 @@ fn decode_ranges(d: &Dict<'_>) -> [(f32, f32); 4] { } /// The image `st` (`width` × `height` pixels) in CMYK: `Ok(None)` when it isn't a CMYK image, -/// `Err` (a warning) when it is one that is read as RGB. -pub(crate) fn cmyk(st: &Stream<'_>, width: u32, height: u32) -> Result, &'static str> { +/// `Err` (a warning) when it is one that is read as RGB. `intent` is the file's PDF/X output intent +/// profile of CMYK ([`output_intent_cmyk`]), which a DeviceCMYK image is tagged with. +pub(crate) fn cmyk(st: &Stream<'_>, width: u32, height: u32, intent: Option<&[u8]>) -> Result, &'static str> { let d = st.dict(); if !cmyk_space(d) { return process_devicen(st, width, height); } let ranges = decode_ranges(d); - let icc = icc_profile(d); + let icc = icc_profile(d).or_else(|| intent.filter(|_| device_cmyk(d)).map(<[u8]>::to_vec)); let filters = st.filters(); if ranges == INVERTED && matches!(filters.as_slice(), [Filter::DctDecode]) { let raw = st.raw_data(); diff --git a/crates/pdf/src/import_scan.rs b/crates/pdf/src/import_scan.rs index b65254eafa..7f2e9cc161 100644 --- a/crates/pdf/src/import_scan.rs +++ b/crates/pdf/src/import_scan.rs @@ -280,6 +280,10 @@ pub(crate) struct Scan { /// Something overprints with overprint mode 0, where a `DeviceCMYK` colour's zero components /// knock out; the document's overprint is the nonzero one (mode 1). pub zero_mode: bool, + /// The images the page draws (image XObjects by object, inline images as `None`), each with + /// whether it is drawn where a `/DefaultCMYK` is in scope, which replaces DeviceCMYK there + /// (ISO 32000-2 §8.6.5.6). An image drawn both ways is `true`. + pub cmyk_defaults: HashMap, bool>, /// The colorant names of the Separation and DeviceN spaces the page sets (`cs`, `CS`), and of /// those of the shading patterns it sets (`scn`, `SCN`) and of the shadings it draws (`sh`), /// each once (none when the page uses more than [`MAX_INKS`] inks or changes ink more than @@ -663,53 +667,23 @@ impl Walker<'_, '_> { self.out.type3_cache_map.insert(hash, (f_key, to_unicode)); } } - let is_colour = if is_type3 { - let mut colour = false; - let mut seen_streams = HashSet::new(); - let mut decoded_bytes = 0usize; - const MAX_CHARPROC_BYTES: usize = 16 << 20; - if let Some(char_procs) = f.get::>(b"CharProcs") { - for key in char_procs.keys() { - if let Some(stream) = char_procs.get::>(key.as_ref()) { - if !seen_streams.insert(stream.cache_key()) { - continue; - } - if decoded_bytes >= MAX_CHARPROC_BYTES { - colour = true; - break; - } - if let Ok(data) = stream.decoded_within(MAX_CHARPROC_BYTES.saturating_sub(decoded_bytes)) { - decoded_bytes = decoded_bytes.saturating_add(data.len()); - let mut iter = TypedIter::new(data.as_ref()); - while let Some(op) = iter.next() { - match op { - TypedInstruction::ColorGlyph(_) => { - colour = true; - break; - } - TypedInstruction::ShapeGlyph(_) => break, - _ => {} - } - } - if colour { - break; - } - } - } - } - } - colour - } else { - false - }; + // A font is noted once for the document, so its glyph procedures are read only the + // first time any page or form lists it. self.fonts.entry(f_key).or_insert_with(|| { let embedded = embeds_glyphs(&f); + let is_colour = is_type3 && sets_glyph_colors(&f); FontNote { name, embedded, vertical: vertical_metrics(&f, embedded), is_type3, to_unicode, is_colour } }); } } } + /// An image drawn with `res` in scope, as the interpreter looks up its `/DefaultCMYK`. + fn drawn_image(&mut self, id: Option, res: &Resources<'_>) { + let default = res.get_color_space(&Name::new_unescaped(b"DefaultCMYK")).is_some(); + *self.out.cmyk_defaults.entry(id).or_default() |= default; + } + fn walk(&mut self, data: &[u8], res: &Resources<'_>, depth: u32) { let mut iter = TypedIter::new(data); self.note_fonts(res); @@ -874,12 +848,17 @@ impl Walker<'_, '_> { | TypedInstruction::ShowTexts(_) | TypedInstruction::NextLineAndShowText(_) | TypedInstruction::ShowTextWithParameters(_) => self.shown(), + TypedInstruction::InlineImage(_) => self.drawn_image(None, res), TypedInstruction::XObject(x) => { if !self.is_visible() { continue; } let Some(s) = res.get_x_object(x.0) else { continue }; let d = s.dict(); + if d.get::>(b"Subtype").as_deref() == Some(b"Image") { + self.drawn_image(d.obj_id(), res); + continue; + } if d.get::>(b"Subtype").as_deref() != Some(b"Form") || d.get::<[f32; 4]>(b"BBox").is_none() { continue; } @@ -1108,6 +1087,48 @@ fn font_name(f: &Dict<'_>) -> Option { Some(stripped.unwrap_or(base)) } +/// The most bytes of a Type 3 font's glyph procedures decoded to look for colored glyphs. +const MAX_CHARPROC_BYTES: usize = 16 << 20; + +// The glyph procedures decoded by `sets_glyph_colors` on this thread. +#[cfg(test)] +thread_local! { + pub(crate) static TEST_CHARPROC_DECODES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Whether Type 3 font `f` has a glyph procedure that sets its own color (`d0`, ISO 32000-1 +/// §9.6.5): its procedures are read until one starts with `d0`, each up to its `d0` or `d1`. Past +/// [`MAX_CHARPROC_BYTES`] of them the font is taken to have one. +fn sets_glyph_colors(f: &Dict<'_>) -> bool { + let Some(char_procs) = f.get::>(b"CharProcs") else { return false }; + let mut seen_streams = HashSet::new(); + let mut decoded_bytes = 0usize; + for key in char_procs.keys() { + if let Some(stream) = char_procs.get::>(key.as_ref()) { + if !seen_streams.insert(stream.cache_key()) { + continue; + } + if decoded_bytes >= MAX_CHARPROC_BYTES { + return true; + } + #[cfg(test)] + TEST_CHARPROC_DECODES.with(|n| n.set(n.get() + 1)); + if let Ok(data) = stream.decoded_within(MAX_CHARPROC_BYTES.saturating_sub(decoded_bytes)) { + decoded_bytes = decoded_bytes.saturating_add(data.len()); + let mut iter = TypedIter::new(data.as_ref()); + while let Some(op) = iter.next() { + match op { + TypedInstruction::ColorGlyph(_) => return true, + TypedInstruction::ShapeGlyph(_) => break, + _ => {} + } + } + } + } + } + false +} + /// Whether font `f` carries its own glyphs: a font program in its descriptor (a composite font's in /// its descendant's), or a Type 3 font's glyph procedures. A font that doesn't is drawn with a /// stand-in, whose glyphs say nothing about which installed face the document means. diff --git a/crates/pdf/src/output.rs b/crates/pdf/src/output.rs index f5e4bb6e36..83104215c2 100644 --- a/crates/pdf/src/output.rs +++ b/crates/pdf/src/output.rs @@ -25,12 +25,17 @@ //! document's), RGB with sRGB (colours of another RGB space as their sRGB equivalents) and grey //! with the sRGB tone curve. Otherwise they are device colours. PDF/A, PDF/X-3 and PDF/X-4 //! always tag them, whatever `profiles` says; PDF/X-1a never does, and always converts to a -//! CMYK destination (see [`crate::pdfx`]). A CMYK image that keeps its numbers is tagged with -//! the CMYK profile it carries, if any, with `all` and `taggedSource`, and in PDF/A, PDF/X-3 -//! and PDF/X-4 unless `profiles` is `destination` ([`ColorOut::cmyk_image_icc`]). When +//! CMYK destination (see [`crate::pdfx`]). In PDF/X-3 and PDF/X-4, CMYK colors in the profile +//! of a CMYK output intent are DeviceCMYK, and so are all CMYK colors with `none`, unless +//! colors are converted to a CMYK destination of another profile ([`ColorOut::device_cmyk`]). +//! A CMYK image that keeps +//! its numbers is tagged with the CMYK profile it carries, if any, with `all` and +//! `taggedSource`, and in PDF/A, PDF/X-3 and PDF/X-4 unless `profiles` is `destination` +//! ([`ColorOut::cmyk_image_icc`]); not when that profile is a DeviceCMYK output intent's. When //! `profiles` isn't set, colors are written as with `none` and gray and RGB images keep the //! profiles they carry (but in PDF/X-1a); when it is set to `none`, no image keeps its own -//! profile, a JPEG's `ICC_PROFILE` segments included, except in PDF/A, PDF/X-3 and PDF/X-4 +//! profile, a JPEG's `ICC_PROFILE` segments included, except in PDF/A, PDF/X-3 and PDF/X-4, +//! where CMYK images lose theirs only when CMYK colors are DeviceCMYK //! ([`ColorOut::source_profiles`]). //! - Output intent: the profile `outputIntent` names, embedded as the `/GTS_PDFX` output intent //! of the catalog with the condition, identifier and registry; Trapped goes in the document @@ -82,6 +87,13 @@ pub(crate) struct ColorOut { no_profiles: bool, /// The CMYK profile that tags CMYK colours. cmyk_profile: String, + /// CMYK colors are written as DeviceCMYK although colors are tagged + /// ([`Self::device_cmyk`]): the profile of the CMYK output intent they are in, embedded once + /// as its `DestOutputProfile`. + device_icc: Option>, + /// With [`Self::device_icc`], CMYK images are untagged too, whatever profile they carry + /// (`profiles` is `none`). + untag_cmyk_images: bool, /// Tagged RGB colours are written as their sRGB equivalents: why (a warning), when their RGB /// space isn't sRGB. pub srgb_note: Option, @@ -132,6 +144,8 @@ impl Default for ColorOut { image_icc: false, no_profiles: false, cmyk_profile, + device_icc: None, + untag_cmyk_images: false, srgb_note: None, pixels: OnceLock::new(), tagged_pixels: OnceLock::new(), @@ -290,9 +304,32 @@ impl ColorOut { } out.catalog = catalog(set, &out.cmyk_profile); out.standard = set.standard; + // In PDF/X-3 and PDF/X-4 the CMYK output intent characterizes DeviceCMYK: CMYK colors in + // its profile are written as DeviceCMYK, and with `none` every CMYK color is, unless + // colors are converted to a CMYK destination of another profile. Files without a standard + // keep the tags that `profiles` asks for. + let intent_cmyk = out.catalog.as_ref().and_then(|c| c.intent.as_ref()?.profile.as_ref()).filter(|(_, n)| *n == 4); + let none = set.output.profiles == Some(ProfileInclusion::None); + let to_cmyk = out.dest.as_ref().is_some_and(|d| d.model == Model::Cmyk); + if out.tagged + && set.standard.is_pdfx() + && let Some(intent) = intent_cmyk.and_then(|(name, _)| cms::icc_bytes(name).ok()) + && ((none && !to_cmyk) || cms::icc_bytes(&out.cmyk_profile).is_ok_and(|own| own == intent)) + { + out.device_icc = Some(intent); + out.untag_cmyk_images = none; + } Ok(out) } + /// CMYK colors are written as DeviceCMYK although colors are tagged, in PDF/X-3 and PDF/X-4 + /// with a CMYK output intent: its profile is the one they are in, or `profiles` is `none` and + /// there is no CMYK destination of another profile. RGB and gray colors stay tagged, and + /// so does a CMYK image that carries another profile, except with `none`. + pub(crate) fn device_cmyk(&self) -> bool { + self.device_icc.is_some() + } + /// Transparency blends in CMYK: converting to CMYK, or (without conversion) in a CMYK /// document (`cmyk`). pub(crate) fn blends_cmyk(&self, cmyk: bool) -> bool { @@ -415,22 +452,29 @@ impl ColorOut { /// The CMYK profile CMYK image `blob` is tagged with ([`crate::images::cmyk_icc`]): the one it /// carries, when its numbers are kept and the Profiles setting or the standard includes source - /// profiles. `None` otherwise, and in PDF/X-1a, whose images are untagged CMYK. + /// profiles. `None` otherwise, and in PDF/X-1a, whose images are untagged CMYK. When CMYK + /// colors are DeviceCMYK ([`Self::device_cmyk`]), an image that carries the output intent's + /// profile is untagged too, and so is every CMYK image with `none`. pub(crate) fn cmyk_image_icc(&self, blob: &vectorcraft_doc::ImageBlob) -> Option> { if !self.image_icc || self.cmyk_pixels().is_some() { return None; } - crate::images::cmyk_icc(blob) + let icc = crate::images::cmyk_icc(blob)?; + match &self.device_icc { + Some(intent) if self.untag_cmyk_images || icc == **intent => None, + _ => Some(icc), + } } /// How CMYK image `blob` is tagged ([`crate::images::recode_cmyk`]): with the profile /// [`Self::cmyk_image_icc`] gives (`icc`), else untagged, without a JPEG's own `ICC_PROFILE` - /// segments when Don't Include Profiles was set. + /// segments when Don't Include Profiles was set or CMYK colors are DeviceCMYK + /// ([`Self::device_cmyk`]). pub(crate) fn cmyk_tag<'a>(&self, icc: Option<&'a [u8]>) -> crate::images::CmykTag<'a> { use crate::images::CmykTag; match icc { Some(icc) => CmykTag::Profile(icc), - None if self.no_profiles => CmykTag::Removed, + None if self.no_profiles || self.device_cmyk() => CmykTag::Removed, None => CmykTag::Untagged, } } diff --git a/crates/pdf/src/pages.rs b/crates/pdf/src/pages.rs index 470432aa8f..ec593baf24 100644 --- a/crates/pdf/src/pages.rs +++ b/crates/pdf/src/pages.rs @@ -261,6 +261,18 @@ impl Opened { crate::editing::editing_in(&self.pdf) } + /// Does the PDF list the editing file among its attachments, also when + /// [`editing`](Self::editing) can't read it? + pub fn has_editing_file(&self) -> bool { + crate::editing::has_editing_file_in(&self.pdf) + } + + /// Is the PDF's attachment name tree too large to search to its end? It may then list an + /// editing file that [`editing`](Self::editing) doesn't find, besides the one it reads. + pub fn editing_search_cut(&self) -> bool { + crate::editing::editing_search_cut_in(&self.pdf) + } + /// The private data of an Illustrator `.ai`, as [`illustrator_data`] reads it. pub fn illustrator_data(&self) -> Option> { private_data(&self.pdf) diff --git a/crates/pdf/src/patch.rs b/crates/pdf/src/patch.rs index 8b9d69b908..9235f22cea 100644 --- a/crates/pdf/src/patch.rs +++ b/crates/pdf/src/patch.rs @@ -107,6 +107,42 @@ impl Xref { /// A replacement of bytes `start..end` of the file. type Edit = (usize, usize, Vec); +/// Where byte offsets of the old file land in the new one, for edits sorted by start that do not +/// overlap, whose ends therefore never decrease. +struct Moves { + /// Each edit's end, in order. + ends: Vec, + /// The change in length made by the edits up to and including each one. + shifts: Vec, +} + +impl Moves { + /// `None` when a change in length doesn't fit an `isize`. + fn new(edits: &[Edit]) -> Option { + let mut total: isize = 0; + let mut shifts = Vec::with_capacity(edits.len()); + for (start, end, new) in edits { + let removed = isize::try_from(end.checked_sub(*start)?).ok()?; + total = total.checked_add(isize::try_from(new.len()).ok()?)?.checked_sub(removed)?; + shifts.push(total); + } + Some(Self { ends: edits.iter().map(|e| e.1).collect(), shifts }) + } + + /// Where `off` lands: moved by every edit that ends at or before it. + fn at(&self, off: usize) -> Option { + match self.ends.partition_point(|&end| end <= off) { + 0 => Some(off), + n => off.checked_add_signed(*self.shifts.get(n - 1)?), + } + } +} + +/// `off` as the ten digits of a cross-reference entry; `None` past what ten digits hold. +fn entry_offset(off: usize) -> Option { + (u64::try_from(off).ok()? < 10_000_000_000).then(|| format!("{off:010}")) +} + /// The edits of one PDF, applied together by [`Self::apply`]. pub(crate) struct Patch { edits: Vec, @@ -139,18 +175,17 @@ impl Patch { } /// `pdf` with the edits, new objects and trailer entries, and a cross-reference table that - /// matches. Refused when an edit overlaps another or reaches past the objects. + /// matches. Refused when an edit overlaps another or reaches past the objects, or when an + /// object would start past the ten digits a cross-reference entry gives its offset in. pub fn apply(mut self, pdf: &[u8], xref: &Xref) -> Result, PdfError> { let bad = |why: &str| PdfError::Write(format!("can't edit the written PDF: {why}")); self.edits.sort_by_key(|e| (e.0, e.1)); if self.edits.windows(2).any(|w| w[0].1 > w[1].0) || self.edits.iter().any(|e| e.0 > e.1 || e.1 > xref.at) { return Err(bad("edits overlap")); } - // Where a byte offset of the old file lands in the new one. let edits = &self.edits; - let moved = |off: usize| -> usize { - edits.iter().filter(|e| e.1 <= off).fold(off as isize, |o, e| o + e.2.len() as isize - (e.1 - e.0) as isize) as usize - }; + let moves = Moves::new(edits).ok_or_else(|| bad("edits too large"))?; + let too_far = || bad("an object lies past what the cross-reference table holds"); let added: usize = self.edits.iter().map(|e| e.2.len()).sum::() + self.objects.iter().map(|o| o.len() + 32).sum::(); let mut out = Vec::with_capacity(pdf.len() + added + 64); let mut at = 0; @@ -175,7 +210,7 @@ impl Patch { for e in old.chunks(20) { match number(e, 0) { Some((off, _)) if e.get(17) == Some(&b'n') => { - out.extend_from_slice(format!("{:010}", moved(off)).as_bytes()); + out.extend_from_slice(moves.at(off).and_then(entry_offset).ok_or_else(too_far)?.as_bytes()); out.extend_from_slice(e.get(10..).unwrap_or_default()); } _ => out.extend_from_slice(e), @@ -183,7 +218,8 @@ impl Patch { } let eol = old.get(18..20).unwrap_or(b"\r\n"); for off in offsets { - out.extend_from_slice(format!("{off:010} 00000 n").as_bytes()); + out.extend_from_slice(entry_offset(off).ok_or_else(too_far)?.as_bytes()); + out.extend_from_slice(b" 00000 n"); out.extend_from_slice(eol); } // The trailer, with its size and the new entries. @@ -201,3 +237,279 @@ impl Patch { Ok(out) } } + +#[cfg(test)] +mod tests { + use super::*; + use std::time::{Duration, Instant}; + + /// A PDF written as the export writes one: objects `<< /N n >>` numbered from 1, those `free` + /// picks left out with a free entry, then one cross-reference table and the trailer. + fn written(count: usize, free: impl Fn(usize) -> bool) -> Vec { + let mut pdf = b"%PDF-1.7\n".to_vec(); + let mut entries = b"0000000000 65535 f\r\n".to_vec(); + for n in 1..=count { + if free(n) { + entries.extend_from_slice(b"0000000000 00001 f\r\n"); + continue; + } + entries.extend(format!("{:010} 00000 n\r\n", pdf.len()).bytes()); + pdf.extend(format!("{n} 0 obj\n<< /N {n} >>\nendobj\n").bytes()); + } + let at = pdf.len(); + pdf.extend(format!("xref\n0 {}\n", count + 1).bytes()); + pdf.extend(entries); + pdf.extend(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{at}\n%%EOF", count + 1).bytes()); + pdf + } + + /// A small linear congruential generator, so every run makes the same edits. + struct Rng(u64); + + impl Rng { + /// A number in `0..n` (0 when `n` is 0). + fn below(&mut self, n: usize) -> usize { + self.0 = self.0.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407); + usize::try_from(self.0 >> 33).unwrap() % n.max(1) + } + + fn bytes(&mut self) -> Vec { + (0..self.below(9)).map(|i| b'a' + u8::try_from(i).unwrap()).collect() + } + } + + /// About `wanted` edits that don't overlap, in shuffled order, at random places among the + /// objects and at object starts: replacements that grow, shrink or remove bytes, edits that end + /// at an object's start, and inserts, several of them at one place. None when `wanted` is 0. + fn edits(pdf: &[u8], xref: &Xref, rng: &mut Rng, wanted: usize) -> Vec { + if wanted == 0 { + return vec![]; + } + let first = b"%PDF-1.7\n".len(); + let mut points: Vec = xref.objects(pdf).into_iter().map(|(_, off)| off).collect(); + points.extend((0..wanted).map(|_| first + rng.below(xref.at() - first + 1))); + points.push(xref.at()); + points.sort_unstable(); + points.dedup(); + let mut out = vec![]; + for w in points.windows(2) { + let (p, q) = (w[0], w[1]); + match rng.below(6) { + 0 => {} + 1 => out.push((p, q, rng.bytes())), + 2 => out.push((p, p, rng.bytes())), + 3 => { + out.push((p, p, rng.bytes())); + out.push((p, p, rng.bytes())); + out.push((p, q.min(p + rng.below(4)), rng.bytes())); + } + 4 => out.push((p + (q - p) / 2, q, rng.bytes())), + _ => out.push((q, q, rng.bytes())), + } + } + for i in (1..out.len()).rev() { + out.swap(i, rng.below(i + 1)); + } + out + } + + fn patch(xref: &Xref, edits: &[Edit], objects: bool) -> Patch { + let mut patch = Patch::new(xref); + for (start, end, with) in edits { + patch.replace(*start, *end, with.clone()); + } + if objects { + patch.add_object(b"<< /Added 1 >>".to_vec()); + patch.trailer_entry(b" /Info 2 0 R"); + } + patch + } + + /// Where `off` lands, by walking every edit: how [`Patch::apply`] found it before [`Moves`]. + fn scan(edits: &[Edit], off: usize) -> usize { + edits.iter().filter(|e| e.1 <= off).fold(off as isize, |o, e| o + e.2.len() as isize - (e.1 - e.0) as isize) as usize + } + + /// [`Patch::apply`] as it was written before [`Moves`], walking every edit for every object. + fn apply_by_scan(mut patch: Patch, pdf: &[u8], xref: &Xref) -> Result, PdfError> { + let bad = |why: &str| PdfError::Write(format!("can't edit the written PDF: {why}")); + patch.edits.sort_by_key(|e| (e.0, e.1)); + if patch.edits.windows(2).any(|w| w[0].1 > w[1].0) || patch.edits.iter().any(|e| e.0 > e.1 || e.1 > xref.at) { + return Err(bad("edits overlap")); + } + let edits = &patch.edits; + let moved = |off: usize| -> usize { scan(edits, off) }; + let added: usize = patch.edits.iter().map(|e| e.2.len()).sum::() + patch.objects.iter().map(|o| o.len() + 32).sum::(); + let mut out = Vec::with_capacity(pdf.len() + added + 64); + let mut at = 0; + for (start, end, new) in edits.iter() { + out.extend_from_slice(pdf.get(at..*start).ok_or_else(|| bad("bad edit"))?); + out.extend_from_slice(new); + at = *end; + } + out.extend_from_slice(pdf.get(at..xref.at).ok_or_else(|| bad("bad edit"))?); + let mut offsets = Vec::with_capacity(patch.objects.len()); + for (i, body) in patch.objects.iter().enumerate() { + offsets.push(out.len()); + out.extend_from_slice(format!("{} 0 obj\n", patch.size + i).as_bytes()); + out.extend_from_slice(body); + out.extend_from_slice(b"\nendobj\n"); + } + let table = out.len(); + let size = patch.size + patch.objects.len(); + out.extend_from_slice(format!("xref\n0 {size}\n").as_bytes()); + let old = pdf.get(xref.entries..xref.entries + 20 * xref.count).ok_or_else(|| bad("bad cross-reference table"))?; + for e in old.chunks(20) { + match number(e, 0) { + Some((off, _)) if e.get(17) == Some(&b'n') => { + out.extend_from_slice(format!("{:010}", moved(off)).as_bytes()); + out.extend_from_slice(e.get(10..).unwrap_or_default()); + } + _ => out.extend_from_slice(e), + } + } + let eol = old.get(18..20).unwrap_or(b"\r\n"); + for off in offsets { + out.extend_from_slice(format!("{off:010} 00000 n").as_bytes()); + out.extend_from_slice(eol); + } + let (ts, te) = xref.trailer; + let dict = pdf.get(ts..te.saturating_sub(2)).ok_or_else(|| bad("bad trailer"))?; + let size_at = find(dict, b"/Size", 0).ok_or_else(|| bad("the trailer has no size"))? + 5; + let (_, size_end) = number(dict, size_at).ok_or_else(|| bad("the trailer has no size"))?; + let (Some(head), Some(tail)) = (dict.get(..size_at), dict.get(size_end..)) else { return Err(bad("bad trailer")) }; + out.extend_from_slice(b"trailer\n"); + out.extend_from_slice(head); + out.extend_from_slice(format!(" {size}").as_bytes()); + out.extend_from_slice(tail); + out.extend_from_slice(&patch.trailer); + out.extend_from_slice(format!(">>\nstartxref\n{table}\n%%EOF").as_bytes()); + Ok(out) + } + + #[test] + fn every_offset_moves_by_the_edits_that_end_at_or_before_it() { + let mut rng = Rng(7661); + for round in 0..100 { + let pdf = written(1 + rng.below(30), |n| n % 7 == 3); + let xref = Xref::read(&pdf).unwrap(); + let mut edits = edits(&pdf, &xref, &mut rng, [0, 1, 3, 20, 80][round % 5]); + edits.sort_by_key(|e| (e.0, e.1)); + let moves = Moves::new(&edits).unwrap(); + for off in 0..=pdf.len() { + assert_eq!(moves.at(off), Some(scan(&edits, off)), "round {round}, offset {off}, edits {edits:?}"); + } + } + } + + #[test] + fn apply_writes_the_bytes_a_walk_of_every_edit_wrote() { + let mut rng = Rng(1378); + for round in 0..300 { + let pdf = written(1 + rng.below(40), |n| n % 7 == 3); + let xref = Xref::read(&pdf).unwrap(); + let edits = edits(&pdf, &xref, &mut rng, [0, 1, 3, 20, 80][round % 5]); + let objects = round % 3 == 0; + let fast = patch(&xref, &edits, objects).apply(&pdf, &xref).unwrap(); + let walked = apply_by_scan(patch(&xref, &edits, objects), &pdf, &xref).unwrap(); + assert_eq!(String::from_utf8_lossy(&fast), String::from_utf8_lossy(&walked), "round {round}"); + } + } + + #[test] + fn every_entry_points_at_its_object_after_the_edits() { + let pdf = written(30, |n| n % 7 == 3); + let xref = Xref::read(&pdf).unwrap(); + let mut patch = Patch::new(&xref); + for (n, off) in xref.objects(&pdf) { + let (at, end) = xref.dict(&pdf, n).unwrap(); + match n % 4 { + 0 => patch.replace(at, at, b" /Grown [1 2 3]".to_vec()), + 1 => patch.replace(at, end, b">>\n".to_vec()), + // An insert at an object's start goes before the object. + 2 => patch.replace(off, off, b"% before\n".to_vec()), + _ => {} + } + } + let added = patch.add_object(b"<< /Added 1 >>".to_vec()); + let out = patch.apply(&pdf, &xref).unwrap(); + let after = Xref::read(&out).unwrap(); + assert_eq!((after.count(), added), (32, 31)); + for n in 1..32u32 { + let Some(off) = after.offset(&out, n) else { + assert!(n % 7 == 3, "object {n} is in use"); + let e = xref.entries + 20 * n as usize; + assert_eq!(out[after.entries + 20 * n as usize..][..20], pdf[e..e + 20], "free entry {n}"); + continue; + }; + assert!(out[off..].starts_with(format!("{n} 0 obj\n").as_bytes()), "object {n} at {off}"); + } + } + + #[test] + fn an_object_moved_past_ten_digits_is_refused() { + let mut pdf = written(2, |_| false); + let entry = Xref::read(&pdf).unwrap().entries + 40; + // Object 2's entry gives the last offset ten digits hold. + pdf[entry..entry + 10].copy_from_slice(b"9999999999"); + let xref = Xref::read(&pdf).unwrap(); + let out = Patch::new(&xref).apply(&pdf, &xref).unwrap(); + assert!(find(&out, b"9999999999 00000 n\r\n", 0).is_some()); + let mut patch = Patch::new(&xref); + patch.replace(9, 9, b"%\n".to_vec()); + let refused = patch.apply(&pdf, &xref); + assert!(matches!(&refused, Err(PdfError::Write(why)) if why.contains("cross-reference table holds")), "{refused:?}"); + } + + /// CPU time this thread has used, where the system reports it (`/proc` on Linux). + fn thread_cpu() -> Option { + let stat = std::fs::read_to_string("/proc/thread-self/schedstat").ok()?; + stat.split_whitespace().next()?.parse().ok().map(Duration::from_nanos) + } + + /// How long `f` takes, in thread CPU time where the system reports it, else wall time. + fn time(f: impl FnOnce() -> T) -> (Duration, T) { + let (cpu, wall) = (thread_cpu(), Instant::now()); + let out = f(); + (thread_cpu().zip(cpu).map_or_else(|| wall.elapsed(), |(b, a)| b.saturating_sub(a)), out) + } + + fn median(mut runs: Vec) -> Duration { + runs.sort_unstable(); + runs[runs.len() / 2] + } + + /// `cargo test --release -p vectorcraft-pdf --lib patch::tests::bench -- --ignored --nocapture`. + /// The edits are those of forms in overprint: two inside each form's stream (its `/Length` and + /// data) and an insert into its dictionary, for `n` forms among `n + 20` objects. Each run + /// applies the patch `reps` times, so that small files take long enough for the clock. + #[test] + #[ignore = "timing; run explicitly"] + fn bench_apply_with_many_edits() { + println!("clock: {}", if thread_cpu().is_some() { "thread CPU time" } else { "wall time" }); + println!("| forms | objects | edits | walk every edit (median of 7) | binary search (median of 7) |"); + println!("| ---: | ---: | ---: | ---: | ---: |"); + for n in [100, 1_000, 5_000, 20_000] { + let pdf = written(n + 20, |_| false); + let xref = Xref::read(&pdf).unwrap(); + let mut edits = vec![]; + for (obj, _) in xref.objects(&pdf).into_iter().take(n) { + let (at, _) = xref.dict(&pdf, obj).unwrap(); + edits.push((at, at + 1, b" /Length 120 ".to_vec())); + edits.push((at + 1, at + 3, b"/Data".to_vec())); + edits.push((at + 3, at + 3, b" /Resources << /ExtGState << /GS0 9 0 R >> >>".to_vec())); + } + let reps = (200_000_000 / (3 * n * n)).clamp(1, 2_000); + let (mut walked, mut searched) = (vec![], vec![]); + for _ in 0..7 { + let (t, old) = time(|| (0..reps).fold(None, |_, _| apply_by_scan(patch(&xref, &edits, false), &pdf, &xref).ok())); + walked.push(t); + let (t, new) = time(|| (0..reps).fold(None, |_, _| patch(&xref, &edits, false).apply(&pdf, &xref).ok())); + searched.push(t); + assert!(old.is_some() && old == new, "{n} forms: the files differ"); + } + let ms = |d: Duration| d.as_secs_f64() * 1000.0 / reps as f64; + println!("| {n} | {} | {} | {:.3} ms | {:.3} ms |", n + 20, edits.len(), ms(median(walked)), ms(median(searched))); + } + } +} diff --git a/crates/pdf/src/pdfx.rs b/crates/pdf/src/pdfx.rs index 2313d62129..67c71d5dbc 100644 --- a/crates/pdf/src/pdfx.rs +++ b/crates/pdf/src/pdfx.rs @@ -4,9 +4,11 @@ //! - PDF/X-1a:2001: every colour is CMYK, grey or a spot ink with a CMYK alternate (colours and //! images are converted to a CMYK destination and written untagged, see [`crate::output`]), no //! transparency (the app flattens it before writing), no layers, PDF 1.3. -//! - PDF/X-3:2002: colours are ICC-based (always tagged), no transparency, no layers, PDF 1.3. -//! - PDF/X-4:2010: transparency and layers are kept, colours are tagged, PDF 1.6 at most, and the -//! XMP metadata names the standard too and carries `xmp:MetadataDate`. +//! - PDF/X-3:2002: colors are ICC-based (always tagged), except CMYK colors in the CMYK output +//! intent's profile, which are DeviceCMYK (with `profiles` `none`, all CMYK colors unless they +//! are converted to a CMYK destination of another profile), no transparency, no layers, PDF 1.3. +//! - PDF/X-4:2010: transparency and layers are kept, colors are tagged as in PDF/X-3, PDF 1.6 at +//! most, and the XMP metadata names the standard too and carries `xmp:MetadataDate`. //! - All of them: a `/GTS_PDFX` output intent (blank, the CMYK profile in effect, embedded), a //! TrimBox on every page (the artboard), `/Trapped` True or False, `/GTS_PDFXVersion` in the //! document information, a title and dates, embedded fonts (or text as outlines), no editing diff --git a/crates/pdf/src/print/plates.rs b/crates/pdf/src/print/plates.rs index 74102373e5..5b33683dcf 100644 --- a/crates/pdf/src/print/plates.rs +++ b/crates/pdf/src/print/plates.rs @@ -171,10 +171,11 @@ impl<'a> Separator<'a> { /// swatch link). Any ink above zero puts ink down, except on PostScript plates for a color that /// counts as 100% black ([`vectorcraft_doc::overprint::is_black_ink`], as /// [`vectorcraft_doc::overprint::OverprintBlack::default`] judges it) and is not linked to a - /// spot swatch, to Registration or to a swatch the document lacks: up to the half a percent of - /// another ink such a black may carry counts as none. + /// spot swatch or to Registration: up to the half a percent of another ink such a black may + /// carry counts as none. A link to a swatch the document lacks separates as the color's own + /// values, so such a black counts as unlinked. fn no_ink(&self, plate: &str, p: &Paint) -> bool { - let process = |swatch: Option<&str>| swatch.is_none_or(|n| n != REGISTRATION && self.doc.swatch(n).is_some_and(|w| !w.spot)); + let process = |swatch: Option<&str>| swatch.is_none_or(|n| n != REGISTRATION && self.doc.swatch(n).is_none_or(|w| !w.spot)); let none = |c: &Color, process: bool, ink: f32| ink <= 0.0 || (self.postscript && process && ink <= 0.005 && is_black_ink(c, 1.0, false)); match p { Paint::Solid { color, swatch, tint } => { diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index 91c037ad84..e2abe87637 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -1449,6 +1449,41 @@ fn empty_and_populated_file_info_preserve_key_presence() { assert!(s.contains("/ViewerPreferences<>"), "viewers should show the document title (#3646)"); } +/// The text of the `/Lang` entry of the catalog of `pdf` (a literal string), if any. +fn catalog_lang(pdf: &[u8]) -> Option { + let xref = crate::patch::Xref::read(pdf).expect("a cross-reference table"); + let root = xref.trailer_ref(pdf, b"/Root").expect("a catalog"); + let (start, end) = xref.dict(pdf, root).expect("the catalog's dictionary"); + let catalog = String::from_utf8_lossy(&pdf[start..end]).into_owned(); + let at = catalog.find("/Lang")? + "/Lang".len(); + let rest = catalog[at..].trim_start().strip_prefix('(').expect("a literal string"); + Some(rest[..rest.find(')').expect("a closed string")].to_string()) +} + +/// The catalog gives the document language chosen in Document Setup as its BCP 47 tag, in +/// exported and printed PDFs, and the XMP packet says it too (#3644). +#[test] +fn the_catalog_gives_the_document_language() { + let mut d = doc(100.0, 100.0); + for (language, tag) in [(None, "en-US"), (Some("French"), "fr"), (Some("German: Swiss"), "de-CH")] { + if let Some(language) = language { + d.setup.language = language.into(); + } + for opts in [PdfOptions::uncompressed(), PdfOptions::default()] { + let bytes = export(&d, &opts).unwrap(); + assert_eq!(catalog_lang(&bytes).as_deref(), Some(tag), "{language:?}"); + } + // Print to PDF writes its file with the same writer. + let printed = print(&d, &PrintOptions { created: Some(1_700_000_000), ..Default::default() }).unwrap(); + assert_eq!(catalog_lang(&printed.bytes).as_deref(), Some(tag), "{language:?}: printed"); + let s = uncompressed(&d); + assert!(s.contains(&format!("{tag}")), "{language:?}: {s}"); + } + // A language without a tag (from a file) writes none rather than a guess. + d.setup.language = "Klingon".into(); + assert_eq!(catalog_lang(&export(&d, &PdfOptions::uncompressed()).unwrap()), None); +} + /// A function or colour space built on itself is refused before the interpreter builds it (by /// recursion, with no cap: a stack overflow), and those of real files are read. #[test] diff --git a/crates/pdf/src/tests/cmykimages.rs b/crates/pdf/src/tests/cmykimages.rs index 4d22a10ee6..ec157a8182 100644 --- a/crates/pdf/src/tests/cmykimages.rs +++ b/crates/pdf/src/tests/cmykimages.rs @@ -36,21 +36,33 @@ fn stream(dict: &str, data: &[u8]) -> Vec { /// A 300 × 100 pt page with a CMYK rectangle and image XObjects `images` (dictionary entries /// after the type, stream data), 50 pt wide each: objects 5…, then the `extra` objects. fn pdf_with_images(images: &[(String, Vec)], extra: &[Vec]) -> Vec { + pdf_with(images, extra, "", "") +} + +/// [`pdf_with_images`] with `catalog` added to the catalog's entries and `resources` to the +/// page's resources. +fn pdf_with(images: &[(String, Vec)], extra: &[Vec], catalog: &str, resources: &str) -> Vec { let xobjects: String = (0..images.len()).map(|i| format!("/Im{i} {} 0 R ", 5 + i)).collect(); let mut content = String::from("0 1 0.6 0.2 k 0 80 300 20 re f\n"); for i in 0..images.len() { content.push_str(&format!("q 50 0 0 50 {} 10 cm /Im{i} Do Q\n", 10 + 60 * i)); } let mut objs = vec![ - b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(), + format!("<< /Type /Catalog /Pages 2 0 R {catalog}>>").into_bytes(), b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(), - format!("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 100] /Resources << /XObject << {xobjects}>> >> /Contents 4 0 R >>").into_bytes(), + format!("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 100] /Resources << /XObject << {xobjects}>> {resources}>> /Contents 4 0 R >>") + .into_bytes(), stream("", content.as_bytes()), ]; for (dict, data) in images { objs.push(stream(&format!("/Type /XObject /Subtype /Image {dict}"), data)); } objs.extend_from_slice(extra); + pdf_of(&objs) +} + +/// A PDF file of `objs`, numbered from 1, whose catalog is object 1. +fn pdf_of(objs: &[Vec]) -> Vec { let mut out = b"%PDF-1.4\n".to_vec(); let mut at = vec![]; for (i, o) in objs.iter().enumerate() { @@ -164,8 +176,9 @@ fn a_cmyk_jpeg_passes_through_open_and_every_pdf_export() { (json!({}), "DeviceCMYK", None), (json!({"output": {"conversion": "preserveNumbers"}}), "DeviceCMYK", None), (json!({"standard": "pdfX1a"}), "DeviceCMYK", None), - (json!({"standard": "pdfX3"}), "ICCBased", Some(4)), - (json!({"standard": "pdfX4"}), "ICCBased", Some(4)), + // CMYK in the output intent's profile (the CMYK profile in effect) is DeviceCMYK. + (json!({"standard": "pdfX3"}), "DeviceCMYK", None), + (json!({"standard": "pdfX4"}), "DeviceCMYK", None), (json!({"output": {"profiles": "all"}}), "ICCBased", Some(4)), ] { let out = export_with_report(&r.document, &opts(settings.clone())).unwrap(); @@ -178,12 +191,14 @@ fn a_cmyk_jpeg_passes_through_open_and_every_pdf_export() { assert!(out.warnings.iter().all(|w| !w.contains("image")), "{settings}: {:?}", out.warnings); // And open again: the same JPEG, carrying the profile it was written in when it was // ICC-based. + // ICC-based, or DeviceCMYK in a PDF/X file, whose output intent's profile it then carries. let back = import(&out.bytes).unwrap(); let blob = blobs(&back)[0]; - if icc_n.is_some() { + let intent = settings.get("standard").is_some().then(|| cms::icc_bytes(&cms::active_settings().cmyk).unwrap().to_vec()); + if let Some(icc) = w[0].icc.clone().or(intent) { assert_eq!(blob.mime, "image/jpeg", "{settings}"); assert_eq!(blob.cmyk(), b[0].cmyk(), "{settings}: the same samples"); - assert_eq!(blob.cmyk_icc_profile(), w[0].icc, "{settings}: the profile it was written in"); + assert_eq!(blob.cmyk_icc_profile().as_deref(), Some(&*icc), "{settings}: the profile it was written in"); } else { assert_eq!(blob.bytes.as_slice(), jpg.as_slice(), "{settings}"); } @@ -645,6 +660,117 @@ fn a_cmyk_image_that_keeps_its_numbers_carries_its_cmyk_profile() { assert!(!String::from_utf8_lossy(&bytes).contains("/S/Luminosity"), "no luminosity soft mask"); } +/// When CMYK colors are DeviceCMYK in the output intent's profile, a CMYK image that carries that +/// profile is DeviceCMYK too, and with `none` so is one that carries another profile; elsewhere +/// it keeps its own (#1954). +#[test] +fn a_cmyk_image_in_the_output_intents_profile_is_device_cmyk() { + let ink = [0u8, 102, 255, 0]; + let working = cms::icc_bytes(&cms::active_settings().cmyk).unwrap(); + let other = cmyk_profile(|_| {}); + let export = |icc: &[u8], s: serde_json::Value| { + let tiff = cmyk_tiff_with(ink, 4, 4, icc); + let inks = tiff.cmyk().unwrap().data; + let d = image_doc(tiff, 4, 4); + let out = export_with_report(&d, &opts(s.clone())).unwrap_or_else(|e| panic!("{s}: {e}")); + let w: Vec = written(&out.bytes).into_iter().filter(|w| w.space != "DeviceGray").collect(); + assert_eq!(w.len(), 1, "{s}: {w:?}"); + assert_eq!(blobs(&import(&out.bytes).unwrap())[0].cmyk().unwrap().data, inks, "{s}: the inks as they were"); + w.into_iter().next().unwrap() + }; + for s in [json!({"standard": "pdfX4"}), json!({"standard": "pdfX3"}), json!({"standard": "pdfX4", "output": {"profiles": "none"}})] { + let w = export(&working, s.clone()); + assert_eq!((w.space.as_str(), w.icc_n), ("DeviceCMYK", None), "{s}: the output intent's profile"); + } + let w = export(&other, json!({"standard": "pdfX4"})); + assert!((w.space.as_str(), w.icc.as_deref()) == ("ICCBased", Some(other.as_slice())), "another profile is kept: {w:?}"); + let w = export(&other, json!({"standard": "pdfX4", "output": {"profiles": "none"}})); + assert_eq!((w.space.as_str(), w.icc_n), ("DeviceCMYK", None), "with none: {w:?}"); + // Without an output intent, the image keeps the profile it carries. + let w = export(&working, json!({"output": {"profiles": "all"}})); + assert!(w.space == "ICCBased" && w.icc.as_deref() == Some(&*working), "{w:?}"); +} + +/// A DeviceCMYK image in a file with a PDF/X output intent of CMYK opens tagged with the intent's +/// profile, so a CMYK image written as DeviceCMYK in that profile opens with it again. Without an +/// output intent it opens untagged. +#[test] +fn a_device_cmyk_image_opens_with_the_pdfx_output_intents_profile() { + let ink = [0u8, 102, 255, 0]; + let working = cms::icc_bytes(&cms::active_settings().cmyk).unwrap(); + for (s, tagged) in [(json!({"standard": "pdfX4"}), true), (json!({"standard": "pdfX3"}), true), (json!({}), false)] { + let d = image_doc(cmyk_tiff_with(ink, 4, 4, &working), 4, 4); + let out = export_with_report(&d, &opts(s.clone())).unwrap_or_else(|e| panic!("{s}: {e}")); + let w: Vec = written(&out.bytes).into_iter().filter(|w| w.space != "DeviceGray").collect(); + assert!(w.len() == 1 && w[0].space == "DeviceCMYK", "{s}: {w:?}"); + let opened = import(&out.bytes).unwrap(); + let icc = blobs(&opened)[0].cmyk_icc_profile(); + assert_eq!(icc.as_deref(), tagged.then_some(&*working), "{s}"); + } +} + +/// In a file whose catalog has a CMYK `/GTS_PDFX` output intent, a DeviceCMYK image opens tagged +/// with the intent's profile; another kind of output intent tags nothing, and neither does the +/// intent on a page whose resources replace DeviceCMYK with a `/DefaultCMYK`. +#[test] +fn a_device_cmyk_image_takes_the_output_intent_unless_a_default_cmyk_replaces_it() { + let (intent, other) = (cmyk_profile(|_| {}), cms::icc_bytes(&cms::active_settings().cmyk).unwrap().to_vec()); + assert_ne!(intent, other); + let image = [(cmyk_dict(2, 2, ""), flat([0, 102, 255, 0], 4))]; + let profiles = [stream("/N 4", &intent), stream("/N 4", &other)]; + let pdfx = "/OutputIntents [<< /Type /OutputIntent /S /GTS_PDFX /OutputConditionIdentifier (Test) /DestOutputProfile 6 0 R >>] "; + let pdfa = "/OutputIntents [<< /Type /OutputIntent /S /GTS_PDFA1 /OutputConditionIdentifier (Test) /DestOutputProfile 6 0 R >>] "; + let default_cmyk = "/ColorSpace << /DefaultCMYK [/ICCBased 7 0 R] >> "; + for (catalog, resources, expected) in [(pdfx, "", Some(&intent)), ("", "", None), (pdfa, "", None), (pdfx, default_cmyk, None)] { + let d = import(&pdf_with(&image, &profiles, catalog, resources)).unwrap(); + let b = blobs(&d); + assert_eq!(b.len(), 1, "{catalog} {resources}"); + assert_eq!(b[0].cmyk().unwrap().data, flat([0, 102, 255, 0], 4), "{catalog} {resources}: the inks as they were"); + assert_eq!(b[0].cmyk_icc_profile().as_deref(), expected.map(Vec::as_slice), "{catalog} {resources}"); + } +} + +/// A `/DefaultCMYK` stops the output intent from tagging a DeviceCMYK image only where it is in +/// scope: on the page's own image when only a form on the page has one, the image keeps the +/// intent's profile; drawn inside that form, it opens untagged; and the same image drawn on a page +/// with a `/DefaultCMYK` and then on a page without one opens untagged on the first and tagged on +/// the second. +#[test] +fn the_output_intent_tags_a_device_cmyk_image_only_where_no_default_cmyk_is_in_scope() { + let (intent, other) = (cmyk_profile(|_| {}), cms::icc_bytes(&cms::active_settings().cmyk).unwrap().to_vec()); + let default = "/ColorSpace << /DefaultCMYK [/ICCBased 8 0 R] >>"; + // Objects: 1 catalog, 2 pages, 3 and 4 the pages, 5 their content, 6 the image, 7 and 8 the + // profiles, 9 a form with a `/DefaultCMYK`. + let file = |pages: &[&str], content: &str, form: &str| { + let kids: String = (0..pages.len()).map(|i| format!("{} 0 R ", 3 + i)).collect(); + let page = |res: &str| format!("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 100] /Resources << {res} >> /Contents 5 0 R >>").into_bytes(); + let form_dict = format!("/Type /XObject /Subtype /Form /BBox [0 0 1 1] /Resources << /XObject << /Im0 6 0 R >> {default} >>"); + pdf_of(&[ + b"<< /Type /Catalog /Pages 2 0 R /OutputIntents [<< /Type /OutputIntent /S /GTS_PDFX /OutputConditionIdentifier (Test) /DestOutputProfile 7 0 R >>] >>".to_vec(), + format!("<< /Type /Pages /Kids [{kids}] /Count {} >>", pages.len()).into_bytes(), + page(pages[0]), + page(pages.get(1).copied().unwrap_or("")), + stream("", content.as_bytes()), + stream(&format!("/Type /XObject /Subtype /Image {}", cmyk_dict(2, 2, "")), &flat([0, 102, 255, 0], 4)), + stream("/N 4", &intent), + stream("/N 4", &other), + stream(&form_dict, form.as_bytes()), + ]) + }; + let image = "q 50 0 0 50 10 10 cm /Im0 Do Q "; + let form = "q 50 0 0 50 80 10 cm /Fm0 Do Q "; + let cases = [ + (file(&["/XObject << /Im0 6 0 R /Fm0 9 0 R >>"], &format!("{image}{form}"), "0 0 0 1 k 0 0 1 1 re f"), vec![Some(&intent)]), + (file(&["/XObject << /Fm0 9 0 R >>"], form, "/Im0 Do"), vec![None]), + (file(&[&format!("/XObject << /Im0 6 0 R >> {default}"), "/XObject << /Im0 6 0 R >>"], image, ""), vec![None, Some(&intent)]), + ]; + for (i, (bytes, expected)) in cases.into_iter().enumerate() { + let d = import(&bytes).unwrap(); + let profiles: Vec>> = all_images(&d).iter().map(|b| b.cmyk_icc_profile().map(|p| p.to_vec())).collect(); + assert_eq!(profiles, expected.into_iter().map(|p| p.cloned()).collect::>(), "case {i}"); + } +} + /// With Don't Include Profiles set, a CMYK JPEG kept as it is is DeviceCMYK without its own /// `ICC_PROFILE` segments, its compressed inks unchanged; one resampled and compressed again is /// written without a profile too. Left unset, the JPEG data stays as it is. @@ -672,6 +798,16 @@ fn a_set_dont_include_profiles_takes_a_cmyk_jpegs_profile_out() { let s = json!({"output": {"profiles": "none"}, "compression": {"color": {"downsample": "bicubic", "ppi": 72.0, "abovePpi": 100.0}}}); let (w, _) = export(s.clone()); assert!(w.icc.is_none() && !segment(&w.data), "{s}: {w:?}"); + // A PDF/X file whose CMYK colors are DeviceCMYK takes the profile out of a JPEG it untags. + let s = json!({"standard": "pdfX4", "output": {"profiles": "none"}}); + let (w, _) = export(s.clone()); + assert!(w.space == "DeviceCMYK" && w.data == vectorcraft_doc::cmyk::jpeg_without_icc(&jpg).unwrap(), "{s}: {w:?}"); + let working = cms::icc_bytes(&cms::active_settings().cmyk).unwrap(); + let own = cmyk_jpeg_with(&flat(ink, 64 * 64), 64, 64, &working); + let d = image_doc(ImageBlob::new("image/jpeg", own.clone()), 64, 64); + let out = export_with_report(&d, &opts(json!({"standard": "pdfX4"}))).unwrap(); + let w: Vec = written(&out.bytes).into_iter().filter(|w| w.space != "DeviceGray").collect(); + assert!(w.len() == 1 && w[0].space == "DeviceCMYK" && w[0].data == vectorcraft_doc::cmyk::jpeg_without_icc(&own).unwrap(), "{w:?}"); } /// A CMYK JPEG kept as it is whose header declares far more pixels than the app reads is left out diff --git a/crates/pdf/src/tests/editing.rs b/crates/pdf/src/tests/editing.rs index c4f2900709..b58c953c2f 100644 --- a/crates/pdf/src/tests/editing.rs +++ b/crates/pdf/src/tests/editing.rs @@ -237,3 +237,104 @@ fn a_file_name_written_as_utf16_is_found() { assert_eq!(e.data, b"hello", "/{key}"); } } + +#[test] +fn an_editing_file_whose_data_cannot_be_resolved_is_still_listed() { + // No `EF` dictionary, an `EF` without `F` or `UF`, and an `F` naming no object. + for ef in ["", "/EF << >>", "/EF << /F 9 0 R >>"] { + let objects = [ + "<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_string(), + "<< /Type /Pages /Kids [5 0 R] /Count 1 >>".to_string(), + "<< /Names [(a) 4 0 R] >>".to_string(), + format!("<< /Type /Filespec /UF ({EDITING_FILE}) {ef} >>"), + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>".to_string(), + ]; + let opened = open_pdf(&raw_pdf(&objects), None).unwrap(); + assert_eq!(opened.editing(), None, "{ef:?}"); + assert!(opened.has_editing_file(), "{ef:?}"); + } + // A name tree key naming it, with a file specification that names no object or isn't one. + for spec in ["9 0 R", "(not a file specification)"] { + let objects = [ + "<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_string(), + "<< /Type /Pages /Kids [4 0 R] /Count 1 >>".to_string(), + format!("<< /Names [(a) 9 0 R ({EDITING_FILE}) {spec}] >>"), + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>".to_string(), + ]; + let opened = open_pdf(&raw_pdf(&objects), None).unwrap(); + assert_eq!(opened.editing(), None, "{spec}"); + assert!(opened.has_editing_file(), "{spec}"); + } + // The key written as an indirect string. + let objects = [ + "<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_string(), + "<< /Type /Pages /Kids [4 0 R] /Count 1 >>".to_string(), + "<< /Names [5 0 R 9 0 R] >>".to_string(), + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>".to_string(), + format!("({EDITING_FILE})"), + ]; + assert!(open_pdf(&raw_pdf(&objects), None).unwrap().has_editing_file()); + // A PDF without the editing file, and one with it. + assert!(!open_pdf(&export(&doc(), &PdfOptions::default()).unwrap(), None).unwrap().has_editing_file()); + let opened = open_pdf(&pdf_with(Some(b"native"), false).bytes, None).unwrap(); + assert!(opened.editing().is_some() && opened.has_editing_file()); +} + +#[test] +fn an_editing_file_deep_in_the_name_tree_is_found() { + // Objects 4..=203 are a chain of 200 name tree nodes, each listing the next one; the editing + // file sits in the leaf (object 204), with its data or naming data that can't be resolved. + for ef in ["/EF << /F 206 0 R >>", "/EF << /F 999 0 R >>"] { + let mut objects = vec![ + "<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_string(), + "<< /Type /Pages /Kids [207 0 R] /Count 1 >>".to_string(), + "<< /Kids [4 0 R] >>".to_string(), + ]; + for node in 4..=203 { + objects.push(format!("<< /Kids [{} 0 R] >>", node + 1)); + } + objects.push("<< /Names [(a) 205 0 R] >>".to_string()); + objects.push(format!("<< /Type /Filespec /UF ({EDITING_FILE}) {ef} >>")); + objects.push("<< /Length 5 >>\nstream\nhello\nendstream".to_string()); + objects.push("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>".to_string()); + let opened = open_pdf(&raw_pdf(&objects), None).unwrap(); + assert!(opened.has_editing_file(), "{ef}"); + let data = opened.editing().map(|e| e.data); + assert_eq!(data.as_deref(), ef.contains("206").then_some(&b"hello"[..]), "{ef}"); + } + // A name tree with more nodes than are searched may list it. + let objects = [ + "<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_string(), + "<< /Type /Pages /Kids [4 0 R] /Count 1 >>".to_string(), + format!("<< /Kids [{}] >>", "<< /Names [] >> ".repeat(70_000)), + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>".to_string(), + ]; + let opened = open_pdf(&raw_pdf(&objects), None).unwrap(); + assert_eq!(opened.editing(), None); + assert!(opened.has_editing_file() && opened.editing_search_cut()); + // One that lists a readable editing file before the nodes left unsearched and another after + // them: the first is read, and the search reads as cut short. + let leaf = |stream: u32| format!("<< /Names [({EDITING_FILE}) << /Type /Filespec /UF ({EDITING_FILE}) /EF << /F {stream} 0 R >> >>] >>"); + let objects = [ + "<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_string(), + "<< /Type /Pages /Kids [8 0 R] /Count 1 >>".to_string(), + format!("<< /Kids [4 0 R {}5 0 R] >>", "<< /Names [] >> ".repeat(70_000)), + leaf(6), + leaf(7), + "<< /Length 5 >>\nstream\nfirst\nendstream".to_string(), + "<< /Length 6 >>\nstream\nsecond\nendstream".to_string(), + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>".to_string(), + ]; + let opened = open_pdf(&raw_pdf(&objects), None).unwrap(); + assert_eq!(opened.editing().map(|e| e.data).as_deref(), Some(&b"first"[..])); + assert!(opened.has_editing_file() && opened.editing_search_cut()); + // The same, with the nodes past the limit in a subtree after the one holding the first. + let mut objects = objects; + objects[2] = format!("<< /Kids [4 0 R << /Kids [{}5 0 R] >>] >>", "<< /Names [] >> ".repeat(70_000)); + let opened = open_pdf(&raw_pdf(&objects), None).unwrap(); + assert_eq!(opened.editing().map(|e| e.data).as_deref(), Some(&b"first"[..])); + assert!(opened.has_editing_file() && opened.editing_search_cut()); + // A tree searched to its end. + let opened = open_pdf(&pdf_with(Some(b"native"), false).bytes, None).unwrap(); + assert!(opened.editing().is_some() && !opened.editing_search_cut()); +} diff --git a/crates/pdf/src/tests/fx.rs b/crates/pdf/src/tests/fx.rs index cd73c01bb9..709031a6a2 100644 --- a/crates/pdf/src/tests/fx.rs +++ b/crates/pdf/src/tests/fx.rs @@ -1,9 +1,11 @@ -//! Raster effects in PDF export: not written yet, so a fill's, a stroke's or the object's own -//! raster effect is reported. +//! Effects in PDF export: raster effects are not written yet, so a fill's, a stroke's or the +//! object's own raster effect is reported; geometry effects are baked into what the file draws. + +use std::sync::Arc; use vectorcraft_color::{Color, Paint}; -use vectorcraft_doc::{Appearance, Document, Effect, Node, NodeId}; -use vectorcraft_geom::{Rect, shapes}; +use vectorcraft_doc::{Appearance, AppearanceItem, CharStyle, Document, Effect, Node, NodeId, NodeKind, TextObject}; +use vectorcraft_geom::{Point, Rect, shapes}; use crate::*; @@ -27,3 +29,50 @@ fn raster_effects_warn_on_fills_strokes_and_objects() { assert!(warnings(item).iter().any(|w| w.starts_with("raster effects")), "{item:?}"); } } + +/// What `n` paints, in paint order, with consecutive repeats dropped: 'b' for a blue fill, 'r' for a +/// red fill and 'g' for a green stroke, each with whether a clip group clips it. Clipping paths +/// themselves are left out. +fn painted_order(n: &Node, clipped: bool, out: &mut Vec<(char, bool)>) { + let solid = |p: &Paint, r: f32, g: f32, b: f32| matches!(p, Paint::Solid { color, .. } if *color == Color::rgb(r, g, b)); + for i in &n.appearance.items { + let mark = match i { + AppearanceItem::Fill(f) if solid(&f.paint, 0.0, 0.0, 1.0) => 'b', + AppearanceItem::Fill(f) if solid(&f.paint, 1.0, 0.0, 0.0) => 'r', + AppearanceItem::Stroke(s) if s.width > 0.0 && solid(&s.paint, 0.0, 1.0, 0.0) => 'g', + _ => continue, + }; + if out.last() != Some(&(mark, clipped)) { + out.push((mark, clipped)); + } + } + let clips = matches!(n.kind, NodeKind::Group { clip: true, .. }); + for c in n.children().into_iter().flatten().skip(usize::from(clips)) { + painted_order(c, clipped || clips, out); + } +} + +#[test] +fn painted_clipping_type_exports_with_group_effect() { + // Type filled blue and stroked green clips a red square in a group with an Offset Path effect: + // the PDF paints the type's fill inside the clip behind the square, and its stroke over the + // clipped art, outside the clip. + let blue = Paint::solid(Color::rgb(0.0, 0.0, 1.0)); + let green = Paint::solid(Color::rgb(0.0, 1.0, 0.0)); + let style = CharStyle { size: 40.0, fill: blue, stroke: green, stroke_width: 2.0, ..Default::default() }; + let mut d = Document::new(200.0, 200.0); + let text = Node::new(d.alloc_id(), NodeKind::Text(Box::new(TextObject::point(Point::new(5.0, 60.0), "IIII", style)))); + let red = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); + let square = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 200.0)), red); + let clip = Node::new(d.alloc_id(), NodeKind::Group { children: vec![Arc::new(text), Arc::new(square)], clip: true }); + let mut outer = Node::group(d.alloc_id(), vec![Arc::new(clip)]); + outer.appearance.effects.push(Effect { id: "path.offsetPath".into(), params: serde_json::json!({"offset": 1}), visible: true }); + let layer = d.default_layer().unwrap(); + d.insert(Some(layer), 0, outer).unwrap(); + let back = import(&export(&d, &PdfOptions::default()).unwrap()).unwrap(); + let mut order = vec![]; + for l in &back.layers { + painted_order(l, false, &mut order); + } + assert_eq!(order, [('b', true), ('r', true), ('g', false)]); +} diff --git a/crates/pdf/src/tests/import_fidelity.rs b/crates/pdf/src/tests/import_fidelity.rs index 251cc925bf..188ca0e80d 100644 --- a/crates/pdf/src/tests/import_fidelity.rs +++ b/crates/pdf/src/tests/import_fidelity.rs @@ -507,6 +507,56 @@ fn a_form_drawn_many_times_reads_its_font_resources_once() { assert_eq!(walk.fonts.len(), 1); } +/// A Type 3 font that every page lists in a font dictionary of its own, and a form lists in its +/// resources, has its glyph procedures read once for the document. Each page still maps the font's +/// glyphs, and the font whose glyphs set their own color (`d0`) is told from the one whose glyphs +/// don't (`d1`). +#[test] +fn a_type3_font_on_every_page_has_its_glyph_procedures_read_once() { + const PAGES: usize = 6; + let n = first_extra(PAGES); + let (shape, color, shape_a, shape_b, color_a, form) = (n, n + 1, n + 2, n + 3, n + 4, n + 5); + let font = |name: &str, procs: &str| { + format!( + "<< /Type /Font /Subtype /Type3 /Name /{name} /FontBBox [0 0 1000 1000] /FontMatrix [0.001 0 0 0.001 0 0] /CharProcs << {procs} >> /Encoding << /Type /Encoding /Differences [97 /a /b] >> /FirstChar 97 /LastChar 98 /Widths [1000 1000] /Resources << >> >>" + ) + }; + let objects = [ + font("Vcshape", &format!("/a {shape_a} 0 R /b {shape_b} 0 R")), + font("Vccolor", &format!("/a {color_a} 0 R /b {color_a} 0 R")), + stream("", "1000 0 0 0 1000 1000 d1 0 0 1000 1000 re f"), + stream("", "1000 0 0 0 1000 1000 d1 0 0 500 500 re f"), + stream("", "1000 0 d0 1 0 0 rg 0 0 1000 1000 re f"), + stream( + &format!("/Type /XObject /Subtype /Form /BBox [0 0 100 100] /Resources << /Font << /C {color} 0 R /S {shape} 0 R >> >>"), + "BT /S 12 Tf (ab) Tj /C 12 Tf (ab) Tj ET", + ), + ]; + let pages: Vec = (0..PAGES) + .map(|_| PdfPage { + resources: format!("/Font << /S {shape} 0 R /C {color} 0 R >> /XObject << /X0 {form} 0 R >>"), + ..PdfPage::new(100.0, 100.0, "BT /S 24 Tf 10 30 Td (ab) Tj /C 24 Tf (ab) Tj ET /X0 Do") + }) + .collect(); + let extra: Vec<&str> = objects.iter().map(String::as_str).collect(); + let pdf = craft_pdf::syntax::Pdf::new(pdf_with(&pages, &extra, None)).unwrap(); + let mut fonts = crate::import_scan::FontNames::new(); + let mut ocgs = crate::import_scan::Ocgs::read(&pdf); + crate::import_scan::TEST_CHARPROC_DECODES.with(|d| d.set(0)); + for page in pdf.pages().iter() { + let scan = crate::import_scan::scan_page(page, &mut ocgs, false, &mut fonts, pdf.decode_limits().max_decoded_stream()).unwrap(); + let mapped: std::collections::HashSet<(u128, bool)> = scan.type3_cache_map.values().copied().collect(); + let noted: std::collections::HashSet<(u128, bool)> = fonts.keys().map(|k| (*k, false)).collect(); + assert_eq!(scan.type3_cache_map.len(), 2 * 257); + assert_eq!(mapped, noted); + let mut colors: Vec<(String, bool)> = fonts.values().map(|f| (f.name.clone(), f.is_colour)).collect(); + colors.sort(); + assert_eq!(colors, [("Vccolor".to_string(), true), ("Vcshape".to_string(), false)]); + } + // The `d1` font's two procedures and the `d0` font's one. + assert_eq!(crate::import_scan::TEST_CHARPROC_DECODES.with(std::cell::Cell::get), 3); +} + /// A value of the page's font dictionary that the reader can't parse (a name with a broken `#` /// escape, a number with a stray `-`) is left out when the page's fonts are noted, and the fonts /// after it are noted. diff --git a/crates/pdf/src/tests/output.rs b/crates/pdf/src/tests/output.rs index 71461ae1f8..d9c2fedc1d 100644 --- a/crates/pdf/src/tests/output.rs +++ b/crates/pdf/src/tests/output.rs @@ -591,39 +591,96 @@ fn standard_pdf(d: &Document, settings: Value) -> ExportReport { export_with_report(d, &PdfOptions { settings, created: Some(1_700_000_000), ..Default::default() }).unwrap() } +/// The output intent's profile, decoded, of `bytes`. +fn intent_profile(bytes: &[u8]) -> Vec { + let mut out = vec![]; + output_intent(bytes, None, |oi| out = oi.get::>(b"DestOutputProfile").unwrap().decoded().unwrap().into_owned()); + out +} + +/// CMYK colors in the profile of a CMYK output intent are DeviceCMYK, which the output intent +/// describes: no ICC-based CMYK space carries the same profile, and it is embedded once (#1954). #[test] -fn a_profile_that_tags_colours_and_is_the_output_intent_is_embedded_once() { - let d = doc(ColorMode::Cmyk, &[Color::cmyk(0.1, 0.2, 0.3, 0.4)]); +fn cmyk_colors_in_the_output_intents_profile_are_device_cmyk() { + let ink = [0.1, 0.2, 0.3, 0.4]; + let d = doc(ColorMode::Cmyk, &[Color::cmyk(ink[0], ink[1], ink[2], ink[3])]); let working = cms::active_settings().cmyk; let icc = cms::icc_bytes(&working).unwrap(); for set in [ json!({"standard": "pdfX4"}), json!({"standard": "pdfX4", "output": {"outputIntent": working}}), - // PDF/X-3 and PDF/X-4 always tag their colours: `profiles` doesn't apply. json!({"standard": "pdfX4", "output": {"profiles": "none", "outputIntent": working}}), json!({"standard": "pdfX3"}), - json!({"output": {"profiles": "all", "outputIntent": working}}), ] { let r = standard_pdf(&d, set.clone()); - let streams = icc_streams(&r.bytes); - assert_eq!(streams.len(), 1, "{set}: ICC profile streams"); - assert!(streams[0] == *icc, "{set}: the working CMYK profile"); - assert!(colours(&r.bytes).iter().all(|c| c.0 == "scn"), "{set}: tagged colours"); - output_intent(&r.bytes, None, |oi| assert_eq!(oi.get::>(b"DestOutputProfile").unwrap().decoded().unwrap().as_ref(), &*icc)); + assert!(r.warnings.is_empty(), "{set}: {:?}", r.warnings); + assert!(icc_streams(&r.bytes) == [icc.to_vec()], "{set}: the working CMYK profile, once"); + assert!(icc_profiles(&r.bytes).is_empty(), "{set}: no ICC-based color space"); + let c = colours(&r.bytes); + assert!(c.len() == 1 && c[0].0 == "k" && close(&c[0].1, &ink), "{set}: DeviceCMYK, the numbers kept: {c:?}"); + assert!(intent_profile(&r.bytes) == *icc, "{set}"); } - // Another output intent profile is its own stream. + // Another output intent's profile: CMYK colors keep their own, and both are embedded. + let other = cms::icc_bytes(DEVICE_CMYK).unwrap(); let r = standard_pdf(&d, json!({"standard": "pdfX4", "output": {"outputIntent": DEVICE_CMYK}})); assert_eq!(icc_streams(&r.bytes).len(), 2); - output_intent(&r.bytes, None, |oi| { - assert_eq!(oi.get::>(b"DestOutputProfile").unwrap().decoded().unwrap().as_ref(), &*cms::icc_bytes(DEVICE_CMYK).unwrap()) - }); + assert!(icc_profiles(&r.bytes) == [(4, icc.to_vec())]); + assert!(colours(&r.bytes).iter().all(|c| c.0 == "scn"), "{:?}", colours(&r.bytes)); + assert!(intent_profile(&r.bytes) == *other); + // With `none`, every CMYK color is DeviceCMYK, in the output intent's profile. + for standard in ["pdfX3", "pdfX4"] { + let set = json!({"standard": standard, "output": {"profiles": "none", "outputIntent": DEVICE_CMYK}}); + let r = standard_pdf(&d, set.clone()); + assert!(icc_streams(&r.bytes) == [other.to_vec()], "{set}"); + let c = colours(&r.bytes); + assert!(c.len() == 1 && c[0].0 == "k" && close(&c[0].1, &ink), "{set}: {c:?}"); + } + // With `none`, colors converted to a CMYK destination of another profile keep its tag: they + // are in the destination's profile, not the output intent's. + let set = json!({"standard": "pdfX4", "output": {"profiles": "none", "conversion": "destination", "destination": DEVICE_CMYK, "outputIntent": working}}); + let r = standard_pdf(&d, set.clone()); + assert!(icc_profiles(&r.bytes) == [(4, other.to_vec())], "{set}"); + assert!(colours(&r.bytes).iter().all(|c| c.0 == "scn"), "{set}: {:?}", colours(&r.bytes)); + assert!(intent_profile(&r.bytes) == *icc, "{set}"); + // Without a standard, `all` tags CMYK colors, with an output intent of their profile or none. + for set in [json!({"output": {"profiles": "all"}}), json!({"output": {"profiles": "all", "outputIntent": working}})] { + let r = standard_pdf(&d, set.clone()); + assert!(icc_profiles(&r.bytes) == [(4, icc.to_vec())], "{set}"); + assert!(colours(&r.bytes).iter().all(|c| c.0 == "scn"), "{set}: {:?}", colours(&r.bytes)); + } +} + +/// Next to DeviceCMYK colors, RGB colors stay ICC-based (a CMYK output intent leaves no room for +/// DeviceRGB), and transparency groups of a CMYK document blend in DeviceCMYK. +#[test] +fn rgb_stays_tagged_and_groups_blend_in_device_cmyk_beside_device_cmyk_colors() { + let d = doc(ColorMode::Rgb, &[Color::rgb(0.2, 0.4, 0.6), Color::cmyk(0.1, 0.2, 0.3, 0.4)]); + for set in [json!({"standard": "pdfX4"}), json!({"standard": "pdfX4", "output": {"profiles": "none"}})] { + let r = standard_pdf(&d, set.clone()); + let ops: Vec = colours(&r.bytes).into_iter().map(|c| c.0).collect(); + assert_eq!(ops, ["scn", "k"], "{set}"); + let n: Vec = icc_profiles(&r.bytes).iter().map(|p| p.0).collect(); + assert_eq!(n, [3], "{set}: sRGB only"); + } + let mut d = doc(ColorMode::Cmyk, &[Color::cmyk(1.0, 0.0, 0.0, 0.0)]); + let mut n = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(20.0, 20.0, 60.0, 60.0)), + Appearance::basic(Paint::solid(Color::cmyk(0.0, 1.0, 0.0, 0.0)), Paint::None, 0.0), + ); + n.opacity = 0.5; + let l = d.layers[0].id; + d.insert(Some(l), 1, n).unwrap(); + let r = standard_pdf(&d, json!({"standard": "pdfX4"})); + let text = String::from_utf8_lossy(&r.bytes); + let groups: Vec<&str> = text.split("/Group<<").skip(1).map(|g| g.split(">>").next().unwrap()).collect(); + assert!(!groups.is_empty() && groups.iter().all(|g| g.contains("/CS/DeviceCMYK")), "{groups:?}"); } /// The profiles assigned to a document (Edit › Assign Profile) are its colour spaces whatever the /// working spaces of the session that exports it: a document opened again in a new session, -/// which starts with the default working spaces, keeps its profiles. Its CMYK colours are tagged -/// with its CMYK profile, which is also the PDF/X output intent, and its RGB colours separate -/// through it. +/// which starts with the default working spaces, keeps its profiles. Its CMYK profile is the PDF/X +/// output intent, whose DeviceCMYK colors are in it, and its RGB colours separate through it. #[test] fn colours_are_in_the_profiles_assigned_to_the_document() { let working = cms::active_settings().cmyk; @@ -635,13 +692,13 @@ fn colours_are_in_the_profiles_assigned_to_the_document() { let r = standard_pdf(&d, json!({"standard": "pdfX4"})); assert!(!r.warnings.iter().any(|w| w.contains("profile")), "{:?}", r.warnings); let own = cms::icc_bytes(DEVICE_CMYK).unwrap(); - assert!(icc_streams(&r.bytes) == [own.to_vec()], "tagged with the document's CMYK profile, not the working one"); + assert!(icc_streams(&r.bytes) == [own.to_vec()], "the document's CMYK profile, not the working one"); output_intent(&r.bytes, None, |oi| assert_eq!(oi.get::>(b"DestOutputProfile").unwrap().decoded().unwrap().as_ref(), &*own)); let c = colours(&r.bytes); - assert!(c[0].0 == "scn" && close(&c[0].1, &[0.1, 0.2, 0.3, 0.4]), "CMYK keeps its numbers: {c:?}"); + assert!(c[0].0 == "k" && close(&c[0].1, &[0.1, 0.2, 0.3, 0.4]), "CMYK keeps its numbers: {c:?}"); let separated = to_cmyk(DEVICE_CMYK).to_cmyk(&grey, intent); assert!(!close(&separated, &cms::active().to_cmyk(&grey, intent)), "the two profiles separate grey differently"); - assert!(c[1].0 == "scn" && close(&c[1].1, &separated), "RGB separated through the document's profile: {c:?} vs {separated:?}"); + assert!(c[1].0 == "k" && close(&c[1].1, &separated), "RGB separated through the document's profile: {c:?} vs {separated:?}"); // A profile that isn't available leaves the working space, with a warning. d.color_profiles.cmyk = Some("No Such Press".into()); let r = standard_pdf(&d, json!({"standard": "pdfX4"})); diff --git a/crates/pdf/src/tests/print.rs b/crates/pdf/src/tests/print.rs index 49a34ff428..588273faf9 100644 --- a/crates/pdf/src/tests/print.rs +++ b/crates/pdf/src/tests/print.rs @@ -829,6 +829,80 @@ fn overprint_black_keeps_the_cyan_under_near_and_freeform_blacks_on_postscript_p assert_eq!((fills(&p.plates[0]), fills(&p.plates[3])), (1, 4), "the cyan plate, the Black plate"); } +#[test] +fn overprint_black_keeps_the_cyan_under_a_near_black_linked_to_a_missing_swatch_on_postscript_plates() { + // 0.4% cyan beside 100% K, linked to a swatch the document lacks: it separates from its own + // values and the option marks it to overprint, so it counts as black like an unlinked color. + let near = Paint::Solid { color: Color::cmyk(0.004, 0.0, 0.0, 1.0), swatch: Some("Missing".into()), tint: 1.0 }; + let square = + Node::path(vectorcraft_doc::NodeId(0), shapes::rectangle(Rect::new(10.0, 15.0, 30.0, 35.0)), Appearance::basic(near, Paint::None, 0.0)); + let d = over_cyan(vec![square]); + assert!(d.swatch("Missing").is_none()); + let opts = PrintOptions { + settings: settings(json!({"output": {"mode": "separations", "overprintBlack": true}})), + postscript: true, + ..Default::default() + }; + let p = plan(&d, &opts).unwrap(); + let fills = |doc: &Document| { + let mut count = 0; + doc.walk(|n| count += usize::from(n.appearance.fill().is_some_and(|f| !f.paint.is_none()))); + count + }; + assert_eq!((fills(&p.plates[0]), fills(&p.plates[3])), (1, 2), "the cyan plate, the Black plate"); +} + +#[test] +fn overprinting_near_blacks_linked_to_a_missing_swatch_keep_the_cyan_on_postscript_plates() { + // 0.4% cyan beside 100% K, linked to a swatch the document lacks and set to overprint, on a + // fill, a stroke, a character fill and a linear gradient's stops: a PostScript cyan plate draws + // it as nothing, as it does an unlinked black, and a PDF cyan plate draws it. A faint cyan that + // is not black, linked to the same name, stays on both. + let missing = |color: Color| Paint::Solid { color, swatch: Some("Missing".into()), tint: 1.0 }; + let near = Color::cmyk(0.004, 0.0, 0.0, 1.0); + let faint = Color::cmyk(0.004, 0.5, 0.0, 0.0); + let square = |x: f64, fill: Paint, stroke: Paint| { + let mut n = + Node::path(vectorcraft_doc::NodeId(0), shapes::rectangle(Rect::new(x, 15.0, x + 20.0, 35.0)), Appearance::basic(fill, stroke, 2.0)); + if let Some(f) = n.appearance.fill_mut() { + f.overprint = true; + } + if let Some(s) = n.appearance.stroke_mut() { + s.overprint = true; + } + n + }; + let stop = |offset: f32| GradientStop { swatch: Some("Missing".into()), ..GradientStop::new(offset, near) }; + let linear = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![stop(0.0), stop(1.0)])); + let style = vectorcraft_doc::CharStyle { fill: missing(near), overprint_fill: true, ..Default::default() }; + let text = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(20.0, 60.0), "Hi", style); + let d = over_cyan(vec![ + square(10.0, missing(near), Paint::None), + square(40.0, Paint::None, missing(near)), + square(70.0, Paint::Gradient(Box::new(linear)), Paint::None), + square(100.0, missing(faint), Paint::None), + Node::new(vectorcraft_doc::NodeId(0), NodeKind::Text(Box::new(text))), + ]); + assert!(d.swatch("Missing").is_none()); + // The fills, strokes and character fills plate `plate` draws. + let drawn = |postscript: bool, plate: usize| { + let opts = PrintOptions { settings: settings(json!({"output": {"mode": "separations"}})), postscript, ..Default::default() }; + let p = plan(&d, &opts).unwrap(); + let (mut fills, mut strokes, mut chars) = (0, 0, 0); + p.plates[plate].walk(|n| { + fills += usize::from(n.appearance.fill().is_some_and(|f| !f.paint.is_none())); + strokes += usize::from(n.appearance.stroke().is_some_and(|s| !s.paint.is_none())); + if let NodeKind::Text(t) = &n.kind { + chars += t.runs.iter().filter(|r| !r.style.fill.is_none()).count(); + } + }); + (fills, strokes, chars) + }; + assert_eq!(drawn(true, 0), (2, 0, 0), "PostScript cyan plate: the cyan and the faint fill"); + assert_eq!(drawn(false, 0), (4, 1, 1), "PDF cyan plate: the cyan, the fill, the gradient, the faint fill, the stroke and the type"); + assert_eq!(drawn(true, 3), (3, 1, 1), "PostScript Black plate: every black, not the faint fill"); +} + #[test] fn an_overprinting_fill_keeps_its_faint_ink_on_pdf_plates() { // 0.4% cyan beside 100% K, set to overprint: a PDF plate draws it with Darken, a PostScript diff --git a/crates/plugins/src/lib.rs b/crates/plugins/src/lib.rs index b304e1721e..019dd0d858 100644 --- a/crates/plugins/src/lib.rs +++ b/crates/plugins/src/lib.rs @@ -53,7 +53,7 @@ pub mod wat; pub use dialog::ParamUi; pub use host::{LogLevel, LogLine, Report}; pub use manifest::{Budget, Command, InputKind, Kind, Manifest, Param, ParamSpec}; -pub use runtime::{ABI_VERSION, HEAVY_FUEL, HEAVY_WALL_TIME_MS, Limits, Plugin, heavy_terms}; +pub use runtime::{ABI_VERSION, HEAVY_FUEL, HEAVY_WALL_TIME_MS, LARGE_FUEL, Limits, Plugin, heavy_terms}; #[doc(hidden)] pub use runtime::{BYTES_COPIED_PER_FUEL, FUEL_SLICE}; diff --git a/crates/plugins/src/runtime.rs b/crates/plugins/src/runtime.rs index 5a2db2ff0d..0cb6197e97 100644 --- a/crates/plugins/src/runtime.rs +++ b/crates/plugins/src/runtime.rs @@ -35,6 +35,11 @@ pub const HEAVY_FUEL: u64 = 1_000_000_000; /// Wall-clock budget of a heavy filter's run, in milliseconds. pub const HEAVY_WALL_TIME_MS: u64 = 300_000; +/// Instructions a filter's run may use besides [`Limits::fuel_per_byte`] for each byte of input +/// when Preferences › Plug-ins & Scratch Disks › Plug-in Instruction Budget is Large +/// ([`Plugin::large_limits`]): 5 times the default. +pub const LARGE_FUEL: u64 = 250_000_000; + /// The limit a run reports when its input and parameters together are past half its memory. pub(crate) const SELECTION_TOO_LARGE: &str = "memory budget (the selection is too large to hand over)"; @@ -215,6 +220,12 @@ impl Plugin { pub fn limits(&self) -> &Limits { &self.limits } + /// Its limits with the Large instruction budget: at least [`LARGE_FUEL`] instructions besides + /// those for each byte of input, and every other limit, the time budget included, as it is. A + /// heavy filter keeps its larger budget. + pub fn large_limits(&self) -> Limits { + Limits { fuel_base: self.limits.fuel_base.max(LARGE_FUEL), ..self.limits.clone() } + } /// Module size in bytes. pub fn size(&self) -> usize { self.size diff --git a/crates/plugins/tests/abi.rs b/crates/plugins/tests/abi.rs index abc2cd05eb..26dec0a7d2 100644 --- a/crates/plugins/tests/abi.rs +++ b/crates/plugins/tests/abi.rs @@ -7,7 +7,7 @@ use std::time::{Duration, Instant}; use serde_json::{Value, json}; use vectorcraft_plugins::storage::{Meter, Storage, StorageError}; -use vectorcraft_plugins::{Error, HEAVY_FUEL, HEAVY_WALL_TIME_MS, Kind, Limits, Plugin, Report, heavy_terms, registry, wat as tpl}; +use vectorcraft_plugins::{Error, HEAVY_FUEL, HEAVY_WALL_TIME_MS, Kind, LARGE_FUEL, Limits, Plugin, Report, heavy_terms, registry, wat as tpl}; /// The example Desaturate plug-in, built from `crates/plugins/example`. const DESATURATE: &[u8] = include_bytes!("fixtures/desaturate.wasm"); @@ -259,6 +259,23 @@ fn a_heavy_filter_finishes_what_a_light_one_cannot() { assert_eq!(p.run(INPUT.as_bytes(), b"{}").unwrap(), INPUT.as_bytes()); } +/// The Large instruction budget gives a light filter 5 times the instructions besides those for +/// each byte of input, so it finishes 20 million steps of a loop that its own budget can't, in the +/// same time budget. A heavy filter keeps its larger budget, and every other limit stays. +#[test] +fn the_large_budget_finishes_what_a_light_one_cannot_and_keeps_a_heavy_one() { + let light = Plugin::load(&build(&tpl::spinning(MANIFEST, 20_000_000, INPUT)), Limits::default()).unwrap(); + assert_eq!(light.run(INPUT.as_bytes(), b"{}"), Err(Error::Limit("instruction budget".into()))); + let large = light.large_limits(); + assert_eq!(large, Limits { fuel_base: LARGE_FUEL, ..Limits::default() }); + assert_eq!(LARGE_FUEL, 5 * Limits::default().fuel_base); + assert_eq!(light.run_limited(INPUT.as_bytes(), b"{}", &large).unwrap(), INPUT.as_bytes()); + let heavy = r#"{"id":"test.heavy","name":"Heavy","version":"1","kind":"filter","budget":"heavy"}"#; + let heavy = Plugin::load(&build(&tpl::spinning(heavy, 1, INPUT)), Limits::default()).unwrap(); + assert_eq!(heavy.large_limits(), *heavy.limits()); + assert_eq!((heavy.large_limits().fuel_base, heavy.large_limits().wall_time_ms), (HEAVY_FUEL, HEAVY_WALL_TIME_MS)); +} + #[test] fn an_exporter_returns_its_file_with_an_export_s_budget() { use vectorcraft_plugins::export::{self, Target}; diff --git a/crates/render/src/encode/quantize.rs b/crates/render/src/encode/quantize.rs index 0c873fd598..dc459d4331 100644 --- a/crates/render/src/encode/quantize.rs +++ b/crates/render/src/encode/quantize.rs @@ -190,12 +190,13 @@ pub fn quantize_locked(rgba: &[u8], width: u32, height: u32, o: &PaletteOptions, /// [`quantize`] to the fixed `palette`: each pixel takes its nearest entry, with `o`'s dither, /// transparency and matte; `o.reduction` sets only the distance weights, and `o.colors` is not -/// used. Only the first 255 colors of `palette` are used, leaving room for the transparent entry. -/// Entries no pixel uses are left out. +/// used. Only the first 256 colors of `palette` are used, or the first 255 when a pixel becomes +/// transparent, leaving room for the transparent entry. Entries no pixel uses are left out. pub fn quantize_to(rgba: &[u8], width: u32, height: u32, o: &PaletteOptions, palette: &[[u8; 3]]) -> Indexed { let px = rgba.as_chunks::<4>().0; let colors = opaque_colors(px, o, false); - let mut palette: Vec<[u8; 3]> = palette.iter().take(255).copied().collect(); + let has_clear = o.transparency && px.iter().any(|p| p[3] < 128); + let mut palette: Vec<[u8; 3]> = palette.iter().take(256 - usize::from(has_clear)).copied().collect(); if palette.is_empty() { palette.push(o.matte.unwrap_or([255; 3])); } diff --git a/crates/render/src/encode/tests_palette.rs b/crates/render/src/encode/tests_palette.rs index 836b5fcf09..d9a8a2fc0f 100644 --- a/crates/render/src/encode/tests_palette.rs +++ b/crates/render/src/encode/tests_palette.rs @@ -102,11 +102,18 @@ fn a_given_palette_keeps_the_entries_pixels_use() { assert_eq!(ix.transparent, Some(0)); assert_eq!(ix.palette[1..], [[255, 0, 0], [0, 0, 255]], "unused entries left out, the order kept"); assert_eq!(ix.indices, [1, 2, 0, 1]); - // At most 255 of the given colors are used, leaving room for the transparent entry. + // With no transparent pixel all 256 of the given colors can be used; with one, the first 255 + // leave room for the transparent entry. let many: Vec<[u8; 3]> = (0..300u32).map(|i| [(i % 256) as u8, (i / 256) as u8, 0]).collect(); let all = image(256, 2, |x, y| [x as u8, y as u8, 0]); let ix = quantize_to(&all, 256, 2, &o, &many); - assert!(ix.palette.len() <= 255 && ix.palette.iter().all(|c| many[..255].contains(c)), "{}", ix.palette.len()); + assert!(ix.palette.len() == 256 && ix.palette.iter().all(|c| many[..256].contains(c)), "{}", ix.palette.len()); + assert!(ix.palette.contains(&many[255]), "the 256th color is used"); + let mut clear = all.clone(); + clear[3] = 0; + let ix = quantize_to(&clear, 256, 2, &o, &many); + assert_eq!(ix.transparent, Some(0)); + assert!(ix.palette.len() <= 256 && ix.palette[1..].iter().all(|c| many[..255].contains(c)), "{}", ix.palette.len()); } #[test] diff --git a/crates/svg/src/export/text.rs b/crates/svg/src/export/text.rs index 8a808b5f72..f8bc712117 100644 --- a/crates/svg/src/export/text.rs +++ b/crates/svg/src/export/text.rs @@ -103,20 +103,23 @@ impl Writer<'_> { || t.stacks_warichu() || (inline && matches!(t.kind, TextKind::OnPath { .. })) || unwritable; - let chars = |w: &mut Self, n: &Node| if outlined { w.text_outlines(n, t) } else { w.text(n, t) }; + // Every writer below draws this one layout of the type. + let db = vectorcraft_text::FontDb::global(); + let lay = vectorcraft_text::layout(db, t); + let chars = |w: &mut Self, n: &Node| if outlined { w.text_outlines(n, t, &lay) } else { w.text(n, t, &lay) }; let painted = n.appearance.items.iter().any(|i| i.visible() && !i.paint().is_none()); // Live type with an inside or outside character stroke writes that stroke apart from the // text, in the group. let apart = !outlined && t.runs.iter().any(|r| aligned(&r.style)); if !painted && !inline && !apart { + #[cfg(test)] + DRAW_HANDED.with(|d| d.set(true)); return chars(self, n); } let id = self.id_attr(n); let a = self.attrs(&css::transparency(n)); self.line(&format!("")); self.depth += 1; - let db = vectorcraft_text::FontDb::global(); - let lay = vectorcraft_text::layout(db, t); let mut all = lay.to_bezpath(); for (_, bar) in vectorcraft_text::decorations(&lay, db, t) { all.extend(bar.iter()); @@ -154,14 +157,22 @@ impl Writer<'_> { } /// Text as glyph outlines: one compound path per run, painted like the run (gradients span - /// the whole text), over its colour glyphs, as on the canvas. - fn text_outlines(&mut self, n: &Node, t: &TextObject) { + /// the whole text), over its colour glyphs, as on the canvas. `lay` is the layout of `t`. + fn text_outlines(&mut self, n: &Node, t: &TextObject, lay: &vectorcraft_text::TextLayout) { + let mut again = None; + let lay = handed(t, lay, &mut again); let db = vectorcraft_text::FontDb::global(); - let lay = vectorcraft_text::layout(db, t); let mut runs = vec![kurbo::BezPath::new(); t.runs.len()]; + // Each run's glyphs, in layout order. + let mut run_glyphs = vec![Vec::new(); t.runs.len()]; + for g in &lay.glyphs { + if let Some(gs) = run_glyphs.get_mut(g.run) { + gs.push(g); + } + } // Underline and strikethrough bars join their run's outlines; ruby glyphs are painted // with the run of the text they annotate. - let bars = vectorcraft_text::decorations(&lay, db, t); + let bars = vectorcraft_text::decorations(lay, db, t); for (run, outline) in lay .glyphs .iter() @@ -197,10 +208,10 @@ impl Writer<'_> { // The glyphs stay in text space; the text's transform joins the document's meanwhile. let saved = self.xf; self.xf = saved * t.xf; - for (i, (bp, run)) in runs.iter().zip(&t.runs).enumerate() { + for ((bp, run), glyphs) in runs.iter().zip(&t.runs).zip(&run_glyphs) { // Colour glyphs paint themselves, under their run's paint: bitmap glyphs (emoji) as // their images, COLR and SVG glyphs as their art. - for g in lay.glyphs.iter().filter(|g| g.run == i) { + for g in glyphs { if let Some((image, to_text)) = g.placed_image() { let m = self.matrix(self.xf * to_text); let href = self.blob_href(&image.blob); @@ -233,40 +244,42 @@ impl Writer<'_> { /// spacing come out as on the canvas. Centred and right-aligned lines are anchored /// (`text-anchor`) at their centre or right end, so they stay aligned in a viewer whose font /// differs; other lines are placed where each style run (and, justified, each word) starts. - fn text(&mut self, n: &Node, t: &TextObject) { + /// `lay` is the layout of `t`. + fn text(&mut self, n: &Node, t: &TextObject, lay: &vectorcraft_text::TextLayout) { // Live SVG text is written in logical order from left-aligned pieces: bidirectional text // (and right-to-left paragraphs) keep their look as outlines until it is written with // `direction`/`unicode-bidi`. So do runs set Right to Left (Character Direction), whose // `direction="rtl"` would anchor their pieces at the right end. - let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); + let mut again = None; + let lay = handed(t, lay, &mut again); let rtl_runs = t.runs.iter().any(|r| r.style.char_direction == Some(vectorcraft_doc::ParaDirection::RightToLeft)); if lay.glyphs.iter().any(|g| g.rtl) || lay.lines.iter().any(|l| l.rtl) || rtl_runs { self.warn("bidirectional text is outlined to preserve shaping and visual order"); - return self.text_outlines(n, t); + return self.text_outlines(n, t, lay); } if let TextKind::OnPath { path, start, end } = &t.kind { // A reader lays a ``'s glyphs straight: joined glyphs bent along the path // keep their look as outlines. if lay.glyphs.iter().any(|g| g.bend.is_some()) { self.warn("joined type bent along a path is outlined to keep its look"); - return self.text_outlines(n, t); + return self.text_outlines(n, t, lay); } // `` has a start offset only: an end bracket, Align to Path and Spacing // keep their look as outlines. if end.is_some() || t.path_align != vectorcraft_doc::PathAlign::Baseline || t.path_spacing != 0.0 { self.warn("type on a path with an end bracket, Align to Path or Spacing is outlined to keep its look"); - return self.text_outlines(n, t); + return self.text_outlines(n, t, lay); } // A reader turns each `` glyph with the path, as Rainbow does: Skew, 3D // Ribbon, Stair Step and Gravity keep their look as outlines. if t.path_effect != vectorcraft_doc::PathEffect::Rainbow { self.warn("type on a path with an effect other than Rainbow is outlined to keep its look"); - return self.text_outlines(n, t); + return self.text_outlines(n, t, lay); } // It cannot hang glyphs outside the start bracket either. - if hangs_on_path(t, &lay) { + if hangs_on_path(t, lay) { self.warn("type on a path with glyphs hanging outside its brackets is outlined to keep its look"); - return self.text_outlines(n, t); + return self.text_outlines(n, t, lay); } // The space before the first character is written as its `dx`; one before a character // after a line break, which the `` writes as a space, keeps its look as outlines. @@ -279,39 +292,39 @@ impl Writer<'_> { }); if spaced_break { self.warn("type on a path with space before a character after a line break is outlined to keep its look"); - return self.text_outlines(n, t); + return self.text_outlines(n, t, lay); } // A `` places its characters one after the other: Insert Aki keeps its look as // outlines. if t.runs.iter().any(|r| r.style.aki_left != 0.0 || r.style.aki_right != 0.0) { self.warn("type on a path with Insert Aki is outlined to keep its look"); - return self.text_outlines(n, t); + return self.text_outlines(n, t, lay); } // Tsume does as well. if t.runs.iter().any(|r| r.style.tsume != 0.0) { self.warn("type on a path with Tsume is outlined to keep its look"); - return self.text_outlines(n, t); + return self.text_outlines(n, t, lay); } // Justification…'s Desired word and letter spacing and glyph scaling do too. if (0..t.paragraph_count()).any(|i| !t.layout_justification(t.para_at(i)).desired_is_default()) { self.warn("type on a path with Justification spacing or glyph scaling is outlined to keep its look"); - return self.text_outlines(n, t); + return self.text_outlines(n, t, lay); } // A `` holds the characters of the text, not the bullets or numbers drawn // before them. if !lay.markers.is_empty() { self.warn("type on a path with bullets or numbers is outlined to keep its look"); - return self.text_outlines(n, t); + return self.text_outlines(n, t, lay); } // Nor the character a repeat mark is drawn as in the mark's width (Kurikaeshi Moji Shori). if !lay.repeat_marks.is_empty() { self.warn("type on a path that starts with a repeat mark drawn as the character it repeats is outlined to keep its look"); - return self.text_outlines(n, t); + return self.text_outlines(n, t, lay); } - return self.text_on_path(n, t, path, *start); + return self.text_on_path(n, t, lay, path, *start); } - self.note_fonts(t, &lay); - let lines = text_lines(t, &lay, self.opts.fewer_tspans); + self.note_fonts(t, lay); + let lines = text_lines(t, lay, self.opts.fewer_tspans); // `drawn` holds the styles the layout draws the text in: Shrink Text to Fit scales its sizes, explicit leading and baseline shifts. let fitted = (lay.fit_scale != 1.0).then(|| vectorcraft_text::scaled(t, lay.fit_scale)); let drawn = fitted.as_ref().unwrap_or(t); @@ -374,35 +387,36 @@ impl Writer<'_> { } s.push_str(""); self.line(&s); - self.aligned_char_strokes(t); + self.aligned_char_strokes(t, lay); } - /// The inside and outside character strokes of live type `t`, over its text (which goes - /// without them, see [`Self::char_props`]): each such run's stroke on its glyph outlines, drawn - /// twice as wide and clipped or masked to its side as aligned path strokes are + /// The inside and outside character strokes of live type `t`, laid out as `lay`, over its text + /// (which goes without them, see [`Self::char_props`]): each such run's stroke on its glyph + /// outlines, drawn twice as wide and clipped or masked to its side as aligned path strokes are /// ([`Self::side_attr`]). The text stays live; only the stroke follows the outlines. - fn aligned_char_strokes(&mut self, t: &TextObject) { + fn aligned_char_strokes(&mut self, t: &TextObject, lay: &vectorcraft_text::TextLayout) { if !t.runs.iter().any(|r| aligned(&r.style)) { return; } + let mut again = None; + let lay = handed(t, lay, &mut again); let db = vectorcraft_text::FontDb::global(); - let lay = vectorcraft_text::layout(db, t); - let bars = vectorcraft_text::decorations(&lay, db, t); + let bars = vectorcraft_text::decorations(lay, db, t); + // Each such run's glyph outlines and then its bars, in layout order. + let mut outlines = vec![BezPath::new(); t.runs.len()]; + for (run, outline) in lay.glyphs.iter().map(|g| (g.run, &g.outline)).chain(bars.iter().map(|(r, b)| (*r, b))) { + if let Some(bp) = outlines.get_mut(run).filter(|_| t.runs.get(run).is_some_and(|r| aligned(&r.style))) { + bp.extend(outline.iter()); + } + } // The glyphs stay in text space; the text's transform joins the document's meanwhile. let saved = self.xf; self.xf = saved * t.xf; - for (i, run) in t.runs.iter().enumerate().filter(|(_, r)| aligned(&r.style)) { - let mut bp = BezPath::new(); - for g in lay.glyphs.iter().filter(|g| g.run == i) { - bp.extend(g.outline.iter()); - } - for (_, bar) in bars.iter().filter(|(r, _)| *r == i) { - bp.extend(bar.iter()); - } + for (run, bp) in t.runs.iter().zip(&outlines).filter(|(r, _)| aligned(&r.style)) { if bp.elements().is_empty() { continue; } - let pd = PathData::from_bezpath(&bp); + let pd = PathData::from_bezpath(bp); let ap = vectorcraft_doc::Appearance { items: vec![AppearanceItem::Stroke(run.style.stroke_layer())], ..Default::default() }; let d = self.path_d(&pd, self.xf); self.shape(&Node::path(NodeId(u64::MAX), pd.clone(), ap), &d, None, &[&pd], FillRule::NonZero, Some(lay.bounds)); @@ -574,15 +588,16 @@ impl Writer<'_> { rules } - /// Type on a path: a `` along the path (a def). - fn text_on_path(&mut self, n: &Node, t: &TextObject, path: &PathData, start: f64) { + /// Type on a path, laid out as `lay`: a `` along the path (a def). + fn text_on_path(&mut self, n: &Node, t: &TextObject, lay: &vectorcraft_text::TextLayout, path: &PathData, start: f64) { let id = self.id_attr(n); let pid = self.fresh_id("text-path"); let d = self.path_d(path, self.xf * t.xf); self.def(1, &format!("")); // The element's user space is the document's; gradients span the laid-out text. - let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); - self.note_fonts(t, &lay); + let mut again = None; + let lay = handed(t, lay, &mut again); + self.note_fonts(t, lay); // The styles the layout draws the text in: Dynamic Text scales its sizes, leading and baseline shifts. let fitted = (lay.fit_scale != 1.0).then(|| vectorcraft_text::scaled(t, lay.fit_scale)); let drawn = fitted.as_ref().unwrap_or(t); @@ -626,7 +641,7 @@ impl Writer<'_> { } s.push_str(""); self.line(&s); - self.aligned_char_strokes(t); + self.aligned_char_strokes(t, lay); } } @@ -635,6 +650,34 @@ fn aligned(st: &CharStyle) -> bool { st.has_stroke() && st.stroke_align != StrokeAlign::Center } +#[cfg(test)] +thread_local! { + /// Tests: each type writer lays `t` out again ([`handed`]) instead of drawing the layout it is + /// handed, so a test can compare the two. The first writer of type written without a group + /// still draws the layout it is handed ([`DRAW_HANDED`]), so each object is laid out where it + /// is drawn. + static LAY_OUT_AGAIN: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// Tests: the next type writer draws the layout it is handed, with [`LAY_OUT_AGAIN`] too. + static DRAW_HANDED: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// The layout a type writer draws: `lay`, the layout of `t` it is handed. In tests that ask for it, +/// `t` laid out again, kept in `again`. +fn handed<'a>( + t: &TextObject, + lay: &'a vectorcraft_text::TextLayout, + again: &'a mut Option, +) -> &'a vectorcraft_text::TextLayout { + #[cfg(test)] + let lay = { + let draw_handed = DRAW_HANDED.with(|d| d.replace(false)); + if LAY_OUT_AGAIN.with(std::cell::Cell::get) && !draw_handed { &*again.insert(vectorcraft_text::layout(FontDb::global(), t)) } else { lay } + }; + #[cfg(not(test))] + let _ = (t, again); + lay +} + /// Does type on a path `t`, laid out as `lay`, hang glyphs outside its brackets? It does when /// Optical Margin Alignment or its first paragraph's Roman Hanging Punctuation is on and its /// glyphs sit elsewhere with both off. diff --git a/crates/svg/src/export/text/tests.rs b/crates/svg/src/export/text/tests.rs index 951817c2c5..6b2fcbfb1f 100644 --- a/crates/svg/src/export/text/tests.rs +++ b/crates/svg/src/export/text/tests.rs @@ -1,5 +1,7 @@ //! The advances a reader gives live type ([`reader_advances`]): the same as when the type is laid //! out again each time, which happens only when a reader sets the type differently from its layout. +//! The type writers draw one layout of the type ([`handed`]) and write what laying it out in each +//! writer writes. use super::*; use vectorcraft_doc::text::{Bullet, ParaList}; @@ -145,3 +147,202 @@ fn a_mixed_document_lays_out_again_only_the_japanese_type() { let (svg, again) = export_layouts_again(vec![point("Latin"), point("「かな」。"), point(""), point("Ab2")]); assert_eq!(again, 1, "{svg}"); } + +/// Type `t`, with the object's own fills and strokes `items`, alone in a document. +fn doc_of(t: TextObject, items: Vec) -> Document { + let mut d = Document::new(300.0, 200.0); + let mut n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t))); + n.appearance.items = items; + let l = d.layers[0].id; + d.insert(Some(l), 0, n).unwrap(); + d +} + +/// Type on a straight path across the page. +fn on_path(text: &str, st: CharStyle) -> TextObject { + let mut t = TextObject::point(Point::ZERO, text, st); + let mut line = BezPath::new(); + line.move_to((20.0, 100.0)); + line.line_to((280.0, 100.0)); + t.kind = TextKind::OnPath { path: PathData::from_bezpath(&line), start: 0.0, end: None }; + t +} + +/// A character style with a stroke on side `align`. +fn stroked(align: StrokeAlign) -> CharStyle { + CharStyle { stroke: Paint::solid(vectorcraft_color::Color::rgb8(200, 0, 0)), stroke_width: 2.0, stroke_align: align, ..style() } +} + +fn red_fill() -> Vec { + vec![AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::solid(vectorcraft_color::Color::rgb8(255, 0, 0))))] +} + +/// The type the writers handle differently, each with how many times its export lays the type +/// out: once, plus the layout of the copy that checks for hanging glyphs on a path; and how many +/// times with each writer laying the type out on its own ([`LAY_OUT_AGAIN`]). +fn writer_cases() -> Vec<(&'static str, Document, crate::ExportOptions, u64, u64)> { + let opts = crate::ExportOptions::default; + let outlined = || crate::ExportOptions { outline_text: true, ..crate::ExportOptions::default() }; + let mut runs = point("Red "); + runs.runs.push(TextRun::new("green ", CharStyle { underline: true, ..stroked(StrokeAlign::Outside) })); + runs.runs.push(TextRun::new("blue", CharStyle { strikethrough: true, ..style() })); + let mut many = point(""); + many.runs = (0..200).map(|i| TextRun::new(if i % 7 == 6 { " " } else { "x" }, CharStyle { size: 8.0 + f64::from(i % 5), ..style() })).collect(); + let mut rtl_run = point("abc"); + rtl_run.runs[0].style.char_direction = Some(vectorcraft_doc::ParaDirection::RightToLeft); + let mut skewed = on_path("Skewed", style()); + skewed.path_effect = vectorcraft_doc::PathEffect::Skew; + let mut hanging = on_path("\u{201C}Quoted.\u{201D}", style()); + hanging.optical_margin = true; + let mut inside = point("Inside out"); + inside.runs.push(TextRun::new(" plain", style())); + inside.runs[0].style = CharStyle { underline: true, ..stroked(StrokeAlign::Inside) }; + let outside = TextObject::point(Point::new(20.0, 20.0), "Outside", stroked(StrokeAlign::Outside)); + vec![ + ("point type", doc_of(point("Plain type"), vec![]), opts(), 1, 1), + ("point type with a fill", doc_of(point("Filled type"), red_fill()), opts(), 1, 2), + ("type on a path", doc_of(on_path("Type on a path", style()), vec![]), opts(), 1, 2), + ("type on a path with a fill", doc_of(on_path("Filled path type", style()), red_fill()), opts(), 1, 3), + ("bidirectional type", doc_of(point("abc \u{5D0}\u{5D1}\u{5D2} def"), vec![]), opts(), 1, 2), + ("a run set right to left", doc_of(rtl_run, vec![]), opts(), 1, 2), + ("bidirectional type on a path", doc_of(on_path("abc \u{5D0}\u{5D1}\u{5D2}", style()), vec![]), opts(), 1, 2), + ("type on a path with Skew", doc_of(skewed, vec![]), opts(), 1, 2), + ("type on a path that may hang", doc_of(hanging, vec![]), opts(), 2, 3), + ("outside character stroke", doc_of(outside, vec![]), opts(), 1, 3), + ("inside character stroke", doc_of(inside, vec![]), opts(), 1, 3), + ("runs with a stroke and decorations", doc_of(runs.clone(), vec![]), opts(), 1, 3), + ("runs as outlines", doc_of(runs.clone(), vec![]), outlined(), 1, 1), + ("outside stroke on a path with a fill", doc_of(on_path("Stroked", stroked(StrokeAlign::Outside)), red_fill()), opts(), 1, 4), + ("inside stroke on a path", doc_of(on_path("Stroked", stroked(StrokeAlign::Inside)), vec![]), opts(), 1, 4), + ("many runs as outlines", doc_of(many.clone(), vec![]), outlined(), 1, 1), + ("many runs", doc_of(many, vec![]), opts(), 1, 1), + ] +} + +/// SVG export of `d` with each type writer laying the type out again (`again`) or drawing the +/// layout it is handed, and how many times the export laid type out. +fn export_counting(d: &Document, opts: &crate::ExportOptions, again: bool) -> (crate::Output, u64) { + LAY_OUT_AGAIN.with(|a| a.set(again)); + let before = vectorcraft_text::test_fonts::layouts_on_this_thread(); + let out = crate::export_full(d, opts, None); + let laid = vectorcraft_text::test_fonts::layouts_on_this_thread() - before; + LAY_OUT_AGAIN.with(|a| a.set(false)); + (out, laid) +} + +#[test] +fn every_type_writer_draws_one_layout() { + for (name, d, opts, layouts, own_layouts) in writer_cases() { + let (out, laid) = export_counting(&d, &opts, false); + assert_eq!(laid, layouts, "{name}: {}", out.svg); + // The same file and warnings as each writer laying the type out on its own. + let (again, laid_again) = export_counting(&d, &opts, true); + assert_eq!(laid_again, own_layouts, "{name}"); + assert_eq!(out.svg, again.svg, "{name}"); + assert_eq!(out.warnings, again.warnings, "{name}"); + assert_eq!(out.setting_notes, again.setting_notes, "{name}"); + } +} + +/// The CPU time this thread has run, from Linux's scheduler statistics; wall time elsewhere. +fn thread_time(start: std::time::Instant) -> std::time::Duration { + std::fs::read_to_string("/proc/thread-self/schedstat") + .ok() + .and_then(|s| s.split_whitespace().next()?.parse().ok()) + .map_or_else(|| start.elapsed(), std::time::Duration::from_nanos) +} + +fn median(mut v: Vec) -> std::time::Duration { + v.sort(); + v[v.len() / 2] +} + +/// Timing, not a check: SVG export of a large document with each writer laying the type out again +/// and with one layout handed to them, alternating, seven runs each; and grouping the glyphs of +/// type with 1,000 runs by run, one filter per run against one pass. Run with +/// `cargo test --release -p vectorcraft-svg --lib svg_type_layout_timing -- --ignored --nocapture`. +#[test] +#[ignore = "timing"] +fn svg_type_layout_timing() { + let mut d = Document::new(2000.0, 2000.0); + let l = d.layers[0].id; + let add = |d: &mut Document, t: TextObject, items: Vec| { + let mut n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t))); + n.appearance.items = items; + d.insert(Some(l), usize::MAX, n).unwrap(); + }; + let words: String = "Type set along a path for timing. ".chars().cycle().take(60).collect(); + for _ in 0..1000 { + add(&mut d, on_path(&words, style()), vec![]); + } + let hebrew = "abc \u{5D0}\u{5D1}\u{5D2}\u{5D3} def ".repeat(6); + for _ in 0..1000 { + add(&mut d, point(&hebrew.chars().take(80).collect::()), vec![]); + } + for _ in 0..300 { + add(&mut d, TextObject::point(Point::new(20.0, 20.0), "Stroked outside", stroked(StrokeAlign::Outside)), vec![]); + } + let mut runs = point(""); + runs.runs = (0..1000).map(|i| TextRun::new(if i % 9 == 8 { " " } else { "x" }, CharStyle { size: 8.0 + f64::from(i % 3), ..style() })).collect(); + let mut outlined = Document::new(2000.0, 2000.0); + let ol = outlined.layers[0].id; + for _ in 0..300 { + let n = Node::new(outlined.alloc_id(), NodeKind::Text(Box::new(runs.clone()))); + outlined.insert(Some(ol), usize::MAX, n).unwrap(); + } + let docs = [ + ("1,000 on a path, 1,000 bidirectional, 300 outside strokes", &d, crate::ExportOptions::default()), + ("300 texts of 1,000 runs as outlines", &outlined, crate::ExportOptions { outline_text: true, ..crate::ExportOptions::default() }), + ]; + for (name, doc, opts) in docs { + let (one, again) = (export_counting(doc, &opts, false), export_counting(doc, &opts, true)); + assert_eq!(one.0.svg, again.0.svg, "{name}"); + let (mut base, mut handed) = (vec![], vec![]); + for _ in 0..7 { + for (again, times) in [(true, &mut base), (false, &mut handed)] { + let start = std::time::Instant::now(); + let t0 = thread_time(start); + let _ = export_counting(doc, &opts, again); + times.push(thread_time(start) - t0); + } + } + let (from, to, base_median, handed_median) = (again.1, one.1, median(base.clone()), median(handed.clone())); + println!( + "{name}: layouts {from} -> {to}; laid out again {base:?} (median {base_median:?}); one layout {handed:?} (median {handed_median:?})" + ); + } + // The glyphs of one 1,000-run text, grouped by run 300 times. + let lay = vectorcraft_text::layout(FontDb::global(), &runs); + let (mut filtered, mut bucketed) = (vec![], vec![]); + for _ in 0..7 { + let start = std::time::Instant::now(); + let t0 = thread_time(start); + for _ in 0..300 { + for i in 0..runs.runs.len() { + for g in lay.glyphs.iter().filter(|g| g.run == i) { + std::hint::black_box(g); + } + } + } + filtered.push(thread_time(start) - t0); + let start = std::time::Instant::now(); + let t0 = thread_time(start); + for _ in 0..300 { + let mut run_glyphs = vec![Vec::new(); runs.runs.len()]; + for g in &lay.glyphs { + if let Some(gs) = run_glyphs.get_mut(g.run) { + gs.push(g); + } + } + for g in run_glyphs.iter().flatten() { + std::hint::black_box(g); + } + } + bucketed.push(thread_time(start) - t0); + } + println!( + "grouping 300 texts of 1,000 runs: filter per run {filtered:?} (median {:?}); one pass {bucketed:?} (median {:?})", + median(filtered.clone()), + median(bucketed.clone()) + ); +} diff --git a/crates/svg/src/import.rs b/crates/svg/src/import.rs index aaeac31a11..5e7afdd55a 100644 --- a/crates/svg/src/import.rs +++ b/crates/svg/src/import.rs @@ -208,6 +208,7 @@ pub(crate) fn import_finding( blends: fx::blends(&xml, &scan.markers), filter_sources: fx::sources(&xml, &scan.markers, |h| files.data_href(h)), files, + image_keys: HashMap::new(), non_scaling: found.non_scaling, data: found.data, events: found.events, @@ -371,6 +372,9 @@ struct Importer { filter_sources: HashMap, /// The files `` elements link to. files: files::Files, + /// The image key of each raster image usvg got, by the address of its bytes, with the bytes + /// held so that the address isn't given to other bytes during the import. + image_keys: HashMap>, String)>, /// Ids of the shapes whose strokes don't scale ([`vector_effect`]). non_scaling: HashSet, /// The `data-*` attributes of elements, by id ([`user_data`]). diff --git a/crates/svg/src/import/importer.rs b/crates/svg/src/import/importer.rs index c1dd856559..7cf350e5e1 100644 --- a/crates/svg/src/import/importer.rs +++ b/crates/svg/src/import/importer.rs @@ -780,6 +780,7 @@ impl Importer { usvg::ImageKind::WEBP(d) => (d, "image/webp"), usvg::ImageKind::SVG(tree) => return self.svg_image(tree, acc), }; + let source = bytes; let size = i.size(); let (pw, ph) = vectorcraft_doc::header_size(bytes).unwrap_or((size.width().round().max(1.0) as u32, size.height().round().max(1.0) as u32)); // A turned CMYK image is stored as the CMYK TIFF of its inks, the size of the PNG usvg got. @@ -792,10 +793,7 @@ impl Importer { let linked = self.files.linked(i.kind()); let missing = linked.is_some_and(|l| l.missing); let link = linked.map(|l| l.link.clone()); - let key = match &link { - Some(l) => linked_key(bytes, &l.path), - None => format!("img-{:016x}", fnv1a(bytes)), - }; + let key = self.image_key(source, bytes, link.as_ref().map(|l| l.path.as_str())); self.doc.images.entry(key.clone()).or_insert_with(|| { let blob = ImageBlob { mime: mime.into(), bytes: bytes.clone(), proxy: missing.then(|| bytes.clone()) }; if link.is_some() && !missing { blob.with_proxy() } else { blob } @@ -813,6 +811,29 @@ impl Importer { Some(node) } + /// The image key of the raster image usvg got as `source`, stored as `bytes` (the CMYK TIFF + /// that replaces a turned CMYK image, else `source`), linked to `path` when it is linked. The + /// bytes are hashed for the first image that shows `source`; the images after it that show + /// the same bytes get the key kept for it. + fn image_key(&mut self, source: &Arc>, bytes: &[u8], path: Option<&str>) -> String { + let at = Arc::as_ptr(source) as usize; + #[cfg(test)] + let kept = !tests::UNKEPT.get(); + #[cfg(not(test))] + let kept = true; + if kept && let Some((_, key)) = self.image_keys.get(&at) { + return key.clone(); + } + #[cfg(test)] + tests::IMAGE_HASHES.set(tests::IMAGE_HASHES.get() + 1); + let key = match path { + Some(path) => linked_key(bytes, path), + None => format!("img-{:016x}", fnv1a(bytes)), + }; + self.image_keys.insert(at, (source.clone(), key.clone())); + key + } + /// An SVG shown as an image (a data URL or a linked file) → its art, `acc` mapping its size. /// Its ids are its own: they mean nothing in the SVG around it. fn svg_image(&mut self, tree: &usvg::Tree, acc: Affine) -> Option { @@ -870,6 +891,7 @@ mod tests { blends: HashMap::new(), filter_sources: HashMap::new(), files: Files::default(), + image_keys: HashMap::new(), non_scaling: HashSet::new(), data: HashMap::new(), events: HashMap::new(), @@ -891,4 +913,242 @@ mod tests { assert!(matches!(im.error, Some(SvgError::TooManyImages(crate::MAX_NESTED_SVG_IMAGES)))); assert_eq!(im.error.unwrap().to_string(), "the SVG expands to more than 256 nested SVG images"); } + + thread_local! { + /// How many times this thread's imports hashed an image's bytes for its key. + pub(super) static IMAGE_HASHES: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// When set, this thread's imports hash the bytes of every image for its key, without + /// the keys kept for earlier images. + pub(super) static UNKEPT: std::cell::Cell = const { std::cell::Cell::new(false) }; + } + + /// `svg` imported on this thread with `opts`, with image keys kept or not, and how many times + /// image bytes were hashed for keys. + fn import_counting(svg: &str, opts: &crate::ImportOptions, kept: bool) -> (Document, Vec, usize) { + UNKEPT.set(!kept); + IMAGE_HASHES.set(0); + let imported = crate::import::import(svg, opts, crate::MAX_NODES); + UNKEPT.set(false); + let (doc, warnings) = imported.unwrap(); + (doc, warnings, IMAGE_HASHES.get()) + } + + /// The image objects of `doc` in paint order. + fn image_objects(doc: &Document) -> Vec { + let mut out = vec![]; + doc.walk(|n| { + if let NodeKind::Image(im) = &n.kind { + out.push((**im).clone()); + } + }); + out + } + + fn svg_of(body: &str) -> String { + format!(r#"{body}"#) + } + + /// A `w` × `h` PNG of pixels made from `seed`. + fn png(w: u32, h: u32, seed: u32) -> Vec { + let mut state = seed.wrapping_mul(2_654_435_761).wrapping_add(1); + let img = image::RgbaImage::from_fn(w, h, |_, _| { + state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + let [r, g, b, _] = state.to_le_bytes(); + image::Rgba([r, g, b, 255]) + }); + let mut out = vec![]; + img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + out + } + + fn data_url(mime: &str, bytes: &[u8]) -> String { + format!("data:{mime};base64,{}", crate::base64_encode(bytes)) + } + + /// A little-endian, uncompressed 1 × 1 CMYK TIFF of the inks `cmyk`. + fn cmyk_tiff(cmyk: [u8; 4]) -> Vec { + let entry = |tag: u16, kind: u16, count: u32, value: u32| { + [&tag.to_le_bytes()[..], &kind.to_le_bytes(), &count.to_le_bytes(), &value.to_le_bytes()].concat() + }; + let entries = 11u16; + let bits_at = 8 + 2 + u32::from(entries) * 12 + 4; + let data_at = bits_at + 8; + let mut out = [b"II".as_slice(), &[0x2a, 0], &8u32.to_le_bytes(), &entries.to_le_bytes()].concat(); + for e in [ + entry(256, 4, 1, 1), + entry(257, 4, 1, 1), + entry(258, 3, 4, bits_at), + entry(259, 3, 1, 1), + entry(262, 3, 1, 5), + entry(273, 4, 1, data_at), + entry(274, 3, 1, 1), + entry(277, 3, 1, 4), + entry(278, 4, 1, 1), + entry(279, 4, 1, 4), + entry(284, 3, 1, 1), + ] { + out.extend(e); + } + out.extend(0u32.to_le_bytes()); + for _ in 0..4 { + out.extend(8u16.to_le_bytes()); + } + assert_eq!(out.len(), data_at as usize); + out.extend(cmyk); + out + } + + /// `svg` imported with `opts` hashes image bytes `hashes` times for keys, and once for each + /// image without kept keys; both imports give the same document and warnings. + fn same_as_hashing_every_image(svg: &str, opts: &crate::ImportOptions, hashes: usize) -> (Document, Vec) { + let (doc, warnings, n) = import_counting(svg, opts, true); + let (every, every_warnings, every_n) = import_counting(svg, opts, false); + assert_eq!(every_n, image_objects(&every).len(), "without kept keys, each image is hashed"); + assert_eq!(n, hashes, "image bytes hashed for keys"); + assert_eq!(warnings, every_warnings); + assert_eq!(image_objects(&doc), image_objects(&every), "the same image objects"); + assert_eq!(doc.images, every.images, "the same stored images"); + assert!(doc == every, "the same document"); + (doc, warnings) + } + + /// Every `` of one image, and every `` with the same data URL, shows bytes usvg + /// got once: they are hashed once, and every image has the key of the image's bytes. + #[test] + fn an_image_shown_many_times_is_hashed_once() { + let png = png(3, 2, 1); + let href = data_url("image/png", &png); + let uses: String = (0..6).map(|i| format!(r##""##, i * 10)).collect(); + let inline: String = (0..6).map(|i| format!(r#""#, i * 10)).collect(); + for body in [format!(r#"{uses}"#), inline] { + let (doc, warnings) = same_as_hashing_every_image(&svg_of(&body), &crate::ImportOptions::default(), 1); + assert!(warnings.is_empty(), "{warnings:?}"); + let objects = image_objects(&doc); + assert_eq!(objects.len(), 6); + let key = format!("img-{:016x}", fnv1a(&png)); + assert!(objects.iter().all(|o| o.key == key && o.link.is_none() && (o.width, o.height) == (3, 2)), "{objects:?}"); + assert_eq!(doc.images.keys().collect::>(), [&key]); + assert_eq!((doc.images[&key].mime.as_str(), &**doc.images[&key].bytes, doc.images[&key].proxy.is_none()), ("image/png", &png[..], true)); + } + } + + /// One image is hashed once; two images of different bytes twice, with keys of their own; two + /// data URLs written differently that hold the same bytes are hashed once each, and share the + /// key and the stored image of those bytes. + #[test] + fn each_buffer_of_image_bytes_is_hashed_once() { + let (a, b) = (png(2, 2, 1), png(2, 2, 2)); + let image = |href: &str| format!(r#""#); + let opts = crate::ImportOptions::default(); + let (doc, _) = same_as_hashing_every_image(&svg_of(&image(&data_url("image/png", &a))), &opts, 1); + assert_eq!(image_objects(&doc)[0].key, format!("img-{:016x}", fnv1a(&a))); + let two = [image(&data_url("image/png", &a)), image(&data_url("image/png", &b)), image(&data_url("image/png", &a))].concat(); + let (doc, _) = same_as_hashing_every_image(&svg_of(&two), &opts, 2); + let keys: Vec = image_objects(&doc).into_iter().map(|o| o.key).collect(); + assert_eq!(keys, [format!("img-{:016x}", fnv1a(&a)), format!("img-{:016x}", fnv1a(&b)), format!("img-{:016x}", fnv1a(&a))]); + assert_eq!(doc.images.len(), 2); + let spelled = [image(&data_url("image/png", &a)), image(&data_url("image/png;x=y", &a))].concat(); + let (doc, _) = same_as_hashing_every_image(&svg_of(&spelled), &opts, 2); + let keys: Vec = image_objects(&doc).into_iter().map(|o| o.key).collect(); + assert_eq!(keys, [format!("img-{:016x}", fnv1a(&a)), format!("img-{:016x}", fnv1a(&a))]); + assert_eq!(doc.images.len(), 1); + } + + /// Every image of one linked file, or of one missing file, is hashed once: the file is read + /// once, and every image has the key of its bytes and its path, with its link. + #[test] + fn a_linked_or_missing_file_shown_many_times_is_hashed_once() { + let png = png(4, 2, 3); + let reads = std::sync::atomic::AtomicUsize::new(0); + let read = |path: &str| { + reads.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + path.ends_with("a.png").then(|| (png.clone(), vectorcraft_doc::LinkInfo::new(path))) + }; + let opts = crate::ImportOptions { folder: Some("/f"), read: Some(&read) }; + for (name, missing) in [("a.png", false), ("gone.png", true)] { + let body: String = (0..5).map(|i| format!(r#""#, i * 10)).collect(); + reads.store(0, std::sync::atomic::Ordering::Relaxed); + let (doc, warnings) = same_as_hashing_every_image(&svg_of(&body), &opts, 1); + assert_eq!(reads.load(std::sync::atomic::Ordering::Relaxed), 2, "{name}: one read for each of the two imports"); + assert_eq!(warnings.iter().any(|w| w.contains(name)), missing, "{name}: {warnings:?}"); + let objects = image_objects(&doc); + assert_eq!(objects.len(), 5); + let path = objects[0].link.as_ref().expect("linked").path.clone(); + assert!(path.ends_with(name), "{path}"); + let stored = doc.images[&objects[0].key].clone(); + assert_eq!(objects[0].key, linked_key(&stored.bytes, &path), "{name}"); + assert!(objects.iter().all(|o| o.key == objects[0].key && o.link.as_ref().is_some_and(|l| l.path == path)), "{name}"); + assert_eq!(doc.images.len(), 1); + assert_eq!(*stored.bytes == png, !missing, "{name}: the file's bytes, or a placeholder"); + assert_eq!(stored.is_proxy(), missing, "{name}"); + } + } + + /// A CMYK TIFF shown many times is stored as a CMYK TIFF and hashed once, its key that of the + /// stored TIFF. + #[test] + fn a_cmyk_image_shown_many_times_is_hashed_once() { + let tif = cmyk_tiff([255, 0, 0, 0]); + let href = data_url("image/tiff", &tif); + let uses: String = (0..4).map(|i| format!(r##""##, i * 10)).collect(); + let body = format!(r#"{uses}"#); + let (doc, _) = same_as_hashing_every_image(&svg_of(&body), &crate::ImportOptions::default(), 1); + let objects = image_objects(&doc); + assert_eq!(objects.len(), 4); + let blob = &doc.images[&objects[0].key]; + assert_eq!(blob.mime, "image/tiff"); + assert!(blob.cmyk().is_some(), "stored with its inks"); + assert_eq!(objects[0].key, format!("img-{:016x}", fnv1a(&blob.bytes))); + assert!(objects.iter().all(|o| o.key == objects[0].key)); + } + + /// This thread's CPU time in seconds where the system reports it, else the time since a first + /// call. + fn cpu_seconds() -> f64 { + static START: std::sync::OnceLock = std::sync::OnceLock::new(); + let schedstat = std::fs::read_to_string("/proc/thread-self/schedstat").ok(); + match schedstat.as_deref().and_then(|s| s.split_whitespace().next()?.parse::().ok()) { + Some(ns) => ns / 1e9, + None => START.get_or_init(std::time::Instant::now).elapsed().as_secs_f64(), + } + } + + /// The import's time for one PNG data URL shown by many `` elements, hashing every image + /// and keeping keys alternating in one process: `cargo test --release -p vectorcraft-svg --lib + /// importer::tests::image_key_timing -- --ignored --nocapture`. + #[test] + #[ignore = "timing, run by hand"] + fn image_key_timing() { + for (side, uses) in [(512, 100), (1024, 500)] { + let png = png(side, side, 7); + let refs: String = (0..uses).map(|i| format!(r##""##, i % 20, i / 20)).collect(); + let svg = svg_of(&format!(r#"{refs}"#, data_url("image/png", &png))); + let run = |kept: bool| { + let t = cpu_seconds(); + let (doc, _, _) = import_counting(&svg, &crate::ImportOptions::default(), kept); + let spent = cpu_seconds() - t; + assert_eq!(image_objects(&doc).len(), uses); + spent + }; + run(false); + run(true); + let (mut every, mut kept) = (vec![], vec![]); + for round in 0..7 { + if round % 2 == 0 { + every.push(run(false)); + kept.push(run(true)); + } else { + kept.push(run(true)); + every.push(run(false)); + } + } + let median = |v: &mut Vec| { + v.sort_by(f64::total_cmp); + v[v.len() / 2] + }; + let ms = |v: &[f64]| v.iter().map(|s| format!("{:.1}", s * 1e3)).collect::>().join(" "); + println!("{uses} uses of a {} byte PNG: every image {} ms, kept {} ms", png.len(), ms(&every), ms(&kept)); + println!("{uses} uses: median every image {:.1} ms, kept {:.1} ms", median(&mut every) * 1e3, median(&mut kept) * 1e3); + } + } } diff --git a/crates/svg/tests/it/effects_export.rs b/crates/svg/tests/it/effects_export.rs index c1a19e8d53..9a0f2aaeba 100644 --- a/crates/svg/tests/it/effects_export.rs +++ b/crates/svg/tests/it/effects_export.rs @@ -145,3 +145,52 @@ fn geometry_effects_on_type_export_as_its_reshaped_outlines() { assert!(!svg.contains(") { + use vectorcraft_doc::AppearanceItem; + let solid = |p: &Paint, r: f32, g: f32, b: f32| matches!(p, Paint::Solid { color, .. } if *color == Color::rgb(r, g, b)); + for i in &n.appearance.items { + let mark = match i { + AppearanceItem::Fill(f) if solid(&f.paint, 0.0, 0.0, 1.0) => 'b', + AppearanceItem::Fill(f) if solid(&f.paint, 1.0, 0.0, 0.0) => 'r', + AppearanceItem::Stroke(s) if s.width > 0.0 && solid(&s.paint, 0.0, 1.0, 0.0) => 'g', + _ => continue, + }; + if out.last() != Some(&(mark, clipped)) { + out.push((mark, clipped)); + } + } + let clips = matches!(n.kind, NodeKind::Group { clip: true, .. }); + for c in n.children().into_iter().flatten().skip(usize::from(clips)) { + painted_order(c, clipped || clips, out); + } +} + +#[test] +fn painted_clipping_type_exports_with_group_effect() { + // Type filled blue and stroked green clips a red square in a group with an Offset Path effect: + // the SVG paints the type's fill inside the clip behind the square, and its stroke over the + // clipped art, outside the clip. + let blue = Paint::solid(Color::rgb(0.0, 0.0, 1.0)); + let green = Paint::solid(Color::rgb(0.0, 1.0, 0.0)); + let style = CharStyle { size: 40.0, fill: blue, stroke: green, stroke_width: 2.0, ..Default::default() }; + let mut d = Document::new(200.0, 200.0); + let text = Node::new(d.alloc_id(), NodeKind::Text(Box::new(TextObject::point(Point::new(5.0, 60.0), "IIII", style)))); + let red = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); + let square = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 200.0)), red); + let clip = Node::new(d.alloc_id(), NodeKind::Group { children: vec![std::sync::Arc::new(text), std::sync::Arc::new(square)], clip: true }); + let mut outer = Node::group(d.alloc_id(), vec![std::sync::Arc::new(clip)]); + outer.appearance.effects.push(Effect { params: json!({"offset": 1}), ..fx("path.offsetPath") }); + let l = d.layers[0].id; + d.insert(Some(l), 0, outer).unwrap(); + let svg = export(&d, &ExportOptions::default()); + let back = vectorcraft_svg::import(&svg).unwrap_or_else(|e| panic!("{e}: {svg}")); + let mut order = vec![]; + for layer in &back.layers { + painted_order(layer, false, &mut order); + } + assert_eq!(order, [('b', true), ('r', true), ('g', false)], "{svg}"); +} diff --git a/crates/text/build.rs b/crates/text/build.rs index 412c471c11..5402ddbe07 100644 --- a/crates/text/build.rs +++ b/crates/text/build.rs @@ -125,16 +125,19 @@ fn web_font_entries(dir: &Path) -> Result<(String, Vec), String> { missing.push(format!("{} {}", e.family, e.style)); continue; }; - let (Some(file), Some(sha)) = (row.get(2), row.get(6)) else { + let (Some(file), Some(scripts), Some(sha)) = (row.get(2), row.get(3), row.get(6)) else { return Err(format!("malformed manifest row for {} {}", e.family, e.style)); }; let integrity = web_fonts::sri(sha).ok_or_else(|| format!("bad sha256 for {} {}", e.family, e.style))?; + let scripts: Vec = scripts.split(',').map(|s| format!("{:?}", s.trim())).collect(); let _ = writeln!( out, - " WebFont {{ family: {:?}, style: {:?}, startup: {}, url: {:?}, integrity: {:?} }},", + " WebFont {{ family: {:?}, style: {:?}, startup: {}, demand: {}, scripts: &[{}], url: {:?}, integrity: {:?} }},", e.family, e.style, e.startup, + e.demand, + scripts.join(", "), web_fonts::url(sha, file), integrity, ); diff --git a/crates/text/build/web_fonts.rs b/crates/text/build/web_fonts.rs index ccd387afab..ac58913afc 100644 --- a/crates/text/build/web_fonts.rs +++ b/crates/text/build/web_fonts.rs @@ -5,8 +5,11 @@ /// One line of `web-fonts.txt`: `when | family | style`. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Listed<'a> { - /// `startup` (fetched before the app starts) rather than `background`. + /// `startup` (fetched before the app starts). pub startup: bool, + /// `demand` (fetched when the interface needs a character of one of the face's scripts). + /// Neither this nor `startup`: `background`. + pub demand: bool, pub family: &'a str, pub style: &'a str, } @@ -23,15 +26,16 @@ pub fn parse_list(text: &str) -> Result>, String> { let [when, family, style] = fields.as_slice() else { return Err(format!("web-fonts.txt line {}: expected `when | family | style`", i + 1)); }; - let startup = match *when { - "startup" => true, - "background" => false, - other => return Err(format!("web-fonts.txt line {}: `{other}` is neither startup nor background", i + 1)), + let (startup, demand) = match *when { + "startup" => (true, false), + "background" => (false, false), + "demand" => (false, true), + other => return Err(format!("web-fonts.txt line {}: `{other}` is not startup, background or demand", i + 1)), }; if family.is_empty() || style.is_empty() { return Err(format!("web-fonts.txt line {}: empty family or style", i + 1)); } - out.push(Listed { startup, family, style }); + out.push(Listed { startup, demand, family, style }); } Ok(out) } @@ -105,12 +109,14 @@ mod tests { #[test] fn list_parsing() { - let l = parse_list("# c\n\nstartup | Noto Sans Arabic | Regular\nbackground | Amiri | Bold Italic\n").unwrap(); + let l = + parse_list("# c\n\nstartup | Noto Sans Arabic | Regular\nbackground | Amiri | Bold Italic\ndemand | NanumGothic | Regular\n").unwrap(); assert_eq!( l, [ - Listed { startup: true, family: "Noto Sans Arabic", style: "Regular" }, - Listed { startup: false, family: "Amiri", style: "Bold Italic" } + Listed { startup: true, demand: false, family: "Noto Sans Arabic", style: "Regular" }, + Listed { startup: false, demand: false, family: "Amiri", style: "Bold Italic" }, + Listed { startup: false, demand: true, family: "NanumGothic", style: "Regular" } ] ); assert!(parse_list("soon | A | B").unwrap_err().contains("line 1")); diff --git a/crates/text/src/craft_fonts.rs b/crates/text/src/craft_fonts.rs index b15b77ec72..24eef3de40 100644 --- a/crates/text/src/craft_fonts.rs +++ b/crates/text/src/craft_fonts.rs @@ -19,8 +19,13 @@ pub struct CraftFont { pub struct WebFont { pub family: &'static str, pub style: &'static str, - /// Fetched before the app starts (a fallback the first frame needs), else in the background. + /// Fetched before the app starts (a fallback the first frame needs). pub startup: bool, + /// Fetched only when the interface needs a character of one of [`WebFont::scripts`] (see + /// [`demand_fonts`]). With neither this nor `startup`, fetched in the background. + pub demand: bool, + /// ISO 15924 scripts the face is for (its craft-fonts manifest row), e.g. `"Hang"`. + pub scripts: &'static [&'static str], /// Site-relative URL, `fonts//`. pub url: &'static str, /// Subresource Integrity value, `sha256-`; the browser rejects other bytes. @@ -106,10 +111,65 @@ pub fn japanese_ui_fonts(bold: bool) -> Vec<&'static CraftFont> { v } +/// The script of `c` that a `demand` web face is fetched for: `"Hang"` for Hangul (jamo, +/// compatibility jamo, syllables and the halfwidth forms) and `"Deva"` for Devanagari (with its +/// extended blocks and the Vedic extensions). `None` for every other character. +pub fn demand_script(c: char) -> Option<&'static str> { + match c as u32 { + 0x1100..=0x11FF | 0x3130..=0x318F | 0xA960..=0xA97F | 0xAC00..=0xD7FF | 0xFFA0..=0xFFDC => Some("Hang"), + 0x0900..=0x097F | 0x1CD0..=0x1CFF | 0xA8E0..=0xA8FF | 0x11B00..=0x11B5F => Some("Deva"), + _ => None, + } +} + +/// The indexes in `fonts` of the `demand` faces for the scripts of `chars` (by +/// [`demand_script`]), each once, in `fonts` order. +pub fn demand_fonts(fonts: &[WebFont], chars: impl IntoIterator) -> Vec { + let mut scripts: Vec<&str> = Vec::new(); + for s in chars.into_iter().filter_map(demand_script) { + if !scripts.contains(&s) { + scripts.push(s); + } + } + fonts.iter().enumerate().filter(|(_, f)| f.demand && f.scripts.iter().any(|s| scripts.contains(s))).map(|(i, _)| i).collect() +} + #[cfg(test)] mod tests { use super::*; + fn web_font(family: &'static str, startup: bool, demand: bool, scripts: &'static [&'static str]) -> WebFont { + WebFont { family, style: "Regular", startup, demand, scripts, url: "", integrity: "" } + } + + #[test] + fn demand_scripts_of_hangul_and_devanagari() { + for c in ['한', '국', 'ㄱ', 'ᄀ', 'ᄀ'] { + assert_eq!(demand_script(c), Some("Hang"), "{c}"); + } + for c in ['ह', 'ि', '्', '़', '।', '\u{A8F2}'] { + assert_eq!(demand_script(c), Some("Deva"), "{c}"); + } + for c in ['A', 'é', 'ا', 'ก', 'ა', '日', 'ロ', '中'] { + assert_eq!(demand_script(c), None, "{c}"); + } + } + + #[test] + fn demand_fonts_follow_the_scripts_painted() { + let fonts = [ + web_font("Arabic", true, false, &["Arab"]), + web_font("Picked", false, false, &["Hang"]), + web_font("Korean", false, true, &["Hang", "Kore"]), + web_font("Devanagari", false, true, &["Deva"]), + ]; + assert_eq!(demand_fonts(&fonts, "한국어".chars()), [2], "Korean fetches only the Korean face"); + assert_eq!(demand_fonts(&fonts, "हिन्दी".chars()), [3], "Hindi fetches only the Devanagari face"); + assert_eq!(demand_fonts(&fonts, "हिन्दी 한국어 Layer".chars()), [2, 3], "each once, in list order"); + assert!(demand_fonts(&fonts, "English العربية 日本語".chars()).is_empty(), "other scripts fetch nothing"); + assert!(demand_fonts(&[], "한국어".chars()).is_empty(), "built without craft-fonts: nothing to fetch"); + } + #[test] fn document_fonts_keep_script_priority_and_include_every_face_once() { let font = |family, style, scripts| CraftFont { family, style, scripts, bytes: &[] }; @@ -157,7 +217,9 @@ mod tests { .collect(); assert_eq!(WEB_FONTS.len(), listed.len()); for (l, w) in listed.iter().zip(WEB_FONTS) { - assert_eq!((l.family, l.style, l.startup), (w.family, w.style, w.startup)); + assert_eq!((l.family, l.style, l.startup, l.demand), (w.family, w.style, w.startup, w.demand)); + let face = CRAFT_FONTS.iter().find(|f| f.family == w.family && f.style == w.style); + assert_eq!(face.map(|f| f.scripts), Some(w.scripts), "{} {}: the manifest's scripts", w.family, w.style); let (dir, name) = w.url.strip_prefix("fonts/").and_then(|r| r.split_once('/')).unwrap(); assert!(dir.len() == 16 && dir.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)), "{}", w.url); assert!(name.ends_with(".ttf") || name.ends_with(".otf"), "{}", w.url); @@ -169,5 +231,11 @@ mod tests { let expected: Vec<_> = ["Noto Sans Arabic", "Noto Sans Thai", "Noto Sans Georgian"].into_iter().filter(|n| CRAFT_FONTS.iter().any(|f| f.family == *n)).collect(); assert_eq!(startup, expected); + // Korean and Devanagari faces are fetched only on demand, never at startup or in the + // background queue every session runs. + let demand: Vec<_> = WEB_FONTS.iter().filter(|w| w.demand).map(|w| w.family).collect(); + let expected: Vec<_> = ["NanumGothic", "Noto Sans Devanagari"].into_iter().filter(|n| CRAFT_FONTS.iter().any(|f| f.family == *n)).collect(); + assert_eq!(demand, expected); + assert!(WEB_FONTS.iter().all(|w| !(w.startup && w.demand))); } } diff --git a/crates/text/src/layout/breaking.rs b/crates/text/src/layout/breaking.rs index ef62fa2bcc..375bc343a2 100644 --- a/crates/text/src/layout/breaking.rs +++ b/crates/text/src/layout/breaking.rs @@ -47,6 +47,7 @@ impl Metrics { FirstBaseline::CapHeight => self.cap, FirstBaseline::XHeight => self.xh, FirstBaseline::Leading => self.lead, + FirstBaseline::EmBoxHeight => self.top, FirstBaseline::Fixed => 0.0, }; v.max(min) diff --git a/crates/text/src/test_fonts.rs b/crates/text/src/test_fonts.rs index 1e1a195db0..7a2a23f089 100644 --- a/crates/text/src/test_fonts.rs +++ b/crates/text/src/test_fonts.rs @@ -1505,6 +1505,19 @@ fn remapped_source_sans(family: &str, postscript: &str, mapping: &[(char, char)] Some(builder.build()) } +/// The family of [`private_use_font`]. +pub const PRIVATE_USE_FAMILY: &str = "Private Use Sans"; + +/// The character [`private_use_font`] maps: the first code point of Supplementary Private Use +/// Area-A, which no bundled or craft-fonts face covers. +pub const PRIVATE_USE_CHAR: char = '\u{F0000}'; + +/// A face that maps only [`PRIVATE_USE_CHAR`] to the bundled Source Sans 3 `H` outline, for tests +/// that need a character no other font covers, with or without craft-fonts. +pub fn private_use_font() -> Option> { + remapped_source_sans(PRIVATE_USE_FAMILY, "PrivateUseSans-Regular", &[(PRIVATE_USE_CHAR, 'H')]) +} + /// The family of [`large_cmap_font`]. pub const LARGE_CMAP_FAMILY: &str = "Largecmap Sans"; diff --git a/crates/text/src/tests/typo.rs b/crates/text/src/tests/typo.rs index 80bd7c783a..1980af6213 100644 --- a/crates/text/src/tests/typo.rs +++ b/crates/text/src/tests/typo.rs @@ -1360,6 +1360,40 @@ fn inset_and_first_baseline_options() { assert!(cap.lines[0].baseline < base.lines[0].baseline && cap.lines[0].baseline > 5.0); } +/// First Baseline Em Box Height: the top of the first line's ideographic em box (the one leading +/// measured from em box top to top uses) touches the top of the type area inside the inset. On a +/// line of several sizes the largest em box decides, and a Min further down sets the baseline. +#[test] +fn em_box_height_puts_the_first_lines_em_box_top_at_the_type_area_top() { + let frame = Rect::new(0.0, 0.0, 300.0, 300.0); + let em_box = |t: &TextObject, inset: f64, min: f64| { + let opts = LayoutOptions { first_baseline: FirstBaseline::EmBoxHeight, first_baseline_min: min, inset, ..Default::default() }; + layout_with(db(), t, &opts).lines[0].baseline + }; + // The em box top the EmBoxTop leading model sets a frame's first line at. + let em_top = |t: &TextObject| { + let mut t = t.clone(); + t.para.leading_model = vectorcraft_doc::LeadingModel::EmBoxTop; + layout(db(), &t).lines[0].baseline + }; + let t = area(COPY, style(12.0), frame, Justify::Left); + let top = em_top(&t); + assert!(top > 5.0 && top < 12.0, "{top}"); + let ascent = layout(db(), &t).lines[0].baseline; + assert!((top - ascent).abs() > 0.1, "not the ascent: {top} {ascent}"); + assert!((em_box(&t, 0.0, 0.0) - top).abs() < 1e-9); + assert!((em_box(&t, 10.0, 0.0) - (10.0 + top)).abs() < 1e-9, "measured from the inset"); + // A Min nearer the top than the em box changes nothing; one further down is the baseline. + assert!((em_box(&t, 10.0, top / 2.0) - (10.0 + top)).abs() < 1e-9); + assert!((em_box(&t, 10.0, 30.0) - 40.0).abs() < 1e-9); + // 10 pt and 20 pt on the first line: the 20 pt em box top is at the top. + let mut mixed = area("small Large", style(10.0), frame, Justify::Left); + mixed.runs = vec![run("small ", 10.0), run("Large", 20.0)]; + let large = area("Large", style(20.0), frame, Justify::Left); + assert!((em_box(&mixed, 0.0, 0.0) - em_box(&large, 0.0, 0.0)).abs() < 1e-9); + assert!((em_box(&large, 0.0, 0.0) - 2.0 * top * 10.0 / 12.0).abs() < 1e-6); +} + /// `LineInfo::first_baseline`: each line that starts a column has its baseline that far below the /// column's top inside the inset, for every first baseline option, with and without a minimum and /// an inset, in both leading models, and for lines of several sizes (each line in one size). @@ -1374,8 +1408,14 @@ fn lines_starting_a_column_sit_at_their_first_baseline() { let text: String = runs.iter().map(|r| r.text.as_str()).collect(); let mut other_sizes = 0; for model in [vectorcraft_doc::LeadingModel::RomanBaseline, vectorcraft_doc::LeadingModel::EmBoxTop] { - for first_baseline in [FirstBaseline::Ascent, FirstBaseline::CapHeight, FirstBaseline::XHeight, FirstBaseline::Leading, FirstBaseline::Fixed] - { + for first_baseline in [ + FirstBaseline::Ascent, + FirstBaseline::CapHeight, + FirstBaseline::XHeight, + FirstBaseline::Leading, + FirstBaseline::EmBoxHeight, + FirstBaseline::Fixed, + ] { for (first_baseline_min, inset) in [(0.0, 0.0), (18.0, 6.0)] { for height in [100.0, 120.0, 140.0] { let mut t = area(&text, style(12.0), Rect::new(0.0, 0.0, 420.0, height), Justify::Left); diff --git a/crates/text/src/tests/vertical.rs b/crates/text/src/tests/vertical.rs index dd12804e91..40c8076b2d 100644 --- a/crates/text/src/tests/vertical.rs +++ b/crates/text/src/tests/vertical.rs @@ -142,6 +142,32 @@ fn fit_first_line_widens_a_vertical_frame_from_its_right_edge() { assert_eq!(layout(FontDb::global(), &t).lines.len(), 1); } +/// First Baseline Em Box Height in vertical area type: the first column's em box edge touches the +/// frame's right edge inside the inset, as far in as leading measured from em box top to top sets +/// it. +#[test] +fn em_box_height_sets_a_vertical_frames_first_column_at_its_em_box() { + use vectorcraft_doc::{FirstBaseline, LeadingModel}; + let first = |fb: FirstBaseline, model: LeadingModel| { + let mut t = vertical("§§"); + t.kind = TextKind::Area { frame: PathData::from_bezpath(&Rect::new(0.0, 0.0, 100.0, 105.0).to_path(0.1)) }; + t.area.first_baseline = fb; + t.area.inset = 5.0; + t.para.leading_model = model; + let l = layout(FontDb::global(), &t); + (l.lines[0].baseline, l.lines[0].first_baseline) + }; + let (baseline, distance) = first(FirstBaseline::EmBoxHeight, LeadingModel::RomanBaseline); + let (em_top, _) = first(FirstBaseline::Ascent, LeadingModel::EmBoxTop); + let (ascent, ascent_distance) = first(FirstBaseline::Ascent, LeadingModel::RomanBaseline); + assert!((baseline - em_top).abs() < 1e-9, "{baseline} {em_top}"); + // Measured from the edge inside the inset, where a Fixed first baseline of 0 sits. + let (edge, _) = first(FirstBaseline::Fixed, LeadingModel::RomanBaseline); + assert!((baseline - distance - edge).abs() < 1e-9, "{baseline} {distance} {edge}"); + assert!((ascent - ascent_distance - edge).abs() < 1e-9, "{ascent} {ascent_distance} {edge}"); + assert!((baseline - ascent).abs() > 0.1, "not the ascent: {baseline} {ascent}"); +} + /// `baselines`: one per line that holds characters, along it for horizontal type and down the /// column's centre line for vertical type (where point type's anchor is); none on a path. #[test] diff --git a/crates/text/src/tests/warichu.rs b/crates/text/src/tests/warichu.rs index cbefb86bb5..7434e43db2 100644 --- a/crates/text/src/tests/warichu.rs +++ b/crates/text/src/tests/warichu.rs @@ -231,7 +231,7 @@ fn a_warichu_line_keeps_the_auto_leading_of_its_own_size() { #[test] fn the_first_baseline_measures_a_block_at_its_own_size() { use vectorcraft_doc::FirstBaseline; - for first in [FirstBaseline::Ascent, FirstBaseline::CapHeight, FirstBaseline::XHeight, FirstBaseline::Leading] { + for first in [FirstBaseline::Ascent, FirstBaseline::CapHeight, FirstBaseline::XHeight, FirstBaseline::Leading, FirstBaseline::EmBoxHeight] { let baseline = |inside: CharStyle| { let mut t = area("", style(20.0), Rect::new(0.0, 0.0, 300.0, 300.0), Justify::Left); t.area.first_baseline = first; diff --git a/crates/text/web-fonts.txt b/crates/text/web-fonts.txt index 7dbb8953b3..235ba98e13 100644 --- a/crates/text/web-fonts.txt +++ b/crates/text/web-fonts.txt @@ -2,6 +2,8 @@ # One face per line: when | family | style (family and style as in craft-fonts' fonts/manifest.txt). # startup = fetched before the app starts (fallbacks the first frame needs) # background = fetched after the app starts (fonts users pick by name) +# demand = fetched only when the interface language or the interface's own text needs one of +# the face's scripts (Korean, Hindi) # Read by build.rs (the WEB_FONTS table) and `cargo xtask web-fonts` (copies the files, a Trunk hook). startup | Noto Sans Arabic | Regular startup | Noto Sans Thai | Regular @@ -36,3 +38,5 @@ background | Reem Kufi | Regular background | Aref Ruqaa | Regular background | Aref Ruqaa | Bold background | Gulzar | Regular +demand | NanumGothic | Regular +demand | Noto Sans Devanagari | Regular diff --git a/crates/three-d/src/fold.rs b/crates/three-d/src/fold.rs index 2dbff773f9..1bfb46f93b 100644 --- a/crates/three-d/src/fold.rs +++ b/crates/three-d/src/fold.rs @@ -34,6 +34,18 @@ pub enum LineKind { Perforation, } +impl LineKind { + /// The angle (degrees) a line of this kind folds at: 90 for a Crease or a Perforation, -90 for + /// a Partial Cut. A positive angle folds away from the printed side; none for a Cut. + pub fn fold_angle(self) -> Option { + match self { + LineKind::Cut => None, + LineKind::Crease | LineKind::Perforation => Some(90.0), + LineKind::PartialCut => Some(-90.0), + } + } +} + /// A fold line: the path (document coordinates), its kind, and a key the issues name it by. #[derive(Clone, Debug)] pub struct FoldLine { @@ -57,10 +69,18 @@ pub struct Panel { pub area: f64, } +impl Panel { + /// A point inside the panel, or the middle of its bounds for one too thin to find one in. + pub fn point_inside(&self) -> Option { + point_in(&self.outline) + } +} + /// The hinge between panels `a` and `b` (indices into the blank's panels, `a` < `b`): the straight /// line from `from` to `to`, made of the lines `keys`. `straight` is false when its pieces are not on /// one straight line within the tolerance; `from` and `to` are then on the line through its longest -/// piece. +/// piece. `angle` (degrees) is the fold angle of the kind of line its longest piece is +/// ([`LineKind::fold_angle`]). #[derive(Clone, Debug)] pub struct Hinge { pub a: usize, @@ -69,6 +89,7 @@ pub struct Hinge { pub to: Point, pub keys: Vec, pub straight: bool, + pub angle: f64, } /// What can be wrong with fold lines, in the order [`blanks`] lists them. @@ -1276,7 +1297,9 @@ impl Context<'_> { let sp = p.path.subpaths.first()?; Some((sp.anchors.first()?.p, sp.anchors.last()?.p)) }; - let (p0, p1) = group.iter().filter_map(|p| chord(p)).max_by(|x, y| x.0.distance(x.1).total_cmp(&y.0.distance(y.1)))?; + let ((p0, p1), longest) = + group.iter().filter_map(|p| Some((chord(p)?, p))).max_by(|(x, _), (y, _)| x.0.distance(x.1).total_cmp(&y.0.distance(y.1)))?; + let angle = longest.lines.iter().filter_map(|&l| self.lines.get(l)?.kind.fold_angle()).next().unwrap_or(90.0); let len = p0.distance(p1); // The longest piece only sets the direction; the length check is on the whole hinge below. if len.is_nan() || len <= 1e-9 { @@ -1308,7 +1331,7 @@ impl Context<'_> { let mut keys = self.keys(lines); keys.sort_unstable(); keys.dedup(); - Some(Hinge { a, b, from: p0 + d * lo, to: p0 + d * hi, keys, straight }) + Some(Hinge { a, b, from: p0 + d * lo, to: p0 + d * hi, keys, straight, angle }) } /// Creases with no hinge: outside every blank, or dividing no two panels; and creases beside a @@ -1426,7 +1449,7 @@ impl Context<'_> { /// The base panel of `panels`: the largest by area; panels whose areas differ by less than 1e-9 of /// the larger tie, and the tie goes to the one whose inside point is highest on the page, then /// leftmost. -fn base_panel(panels: &[Panel]) -> Option { +pub fn base_panel(panels: &[Panel]) -> Option { let top = panels.iter().map(|p| p.area).fold(f64::NEG_INFINITY, f64::max); if !top.is_finite() { return None; @@ -1440,5 +1463,9 @@ fn base_panel(panels: &[Panel]) -> Option { .map(|(i, _)| i) } +mod pose; +pub mod raster; +pub use pose::{Folded, FoldedHinge, FoldedPanel, MAX_POLYGON_POINTS, Pose, fold, panel_at, pick, polygon}; + #[cfg(test)] mod tests; diff --git a/crates/three-d/src/fold/pose.rs b/crates/three-d/src/fold/pose.rs new file mode 100644 index 0000000000..650ab54291 --- /dev/null +++ b/crates/three-d/src/fold/pose.rs @@ -0,0 +1,407 @@ +//! A blank folded into its 3D shape ([`fold`]). +//! +//! The flat blank lies at z = 0 with document x to the right and document y flipped so y points up; +//! the printed side faces +z. The base panel stays in place. The other panels are reached from it +//! through a breadth-first tree of hinges, each panel's hinges taken in the order of their ends (y, +//! then x, the first end first), so the tree does not depend on the order the lines were drawn in. A child +//! panel turns about its hinge by the hinge's angle times the fold amount; a positive angle moves it +//! toward -z, away from the printed side, whichever way the hinge was drawn. Hinges outside the tree +//! close a loop of panels: [`FoldedHinge::gap`] says how far apart their two placements end up when +//! the blank is folded all the way. + +use std::collections::{HashSet, VecDeque}; + +use vectorcraft_geom::{PathData, PathEl, Point, Shape as _}; + +use super::{Blank, base_panel, point_in}; + +/// Most points a panel's outline is flattened to; a panel with more is left out of the collision +/// test and the preview. +pub const MAX_POLYGON_POINTS: usize = 1 << 16; + +type V3 = [f64; 3]; + +fn sub(a: V3, b: V3) -> V3 { + [a[0] - b[0], a[1] - b[1], a[2] - b[2]] +} + +fn add(a: V3, b: V3) -> V3 { + [a[0] + b[0], a[1] + b[1], a[2] + b[2]] +} + +fn scale(a: V3, s: f64) -> V3 { + [a[0] * s, a[1] * s, a[2] * s] +} + +fn dot(a: V3, b: V3) -> f64 { + a[0] * b[0] + a[1] * b[1] + a[2] * b[2] +} + +fn cross(a: V3, b: V3) -> V3 { + [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]] +} + +fn length(a: V3) -> f64 { + dot(a, a).sqrt() +} + +/// A document point on the flat blank (y flipped so it points up, z = 0). +pub(super) fn flat(p: Point) -> V3 { + [p.x, -p.y, 0.0] +} + +/// Where a panel is: a rotation `m` (rows) and a translation `t`, taking a point of the flat +/// blank (see [`flat`]) to its place in 3D. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Pose { + pub m: [[f64; 3]; 3], + pub t: [f64; 3], +} + +impl Pose { + /// The flat blank's own place. + pub const IDENTITY: Pose = Pose { m: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], t: [0.0; 3] }; + + /// Where the flat point `v` goes. + pub fn apply(&self, v: [f64; 3]) -> [f64; 3] { + add(self.turn(v), self.t) + } + + /// The direction `v` turned by the rotation alone. + pub fn turn(&self, v: [f64; 3]) -> [f64; 3] { + let [a, b, c] = self.m; + [dot(a, v), dot(b, v), dot(c, v)] + } + + /// Where the document point `p` goes. + pub fn place(&self, p: Point) -> [f64; 3] { + self.apply(flat(p)) + } + + /// The direction the printed side faces. + pub fn normal(&self) -> [f64; 3] { + self.turn([0.0, 0.0, 1.0]) + } + + /// This pose followed, in the flat blank's terms, by a right-handed turn of `theta` radians + /// about the line through `at` along the unit direction `axis`: the pose of a panel hinged to + /// this one there. + fn turned_about(&self, at: V3, axis: V3, theta: f64) -> Pose { + let (s, c) = theta.sin_cos(); + let [x, y, z] = axis; + // Rodrigues' rotation matrix. + let r = [ + [c + x * x * (1.0 - c), x * y * (1.0 - c) - z * s, x * z * (1.0 - c) + y * s], + [y * x * (1.0 - c) + z * s, c + y * y * (1.0 - c), y * z * (1.0 - c) - x * s], + [z * x * (1.0 - c) - y * s, z * y * (1.0 - c) + x * s, c + z * z * (1.0 - c)], + ]; + let mut m = [[0.0; 3]; 3]; + for (i, row) in m.iter_mut().enumerate() { + for (j, cell) in row.iter_mut().enumerate() { + *cell = (0..3).map(|k| self.m[i][k] * r[k][j]).sum(); + } + } + // p ↦ self(r (p - at) + at) = (self.m r) p + self.m (at - r at) + self.t + let r_at = [dot(r[0], at), dot(r[1], at), dot(r[2], at)]; + Pose { m, t: add(self.turn(sub(at, r_at)), self.t) } + } +} + +/// A folded panel: where it is, its parent in the fold tree (`None` for the base and for a panel no +/// chain of hinges joins to it, which stays flat where it is) and how many hinges lie between it +/// and the base. +#[derive(Clone, Debug)] +pub struct FoldedPanel { + pub pose: Pose, + pub parent: Option, + pub depth: usize, +} + +/// A folded hinge: its panels, its angle (degrees, before the fold amount), whether it is in the +/// fold tree and, for one that is not, how far apart its two placements end up with every hinge at +/// its full angle, whatever the fold amount (`gap`, points), and whether that is close enough to call +/// it closed. +#[derive(Clone, Debug)] +pub struct FoldedHinge { + pub a: usize, + pub b: usize, + pub angle: f64, + pub tree: bool, + pub closes: bool, + pub gap: f64, +} + +/// A blank folded at one amount. +#[derive(Clone, Debug)] +pub struct Folded { + pub base: usize, + pub panels: Vec, + /// The panels in breadth-first order from the base, the panels not joined to it last. + pub order: Vec, + pub hinges: Vec, + /// Pairs of panels (`a` < `b`) that pass through each other. + pub collisions: Vec<(usize, usize)>, +} + +/// The panel of `blank` that `p` (document coordinates) lies in. +pub fn panel_at(blank: &Blank, p: Point) -> Option { + blank.panels.iter().position(|panel| panel.outline.to_bezpath().winding(p) != 0) +} + +/// Which of `blanks` to fold, and about which of its panels: the blank and panel `at` (document +/// coordinates) lies in, or, without a point, the blank with the largest panel (the first of equals) +/// and its base panel. `None` when `at` lies in no panel, or no blank has a panel. +pub fn pick(blanks: &[Blank], at: Option) -> Option<(usize, usize)> { + match at { + Some(p) => blanks.iter().enumerate().find_map(|(i, b)| Some((i, panel_at(b, p)?))), + None => { + let largest = |b: &Blank| b.panels.iter().map(|p| p.area).fold(f64::NEG_INFINITY, f64::max); + let (i, b) = + blanks.iter().enumerate().filter(|(_, b)| !b.panels.is_empty()).fold(None, |best: Option<(usize, &Blank)>, (i, b)| match best { + Some((_, kept)) if largest(kept) >= largest(b) => best, + _ => Some((i, b)), + })?; + Some((i, base_panel(&b.panels)?)) + } + } +} + +/// `blank` folded about its panel `base` (the largest when `None`) by `amount` (0, flat, to 1, every +/// hinge at its angle). `tolerance` (points) is how far apart a closing hinge's placements may end +/// up and still close (or 0.5% of its length, when that is more), and how far apart two panels in +/// one plane may lie and still be stacked rather than crossing. `None` when the blank has no +/// panels, `base` is not one of them, or `amount` is not from 0 to 1. +pub fn fold(blank: &Blank, base: Option, amount: f64, tolerance: f64) -> Option { + let base = match base { + Some(b) => b, + None => base_panel(&blank.panels)?, + }; + if base >= blank.panels.len() || !(0.0..=1.0).contains(&amount) { + return None; + } + let tolerance = if tolerance.is_finite() && tolerance > 0.0 { tolerance } else { 0.01 }; + let n = blank.panels.len(); + // Each panel's hinges, by the place they start (y, then x), then by the other panel. + let mut by_panel: Vec> = vec![vec![]; n]; + for (i, h) in blank.hinges.iter().enumerate() { + for p in [h.a, h.b] { + if let Some(list) = by_panel.get_mut(p) { + list.push(i); + } + } + } + // A hinge's ends, the one first by (y, x) first. + let ends = |i: &usize| { + blank.hinges.get(*i).map_or([f64::INFINITY; 4], |h| { + let (s, e) = if (h.from.y, h.from.x) <= (h.to.y, h.to.x) { (h.from, h.to) } else { (h.to, h.from) }; + [s.y, s.x, e.y, e.x] + }) + }; + for list in &mut by_panel { + list.sort_by(|a, b| { + let (ka, kb) = (ends(a), ends(b)); + ka.iter().zip(&kb).fold(std::cmp::Ordering::Equal, |o, (x, y)| o.then(x.total_cmp(y))).then(a.cmp(b)) + }); + } + let centers: Vec> = blank.panels.iter().map(|p| point_in(&p.outline).map(flat)).collect(); + let (panels, tree, order) = place(blank, &by_panel, ¢ers, base, amount); + // Closing hinges are measured with every hinge at its full angle, so a blank that closes when + // folded is not reported open part of the way there. + let full = if amount == 1.0 { None } else { Some(place(blank, &by_panel, ¢ers, base, 1.0).0) }; + let measured = full.as_deref().unwrap_or(&panels); + let hinges = blank + .hinges + .iter() + .zip(&tree) + .map(|(h, &tree)| { + let (pa, pb) = (measured.get(h.a).map(|p| p.pose), measured.get(h.b).map(|p| p.pose)); + let gap = match (pa, pb) { + (Some(pa), Some(pb)) if !tree => [h.from, h.to].iter().map(|&e| length(sub(pa.place(e), pb.place(e)))).fold(0.0, f64::max), + _ => 0.0, + }; + let closes = tree || gap <= tolerance.max(0.005 * h.from.distance(h.to)); + FoldedHinge { a: h.a, b: h.b, angle: h.angle, tree, closes, gap } + }) + .collect(); + let collisions = collisions(blank, &panels, tolerance); + Some(Folded { base, panels, order, hinges, collisions }) +} + +/// The panels of `blank` placed by the fold tree from `base` with each hinge at `amount` of its +/// angle, which hinges are in the tree, and the panels in breadth-first order (the panels not +/// joined to the base last). +fn place(blank: &Blank, by_panel: &[Vec], centers: &[Option], base: usize, amount: f64) -> (Vec, Vec, Vec) { + let n = blank.panels.len(); + let mut panels: Vec = vec![FoldedPanel { pose: Pose::IDENTITY, parent: None, depth: 0 }; n]; + let mut reached = vec![false; n]; + let mut tree = vec![false; blank.hinges.len()]; + let mut order = Vec::with_capacity(n); + let mut queue = VecDeque::from([base]); + if let Some(r) = reached.get_mut(base) { + *r = true; + } + while let Some(p) = queue.pop_front() { + order.push(p); + let Some(parent) = panels.get(p).cloned() else { continue }; + for &hi in by_panel.get(p).map(Vec::as_slice).unwrap_or_default() { + let Some(h) = blank.hinges.get(hi) else { continue }; + let child = if h.a == p { h.b } else { h.a }; + if reached.get(child) != Some(&false) { + continue; + } + let (mut from, mut to) = (flat(h.from), flat(h.to)); + let len = length(sub(to, from)); + if !(len.is_finite() && len > 0.0) { + continue; + } + // The parent on the left of the hinge's direction, the child on its right. The side is + // read next to the hinge, so a parent with a notch or an arm past the hinge's line still + // turns the child the right way; the panel's inside point is the fallback. + let left = match blank.panels.get(p).and_then(|panel| side_of(&panel.outline, from, to, len)) { + Some(left) => left, + None => centers.get(p).copied().flatten().is_none_or(|c| cross(sub(to, from), sub(c, from))[2] >= 0.0), + }; + if !left { + std::mem::swap(&mut from, &mut to); + } + let axis = scale(sub(to, from), 1.0 / len); + let theta = (h.angle * amount).to_radians(); + if !theta.is_finite() { + continue; + } + if let Some(slot) = panels.get_mut(child) { + *slot = FoldedPanel { pose: parent.pose.turned_about(from, axis, theta), parent: Some(p), depth: parent.depth + 1 }; + } + if let Some(r) = reached.get_mut(child) { + *r = true; + } + if let Some(t) = tree.get_mut(hi) { + *t = true; + } + queue.push_back(child); + } + } + order.extend((0..n).filter(|&i| reached.get(i) == Some(&false))); + (panels, tree, order) +} + +/// Whether `outline` lies on the left of the line from `from` to `to` (flat coordinates, `len` apart) +/// next to its middle: `Some(true)` when a point just off the middle on the left is inside it and +/// the matching point on the right is not, `Some(false)` the other way round, `None` when no offset +/// tells them apart. The nearest offset is tried first. +fn side_of(outline: &PathData, from: V3, to: V3, len: f64) -> Option { + let bp = outline.to_bezpath(); + let mid = scale(add(from, to), 0.5); + let left = [-(to[1] - from[1]) / len, (to[0] - from[0]) / len, 0.0]; + let doc = |v: V3| Point::new(v[0], -v[1]); + let mut offsets = [1e-3, 0.25, len * 0.01]; + offsets.sort_by(f64::total_cmp); + offsets.into_iter().find_map(|off| { + let (l, r) = (bp.winding(doc(add(mid, scale(left, off)))) != 0, bp.winding(doc(sub(mid, scale(left, off)))) != 0); + (l != r).then_some(l) + }) +} + +/// The rings of `path` flattened to `tolerance`, in document coordinates; `None` past +/// [`MAX_POLYGON_POINTS`] points. +pub fn polygon(path: &PathData, tolerance: f64) -> Option>> { + let mut rings: Vec> = vec![]; + let mut count = 0usize; + let mut fits = true; + vectorcraft_geom::flatten(path.to_bezpath(), tolerance, |el| { + if !fits { + return; + } + match el { + PathEl::MoveTo(p) => rings.push(vec![p]), + PathEl::LineTo(p) => match rings.last_mut() { + Some(r) => r.push(p), + None => rings.push(vec![p]), + }, + _ => return, + } + count += 1; + fits = count <= MAX_POLYGON_POINTS; + }); + rings.retain(|r| r.len() >= 3); + (fits && rings.iter().flatten().all(|p| p.is_finite())).then_some(rings) +} + +/// A panel placed in 3D: its rings, the plane it lies in (unit normal and offset) and its bounds. +struct Placed { + rings: Vec>, + normal: V3, + offset: f64, + lo: V3, + hi: V3, +} + +/// The pairs of `panels` that pass through each other. Two panels hinged to each other are not +/// tested, nor two in parallel planes (stacked in one plane, or apart). +fn collisions(blank: &Blank, panels: &[FoldedPanel], tolerance: f64) -> Vec<(usize, usize)> { + let placed: Vec> = blank + .panels + .iter() + .zip(panels) + .map(|(panel, f)| { + let rings: Vec> = + polygon(&panel.outline, tolerance)?.into_iter().map(|r| r.into_iter().map(|p| f.pose.place(p)).collect()).collect(); + let all = rings.iter().flatten(); + let lo = all.clone().fold([f64::INFINITY; 3], |a, p| [a[0].min(p[0]), a[1].min(p[1]), a[2].min(p[2])]); + let hi = all.fold([f64::NEG_INFINITY; 3], |a, p| [a[0].max(p[0]), a[1].max(p[1]), a[2].max(p[2])]); + let normal = f.pose.normal(); + let offset = dot(normal, f.pose.t); + Some(Placed { rings, normal, offset, lo, hi }) + }) + .collect(); + let hinged: HashSet<(usize, usize)> = blank.hinges.iter().map(|h| (h.a.min(h.b), h.a.max(h.b))).collect(); + let mut out = vec![]; + for (i, a) in placed.iter().enumerate() { + let Some(a) = a else { continue }; + for (j, b) in placed.iter().enumerate().skip(i + 1) { + let Some(b) = b else { continue }; + if hinged.contains(&(i, j)) || (0..3).any(|k| a.hi[k] + tolerance < b.lo[k] || b.hi[k] + tolerance < a.lo[k]) { + continue; + } + let line = cross(a.normal, b.normal); + let along = length(line); + if along.is_nan() || along <= 1e-9 { + continue; + } + let u = scale(line, 1.0 / along); + let on_a = crossings(&a.rings, b.normal, b.offset, u, tolerance); + let on_b = crossings(&b.rings, a.normal, a.offset, u, tolerance); + if on_a.iter().any(|x| on_b.iter().any(|y| x.1.min(y.1) - x.0.max(y.0) > tolerance)) { + out.push((i, j)); + } + } + } + out +} + +/// Where `rings` cross the plane `normal · p = offset`: the spans of the line along `u` that lie +/// inside them, by their place along `u`. A panel with no point more than `tolerance` to one side +/// of the plane only touches it, and crosses it nowhere; otherwise points within `tolerance` of it +/// count as on its positive side. +fn crossings(rings: &[Vec], normal: V3, offset: f64, u: V3, tolerance: f64) -> Vec<(f64, f64)> { + let side = |p: V3| dot(normal, p) - offset; + let sides = rings.iter().flatten().map(|&p| side(p)); + let (above, below) = sides.fold((false, false), |(a, b), s| (a || s > tolerance, b || s < -tolerance)); + if !(above && below) { + return vec![]; + } + let mut at = vec![]; + for ring in rings { + for (k, &p) in ring.iter().enumerate() { + let Some(&q) = ring.get((k + 1) % ring.len()) else { continue }; + let (sp, sq) = (side(p), side(q)); + if (sp >= -tolerance) != (sq >= -tolerance) { + let t = (sp / (sp - sq)).clamp(0.0, 1.0); + at.push(dot(u, add(p, scale(sub(q, p), t)))); + } + } + } + at.retain(|x| x.is_finite()); + at.sort_by(f64::total_cmp); + at.as_chunks::<2>().0.iter().map(|&[a, b]| (a, b)).collect() +} diff --git a/crates/three-d/src/fold/raster.rs b/crates/three-d/src/fold/raster.rs new file mode 100644 index 0000000000..9cccbaf6d9 --- /dev/null +++ b/crates/three-d/src/fold/raster.rs @@ -0,0 +1,495 @@ +//! Draws a [`Folded`] blank as pixels: each panel's outline is projected through the view and filled +//! by scanline, with a depth buffer, and each pixel takes its color from a raster of the flat print +//! (the printed side) or from the inside color (the back), shaded by the panel's slope to a fixed +//! light. The inverse of the panel's projective map gives the flat point under every pixel, so the +//! print is drawn without seams under perspective. With perspective, each panel is cut at a near +//! plane in front of the eye before it is projected. + +use vectorcraft_geom::{Point, Rect}; + +use super::pose::{Folded, polygon}; +use super::{Blank, Panel}; + +/// Most pixels a side of the view or of the print raster may have. +pub const MAX_SIDE: u32 = 4096; +/// Most pixels the view may have in all (2,048 × 1,024; 32 MiB of buffers). +pub const MAX_PIXELS: u32 = 1 << 21; +/// The share of the eye's distance a panel is cut at in front of the eye. +const NEAREST: f64 = 1e-3; +/// How far apart (points of view depth) two panels may be and still tie. +const TIE: f64 = 1e-4; +/// The light's direction: above, to the left of and toward the viewer. +const LIGHT: [f64; 3] = [-0.37, 0.56, 0.74]; + +type V3 = [f64; 3]; + +fn dot(a: V3, b: V3) -> f64 { + a[0] * b[0] + a[1] * b[1] + a[2] * b[2] +} + +/// The view: its size in pixels, its turn (degrees: `rotate_x` tips the top toward the viewer, +/// `rotate_y` turns the right side toward the viewer), its scale (pixels per point at the center's +/// depth), how far it is moved (pixels), its perspective (the field of view in degrees; 0 for none) +/// and the 3D point at its middle. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Camera { + pub width: u32, + pub height: u32, + pub rotate_x: f64, + pub rotate_y: f64, + pub scale: f64, + pub pan: [f64; 2], + pub perspective: f64, + pub center: [f64; 3], +} + +impl Camera { + /// The turn from 3D to the view's own axes (x right, y up, z toward the viewer), as rows. + fn rotation(&self) -> [[f64; 3]; 3] { + let (sx, cx) = self.rotate_x.to_radians().sin_cos(); + let (sy, cy) = (-self.rotate_y).to_radians().sin_cos(); + // Rx · Ry + [[cy, 0.0, sy], [sx * sy, cx, -sx * cy], [-cx * sy, sx, cx * cy]] + } + + /// The point `p` in the view's own axes, its middle at the origin. + pub fn to_view(&self, p: V3) -> V3 { + let r = self.rotation(); + let d = [p[0] - self.center[0], p[1] - self.center[1], p[2] - self.center[2]]; + [dot(r[0], d), dot(r[1], d), dot(r[2], d)] + } + + /// The distance (points) from the eye to the view's middle and the focal length (pixels) under + /// perspective; `None` without it. + fn eye(&self) -> Option<(f64, f64)> { + if self.perspective <= 0.0 || self.perspective >= 180.0 { + return None; + } + let half = f64::from(self.width.min(self.height)) / 2.0; + let focal = half / (self.perspective.to_radians() / 2.0).tan(); + let eye = focal / self.scale; + (focal.is_finite() && eye.is_finite() && eye > 0.0).then_some((eye, focal)) + } + + fn usable(&self) -> bool { + let finite = + [self.rotate_x, self.rotate_y, self.scale, self.pan[0], self.pan[1], self.perspective].iter().chain(&self.center).all(|v| v.is_finite()); + let pixels = u64::from(self.width) * u64::from(self.height); + finite && self.scale > 0.0 && (1..=MAX_SIDE).contains(&self.width) && (1..=MAX_SIDE).contains(&self.height) && pixels <= u64::from(MAX_PIXELS) + } +} + +/// One level of the print raster: premultiplied RGBA, 4 bytes a pixel. +#[derive(Clone, Debug)] +pub struct Level { + pub width: u32, + pub height: u32, + pub pixels: Vec, +} + +impl Level { + /// The color at pixel `(x, y)`, clamped to the edges. + fn at(&self, x: i64, y: i64) -> [f32; 4] { + let x = x.clamp(0, i64::from(self.width) - 1); + let y = y.clamp(0, i64::from(self.height) - 1); + let i = usize::try_from((y * i64::from(self.width) + x) * 4).unwrap_or(usize::MAX); + match self.pixels.get(i..i.saturating_add(4)) { + Some(&[r, g, b, a]) => [f32::from(r), f32::from(g), f32::from(b), f32::from(a)], + _ => [0.0; 4], + } + } + + /// The color at `(x, y)` (pixels), between the four nearest pixels. + fn sample(&self, x: f64, y: f64) -> [f32; 4] { + let (fx, fy) = (x - 0.5, y - 0.5); + let (x0, y0) = (fx.floor(), fy.floor()); + let (tx, ty) = ((fx - x0) as f32, (fy - y0) as f32); + let (x0, y0) = (x0 as i64, y0 as i64); + let (a, b, c, d) = (self.at(x0, y0), self.at(x0 + 1, y0), self.at(x0, y0 + 1), self.at(x0 + 1, y0 + 1)); + let mut out = [0.0; 4]; + for (k, o) in out.iter_mut().enumerate() { + let top = a[k] + (b[k] - a[k]) * tx; + let bottom = c[k] + (d[k] - c[k]) * tx; + *o = top + (bottom - top) * ty; + } + out + } + + /// This level at half its size, rounded up, each pixel the mean of the pixels it covers weighted + /// by the area of the full print they cover. A pixel of this level is `step` pixels of the full + /// print (`base` pixels across and down) on a side, and fewer in the last column and row when + /// `base` is not a multiple of `step`. + fn half(&self, base: (u32, u32), step: u32) -> Option { + let (w, h) = (self.width.div_ceil(2), self.height.div_ceil(2)); + if (w, h) == (self.width, self.height) { + return None; + } + // The pixels of the full print that column or row `i` of this level covers, or 0 past it. + let covers = |i: u32, side: u32| u64::from(side).saturating_sub(u64::from(i) * u64::from(step)).min(u64::from(step)) as f32; + let mut pixels = Vec::with_capacity(w as usize * h as usize * 4); + for y in 0..h { + for x in 0..w { + let mut sum = [0.0f32; 4]; + let mut area = 0.0; + for (sx, sy) in [(2 * x, 2 * y), (2 * x + 1, 2 * y), (2 * x, 2 * y + 1), (2 * x + 1, 2 * y + 1)] { + if sx >= self.width || sy >= self.height { + continue; + } + let a = covers(sx, base.0) * covers(sy, base.1); + let p = self.at(i64::from(sx), i64::from(sy)); + for (s, c) in sum.iter_mut().zip(p) { + *s += c * a; + } + area += a; + } + for s in sum { + pixels.push(if area > 0.0 { (s / area).round() as u8 } else { 0 }); + } + } + } + Some(Level { width: w, height: h, pixels }) + } +} + +/// The flat print: the document rect it covers and its raster at full size and halved again and +/// again down to one pixel. +#[derive(Clone, Debug)] +pub struct Print { + pub region: Rect, + pub levels: Vec, +} + +impl Print { + /// The print of `region` from `pixels` (premultiplied RGBA, `width` × `height`); `None` when + /// the sizes do not agree, a side is 0 or more than [`MAX_SIDE`], or the region is empty. + pub fn new(region: Rect, width: u32, height: u32, pixels: Vec) -> Option { + let fits = (1..=MAX_SIDE).contains(&width) && (1..=MAX_SIDE).contains(&height); + let empty = !(region.width() > 0.0 && region.height() > 0.0 && region.is_finite()); + if !fits || empty || pixels.len() != width as usize * height as usize * 4 { + return None; + } + let mut levels = vec![Level { width, height, pixels }]; + let mut step = 1; + while let Some(next) = levels.last().and_then(|l| l.half((width, height), step)) { + levels.push(next); + step *= 2; + } + Some(Print { region, levels }) + } + + /// The print's color (premultiplied, 0 to 255) at document point `p`, from the level whose + /// pixels are closest to `footprint` points across; transparent outside the region. + fn sample(&self, p: Point, footprint: f64) -> [f32; 4] { + let Some(base) = self.levels.first() else { return [0.0; 4] }; + if !self.region.contains(p) { + return [0.0; 4]; + } + let per_point = f64::from(base.width) / self.region.width(); + let level = if footprint.is_finite() && footprint > 0.0 { (footprint * per_point).log2().floor().max(0.0) as usize } else { 0 }; + let level = level.min(self.levels.len() - 1); + let Some(l) = self.levels.get(level) else { return [0.0; 4] }; + // Each level halves the one before it, so a pixel of level n covers 2ⁿ of the first's. + let shrink = f64::from(1u32 << level); + let sx = f64::from(base.width) / self.region.width() / shrink; + let sy = f64::from(base.height) / self.region.height() / shrink; + l.sample((p.x - self.region.x0) * sx, (p.y - self.region.y0) * sy) + } +} + +/// What [`render`] draws: a folded blank, its print (if any), the color of the board's back and of +/// its printed side where the print has no art (straight RGBA; the board is opaque, so their alpha +/// is not used), and the view. +pub struct Scene<'a> { + pub blank: &'a Blank, + pub folded: &'a Folded, + pub print: Option<&'a Print>, + pub inside: [u8; 4], + pub outside: [u8; 4], + pub camera: Camera, +} + +/// A drawn view: premultiplied RGBA, 4 bytes a pixel, transparent where no panel is; and for each +/// pixel the panel drawn there plus 1 (0 for none). +#[derive(Clone, Debug)] +pub struct Image { + pub width: u32, + pub height: u32, + pub pixels: Vec, + pub panels: Vec, +} + +impl Image { + /// The panel drawn at pixel `(x, y)`. + pub fn panel_at(&self, x: u32, y: u32) -> Option { + if x >= self.width || y >= self.height { + return None; + } + let i = y as usize * self.width as usize + x as usize; + self.panels.get(i).and_then(|&p| usize::from(p).checked_sub(1)) + } +} + +/// The 3D bounds of `blank`'s panels folded as `folded` places them (low and high corners). +pub fn bounds(blank: &Blank, folded: &Folded) -> Option<(V3, V3)> { + let mut lo = [f64::INFINITY; 3]; + let mut hi = [f64::NEG_INFINITY; 3]; + for (panel, f) in blank.panels.iter().zip(&folded.panels) { + let Some(b) = panel.outline.bounds() else { continue }; + for c in [Point::new(b.x0, b.y0), Point::new(b.x1, b.y0), Point::new(b.x0, b.y1), Point::new(b.x1, b.y1)] { + let p = f.pose.place(c); + for k in 0..3 { + lo[k] = lo[k].min(p[k]); + hi[k] = hi[k].max(p[k]); + } + } + } + lo.iter().chain(&hi).all(|v| v.is_finite()).then_some((lo, hi)) +} + +/// A panel ready to fill: its projective map from the flat blank to the view and back, its depth +/// plane in view terms, and its color factors. +struct Mapped { + /// Flat (u, v, 1) → (x w, y w, w) in pixels, as rows. + forward: [[f64; 3]; 3], + /// The inverse of `forward`. + inverse: [[f64; 3]; 3], + /// View depth at flat (u, v): u a + v b + c. + depth: [f64; 3], + printed: bool, + shade: f32, +} + +fn mul(m: &[[f64; 3]; 3], v: V3) -> V3 { + [dot(m[0], v), dot(m[1], v), dot(m[2], v)] +} + +fn invert(m: &[[f64; 3]; 3]) -> Option<[[f64; 3]; 3]> { + let [[a, b, c], [d, e, f], [g, h, i]] = *m; + let co = [e * i - f * h, f * g - d * i, d * h - e * g]; + let det = a * co[0] + b * co[1] + c * co[2]; + if !(det.is_finite() && det.abs() > 1e-300) { + return None; + } + let inv = [ + [co[0] / det, (c * h - b * i) / det, (b * f - c * e) / det], + [co[1] / det, (a * i - c * g) / det, (c * d - a * f) / det], + [co[2] / det, (b * g - a * h) / det, (a * e - b * d) / det], + ]; + inv.iter().flatten().all(|v| v.is_finite()).then_some(inv) +} + +fn map_panel(camera: &Camera, f: &super::FoldedPanel) -> Option { + let r = camera.rotation(); + let turn = |v: V3| mul(&r, f.pose.turn(v)); + let (a, b) = (turn([1.0, 0.0, 0.0]), turn([0.0, 1.0, 0.0])); + let o = camera.to_view(f.pose.t); + let (cx, cy) = (f64::from(camera.width) / 2.0 + camera.pan[0], f64::from(camera.height) / 2.0 + camera.pan[1]); + let normal = turn([0.0, 0.0, 1.0]); + let (w, k, printed) = match camera.eye() { + Some((eye, focal)) => ([-a[2], -b[2], eye - o[2]], focal, dot(normal, [-o[0], -o[1], eye - o[2]]) > 0.0), + None => ([0.0, 0.0, 1.0], camera.scale, normal[2] > 0.0), + }; + let x = [cx * w[0] + k * a[0], cx * w[1] + k * b[0], cx * w[2] + k * o[0]]; + let y = [cy * w[0] - k * a[1], cy * w[1] - k * b[1], cy * w[2] - k * o[1]]; + let forward = [x, y, w]; + let inverse = invert(&forward)?; + let facing = if printed { normal } else { [-normal[0], -normal[1], -normal[2]] }; + let shade = (0.6 + 0.4 * dot(facing, LIGHT).max(0.0)) as f32; + Some(Mapped { forward, inverse, depth: [a[2], b[2], o[2]], printed, shade }) +} + +/// `ring` (flat points) cut to the side of the plane `w · (u, v, 1) ≥ near`. +fn clip(ring: &[[f64; 2]], w: V3, near: f64) -> Vec<[f64; 2]> { + let at = |p: [f64; 2]| dot(w, [p[0], p[1], 1.0]) - near; + let mut out = Vec::with_capacity(ring.len() + 4); + for (k, &p) in ring.iter().enumerate() { + let Some(&q) = ring.get((k + 1) % ring.len()) else { continue }; + let (dp, dq) = (at(p), at(q)); + if dp >= 0.0 { + out.push(p); + } + if (dp >= 0.0) != (dq >= 0.0) { + let t = dp / (dp - dq); + out.push([p[0] + (q[0] - p[0]) * t, p[1] + (q[1] - p[1]) * t]); + } + } + out +} + +/// The buffers [`render`] fills. +struct Target { + width: usize, + height: usize, + color: Vec, + depth: Vec, + rank: Vec, + panel: Vec, +} + +/// One panel's fill: its map, rank (for ties), panel number and colors. +struct Fill<'a> { + mapped: &'a Mapped, + rank: u16, + panel: u16, + print: Option<&'a Print>, + inside: [f32; 4], + outside: [f32; 4], +} + +impl Fill<'_> { + /// The document point under pixel center `(x, y)`, or `None` behind the eye. + fn flat_at(&self, x: f64, y: f64) -> Option<(f64, f64)> { + let [u, v, w] = mul(&self.mapped.inverse, [x, y, 1.0]); + (w > 0.0 && w.is_finite()).then(|| (u / w, v / w)).filter(|(u, v)| u.is_finite() && v.is_finite()) + } + + /// The color of the panel at flat point `(u, v)`, `footprint` points across a pixel. + fn color(&self, u: f64, v: f64, footprint: f64) -> [f32; 4] { + let base = if self.mapped.printed { + let p = self.print.map_or([0.0; 4], |pr| pr.sample(Point::new(u, -v), footprint)); + let under = 1.0 - p[3] / 255.0; + [p[0] + self.outside[0] * under, p[1] + self.outside[1] * under, p[2] + self.outside[2] * under, 255.0] + } else { + self.inside + }; + let s = self.mapped.shade; + [base[0] * s, base[1] * s, base[2] * s, base[3]] + } + + /// Fill the span of row `row` from `x0` to `x1` (pixel coordinates) into `target`. + fn span(&self, target: &mut Target, row: usize, x0: f64, x1: f64) { + let first = (x0 - 0.5).ceil().max(0.0); + let last = ((x1 - 0.5).ceil() - 1.0).min(target.width as f64 - 1.0); + if first > last { + return; + } + let y = row as f64 + 0.5; + for col in first as usize..=last as usize { + let x = col as f64 + 0.5; + let Some((u, v)) = self.flat_at(x, y) else { continue }; + let [a, b, c] = self.mapped.depth; + let z = u * a + v * b + c; + let i = row * target.width + col; + let (Some(&zb), Some(&rb)) = (target.depth.get(i), target.rank.get(i)) else { continue }; + let wins = z > zb + TIE || ((z - zb).abs() <= TIE && self.rank > rb); + if !wins { + continue; + } + // The print's footprint is the longer of a pixel's two sides in flat terms. + let across = |dx: f64, dy: f64| self.flat_at(x + dx, y + dy).map_or(0.0, |(u2, v2)| (u2 - u).hypot(v2 - v)); + let footprint = across(1.0, 0.0).max(across(0.0, 1.0)); + let color = self.color(u, v, footprint); + if let Some(px) = target.color.get_mut(i * 4..i * 4 + 4) { + for (o, c) in px.iter_mut().zip(color) { + *o = c.round().clamp(0.0, 255.0) as u8; + } + } + if let Some(d) = target.depth.get_mut(i) { + *d = z; + } + if let Some(r) = target.rank.get_mut(i) { + *r = self.rank; + } + if let Some(p) = target.panel.get_mut(i) { + *p = self.panel; + } + } + } + + /// Fill the projected `rings` (pixel coordinates), even-odd, into `target`. + fn rings(&self, target: &mut Target, rings: &[Vec<[f64; 2]>]) { + let ys = rings.iter().flatten().map(|p| p[1]); + let (lo, hi) = ys.fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), y| (lo.min(y), hi.max(y))); + if !(lo.is_finite() && hi.is_finite()) { + return; + } + let first = (lo - 0.5).ceil().max(0.0); + let last = (hi - 0.5).floor().min(target.height as f64 - 1.0); + if first > last { + return; + } + let mut xs = vec![]; + for row in first as usize..=last as usize { + let y = row as f64 + 0.5; + xs.clear(); + for ring in rings { + for (k, p) in ring.iter().enumerate() { + let Some(q) = ring.get((k + 1) % ring.len()) else { continue }; + if (p[1] <= y) != (q[1] <= y) { + xs.push(p[0] + (y - p[1]) * (q[0] - p[0]) / (q[1] - p[1])); + } + } + } + xs.retain(|x| x.is_finite()); + xs.sort_by(f64::total_cmp); + for &[a, b] in xs.as_chunks::<2>().0 { + self.span(target, row, a, b); + } + } + } +} + +/// The board color `c` as drawn: its RGB, opaque. +fn opaque(c: [u8; 4]) -> [f32; 4] { + [f32::from(c[0]), f32::from(c[1]), f32::from(c[2]), 255.0] +} + +/// The outline rings of `panel` in flat terms (u, v), flattened finely enough for `scale` pixels a +/// point. +fn flat_rings(panel: &Panel, scale: f64) -> Option>> { + let b = panel.outline.bounds()?; + let tolerance = (0.25 / scale).max((b.width() + b.height()) * 1e-5).max(1e-6); + Some(polygon(&panel.outline, tolerance)?.into_iter().map(|r| r.into_iter().map(|p| [p.x, -p.y]).collect()).collect()) +} + +/// `scene` drawn; `None` when the view is not usable (a size of 0, a side over [`MAX_SIDE`], more +/// than [`MAX_PIXELS`] pixels, or a value that is not finite). Panels whose map is not finite, or whose outline has more than +/// [`super::MAX_POLYGON_POINTS`] points, are left out. +pub fn render(scene: &Scene) -> Option { + let camera = scene.camera; + if !camera.usable() { + return None; + } + let (width, height) = (camera.width as usize, camera.height as usize); + let pixels = width * height; + let mut target = + Target { width, height, color: vec![0; pixels * 4], depth: vec![f64::NEG_INFINITY; pixels], rank: vec![0; pixels], panel: vec![0; pixels] }; + let (inside, outside) = (opaque(scene.inside), opaque(scene.outside)); + let near = camera.eye().map(|(eye, _)| eye * NEAREST); + for (rank, &pi) in scene.folded.order.iter().enumerate() { + let (Some(panel), Some(f)) = (scene.blank.panels.get(pi), scene.folded.panels.get(pi)) else { continue }; + let Some(mapped) = map_panel(&camera, f) else { continue }; + let Some(rings) = flat_rings(panel, camera.scale) else { continue }; + let projected: Vec> = rings + .iter() + .map(|r| match near { + Some(near) => clip(r, mapped.forward[2], near), + None => r.clone(), + }) + .filter(|r| r.len() >= 3) + .map(|r| { + r.into_iter() + .filter_map(|[u, v]| { + let [x, y, w] = mul(&mapped.forward, [u, v, 1.0]); + let p = [x / w, y / w]; + (w > 0.0 && p[0].is_finite() && p[1].is_finite()).then_some(p) + }) + .collect::>() + }) + .filter(|r| r.len() >= 3) + .collect(); + let fill = Fill { + mapped: &mapped, + rank: u16::try_from(rank + 1).unwrap_or(u16::MAX), + panel: u16::try_from(pi + 1).unwrap_or(u16::MAX), + print: scene.print, + inside, + outside, + }; + fill.rings(&mut target, &projected); + } + Some(Image { width: camera.width, height: camera.height, pixels: target.color, panels: target.panel }) +} + +#[cfg(test)] +mod tests; diff --git a/crates/three-d/src/fold/raster/tests.rs b/crates/three-d/src/fold/raster/tests.rs new file mode 100644 index 0000000000..8639615a53 --- /dev/null +++ b/crates/three-d/src/fold/raster/tests.rs @@ -0,0 +1,257 @@ +use vectorcraft_geom::{PathData, Point, Rect, SubPath}; + +use super::super::{Blank, Folded, FoldedPanel, Panel, Pose}; +use super::*; + +fn square(x0: f64, y0: f64, x1: f64, y1: f64) -> SubPath { + SubPath::polyline(&[Point::new(x0, y0), Point::new(x1, y0), Point::new(x1, y1), Point::new(x0, y1)], true) +} + +fn panel(subpaths: Vec) -> Panel { + Panel { outline: PathData::new(subpaths), area: 0.0 } +} + +/// A blank of `panels` and a fold that places each at `poses`, in the order given. +fn scene_of(panels: Vec, poses: Vec) -> (Blank, Folded) { + let n = panels.len(); + let folded = Folded { + base: 0, + panels: poses.into_iter().map(|pose| FoldedPanel { pose, parent: None, depth: 0 }).collect(), + order: (0..n).collect(), + hinges: vec![], + collisions: vec![], + }; + (Blank { panels, hinges: vec![], holes: vec![] }, folded) +} + +/// Facing the printed side, 100 × 100 pixels, one pixel a point, the flat square 0..100 filling it. +fn front() -> Camera { + Camera { width: 100, height: 100, rotate_x: 0.0, rotate_y: 0.0, scale: 1.0, pan: [0.0; 2], perspective: 0.0, center: [50.0, -50.0, 0.0] } +} + +fn moved(z: f64) -> Pose { + Pose { t: [0.0, 0.0, z], ..Pose::IDENTITY } +} + +fn pixel(img: &Image, x: u32, y: u32) -> [u8; 4] { + let i = (y * img.width + x) as usize * 4; + [img.pixels[i], img.pixels[i + 1], img.pixels[i + 2], img.pixels[i + 3]] +} + +/// A 2 × 2 print of the square 0..100: red, green on top; blue, white below. +fn quads() -> Print { + let px = [[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [255, 255, 255, 255]]; + Print::new(Rect::new(0.0, 0.0, 100.0, 100.0), 2, 2, px.concat()).expect("a print") +} + +const WHITE: [u8; 4] = [255, 255, 255, 255]; + +#[test] +fn a_flat_panel_takes_the_print_s_color_under_each_pixel() { + let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0)])], vec![Pose::IDENTITY]); + let print = quads(); + let img = render(&Scene { blank: &b, folded: &f, print: Some(&print), inside: [0, 0, 0, 255], outside: WHITE, camera: front() }).expect("drawn"); + let shade = 0.6 + 0.4 * 0.74; + let lit = |c: f64| (c * shade).round() as u8; + assert_eq!(pixel(&img, 5, 5), [lit(255.0), 0, 0, 255], "top left is red"); + assert_eq!(pixel(&img, 94, 5), [0, lit(255.0), 0, 255], "top right is green"); + assert_eq!(pixel(&img, 5, 94), [0, 0, lit(255.0), 255], "bottom left is blue"); + assert_eq!(img.panel_at(50, 50), Some(0)); + // Where the print has no art, the board's printed side shows. + let empty = Print::new(Rect::new(0.0, 0.0, 100.0, 100.0), 1, 1, vec![0; 4]).expect("a print"); + let img = render(&Scene { blank: &b, folded: &f, print: Some(&empty), inside: [0, 0, 0, 255], outside: [200, 100, 50, 255], camera: front() }) + .expect("drawn"); + assert_eq!(pixel(&img, 50, 50), [lit(200.0), lit(100.0), lit(50.0), 255]); +} + +#[test] +fn the_board_is_opaque_whatever_the_alpha_of_its_colors() { + let shade = 0.6 + 0.4 * 0.74; + let lit = |c: f64| (c * shade).round() as u8; + let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0)])], vec![Pose::IDENTITY]); + for a in [0, 128] { + let img = render(&Scene { blank: &b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: [200, 100, 50, a], camera: front() }) + .expect("drawn"); + assert_eq!(pixel(&img, 50, 50), [lit(200.0), lit(100.0), lit(50.0), 255], "outside alpha {a}"); + } + // A transparent inside color draws opaque too, on the nearer of two panels seen from the back. + let whole = || panel(vec![square(0.0, 0.0, 100.0, 100.0)]); + let (b, f) = scene_of(vec![whole(), whole()], vec![Pose::IDENTITY, moved(5.0)]); + let camera = Camera { rotate_y: 180.0, ..front() }; + let img = render(&Scene { blank: &b, folded: &f, print: None, inside: [0, 200, 0, 0], outside: WHITE, camera }).expect("drawn"); + let [r, g, bl, a] = pixel(&img, 50, 50); + assert!(r == 0 && bl == 0 && g > 100 && a == 255, "{:?}", [r, g, bl, a]); +} + +#[test] +fn a_print_squeezed_only_up_and_down_on_screen_samples_a_halved_level() { + // 64 × 64, rows alternating black and white: halved, they average to gray. + let mut px = vec![]; + for y in 0..64 { + for _ in 0..64 { + px.extend(if y % 2 == 0 { [0, 0, 0, 255] } else { [255, 255, 255, 255] }); + } + } + let print = Print::new(Rect::new(0.0, 0.0, 100.0, 100.0), 64, 64, px).expect("a print"); + let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0)])], vec![Pose::IDENTITY]); + // Tipped 80°: about 5.8 points a pixel up and down, 1 across. + let camera = Camera { rotate_x: 80.0, ..front() }; + let img = render(&Scene { blank: &b, folded: &f, print: Some(&print), inside: [0; 4], outside: WHITE, camera }).expect("drawn"); + let reds: Vec = (0..img.height) + .flat_map(|y| (0..img.width).map(move |x| (x, y))) + .filter(|&(x, y)| img.panel_at(x, y).is_some()) + .map(|(x, y)| pixel(&img, x, y)[0]) + .collect(); + assert!(!reds.is_empty()); + let (lo, hi) = (reds.iter().min().copied().unwrap_or(0), reds.iter().max().copied().unwrap_or(0)); + assert!(hi - lo <= 2, "an even gray, not black and white rows: {lo} to {hi}"); +} + +#[test] +fn the_back_of_a_panel_shows_the_inside_color() { + let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0)])], vec![Pose::IDENTITY]); + let print = quads(); + let camera = Camera { rotate_y: 180.0, ..front() }; + let img = render(&Scene { blank: &b, folded: &f, print: Some(&print), inside: [0, 200, 0, 255], outside: WHITE, camera }).expect("drawn"); + let [r, g, bl, a] = pixel(&img, 50, 50); + assert!(r == 0 && bl == 0 && g > 100 && a == 255, "{:?}", [r, g, bl, a]); +} + +#[test] +fn the_nearer_of_two_panels_shows_and_a_tie_goes_to_the_later_one() { + let whole = || panel(vec![square(0.0, 0.0, 100.0, 100.0)]); + let draw = |z: f64| { + let (b, f) = scene_of(vec![whole(), whole()], vec![Pose::IDENTITY, moved(z)]); + render(&Scene { blank: &b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera: front() }).expect("drawn") + }; + assert_eq!(draw(5.0).panel_at(50, 50), Some(1), "panel 1 is in front"); + assert_eq!(draw(-5.0).panel_at(50, 50), Some(0), "panel 1 is behind"); + assert_eq!(draw(0.0).panel_at(50, 50), Some(1), "a tie goes to the panel later in the order"); + // Panels that cross: each shows where it is nearer. + let tilted = Pose { m: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.5, 0.0, 1.0]], t: [0.0, 0.0, -25.0] }; + let (b, f) = scene_of(vec![whole(), whole()], vec![Pose::IDENTITY, tilted]); + let img = render(&Scene { blank: &b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera: front() }).expect("drawn"); + assert_eq!(img.panel_at(20, 50), Some(0), "the tilted panel is behind on the left"); + assert_eq!(img.panel_at(80, 50), Some(1), "and in front on the right"); +} + +#[test] +fn a_hole_in_a_panel_is_left_empty() { + let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0), square(30.0, 30.0, 70.0, 70.0)])], vec![Pose::IDENTITY]); + let img = render(&Scene { blank: &b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera: front() }).expect("drawn"); + assert_eq!(img.panel_at(50, 50), None); + assert_eq!(pixel(&img, 50, 50), [0; 4]); + assert_eq!(img.panel_at(10, 50), Some(0)); +} + +#[test] +fn a_panel_past_the_eye_at_a_wide_perspective_is_cut_at_the_near_plane() { + // A long panel standing out of the page toward the viewer, through the eye. + let toward = Pose { m: [[1.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 1.0, 0.0]], t: [0.0, -50.0, 0.0] }; + let (b, f) = scene_of(vec![panel(vec![square(0.0, -1000.0, 100.0, 1000.0)])], vec![toward]); + for perspective in [1.0, 60.0, 160.0, 179.0] { + let camera = Camera { perspective, scale: 8.0, rotate_x: 30.0, ..front() }; + let img = render(&Scene { blank: &b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + let drawn = img.panels.iter().filter(|&&p| p != 0).count(); + assert!(drawn > 0, "{perspective}°: some of it shows"); + assert_eq!(img.pixels.len(), 100 * 100 * 4); + } +} + +#[test] +fn unusable_views_and_prints_are_refused() { + let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0)])], vec![Pose::IDENTITY]); + for camera in [ + Camera { width: 0, ..front() }, + Camera { height: MAX_SIDE + 1, ..front() }, + Camera { width: MAX_SIDE, height: MAX_PIXELS / MAX_SIDE + 1, ..front() }, + Camera { scale: 0.0, ..front() }, + Camera { rotate_x: f64::NAN, ..front() }, + Camera { center: [f64::INFINITY, 0.0, 0.0], ..front() }, + ] { + assert!(render(&Scene { blank: &b, folded: &f, print: None, inside: [0; 4], outside: WHITE, camera }).is_none(), "{camera:?}"); + } + let region = Rect::new(0.0, 0.0, 10.0, 10.0); + assert!(Print::new(region, 2, 2, vec![0; 15]).is_none(), "too few bytes"); + assert!(Print::new(region, 0, 2, vec![]).is_none()); + assert!(Print::new(region, MAX_SIDE + 1, 1, vec![0; (MAX_SIDE as usize + 1) * 4]).is_none()); + assert!(Print::new(Rect::new(0.0, 0.0, 0.0, 10.0), 1, 1, vec![0; 4]).is_none(), "an empty region"); + let p = Print::new(region, 8, 4, vec![255; 8 * 4 * 4]).expect("a print"); + assert_eq!(p.levels.iter().map(|l| (l.width, l.height)).collect::>(), vec![(8, 4), (4, 2), (2, 1), (1, 1)]); +} + +#[test] +fn halving_an_odd_sized_print_keeps_its_last_row_and_column() { + // 3 × 3, transparent but for an opaque white last column and last row. + let mut px = vec![0u8; 3 * 3 * 4]; + for i in [2, 5, 6, 7, 8] { + px[i * 4..i * 4 + 4].copy_from_slice(&[255; 4]); + } + let p = Print::new(Rect::new(0.0, 0.0, 30.0, 30.0), 3, 3, px).expect("a print"); + let half = &p.levels[1]; + assert_eq!((half.width, half.height), (2, 2)); + // The bottom right pixel of the half level covers only the corner pixel. + assert_eq!(&half.pixels[12..16], &[255; 4]); + assert_eq!(&half.pixels[0..4], &[0; 4], "the top left covers four transparent pixels"); +} + +#[test] +fn a_print_far_smaller_on_screen_samples_a_halved_level() { + // Columns alternate black and white: halved, they average to gray. + let mut px = vec![]; + for _ in 0..4 { + for x in 0..4 { + px.extend(if x % 2 == 0 { [0, 0, 0, 255] } else { [255, 255, 255, 255] }); + } + } + let print = Print::new(Rect::new(0.0, 0.0, 100.0, 100.0), 4, 4, px).expect("a print"); + let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0)])], vec![Pose::IDENTITY]); + // 100 points in 2 pixels: 2 print pixels a view pixel. + let camera = Camera { width: 2, height: 2, scale: 0.02, ..front() }; + let img = render(&Scene { blank: &b, folded: &f, print: Some(&print), inside: [0; 4], outside: WHITE, camera }).expect("drawn"); + let [r, ..] = pixel(&img, 0, 0); + assert!((80..=150).contains(&r), "gray, not a black or white column: {r}"); +} + +#[test] +fn a_print_sixteen_times_smaller_on_screen_samples_a_level_halved_four_times() { + // 64 × 64, columns in bands of 4 alternating black and white: halved twice, they still alternate; + // halved four times, they average to gray. + let mut px = vec![]; + for _ in 0..64 { + for x in 0..64 { + px.extend(if (x / 4) % 2 == 0 { [0, 0, 0, 255] } else { [255, 255, 255, 255] }); + } + } + let print = Print::new(Rect::new(0.0, 0.0, 100.0, 100.0), 64, 64, px).expect("a print"); + assert_eq!(print.levels.len(), 7, "64 down to 1"); + let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0)])], vec![Pose::IDENTITY]); + // 100 points in 3 pixels: about 21 print pixels a view pixel. + let camera = Camera { width: 3, height: 3, scale: 0.03, ..front() }; + let img = render(&Scene { blank: &b, folded: &f, print: Some(&print), inside: [0; 4], outside: WHITE, camera }).expect("drawn"); + let [r, ..] = pixel(&img, 0, 1); + assert!((90..=140).contains(&r), "gray, not a black or white band: {r}"); +} + +#[test] +fn a_halved_level_weighs_an_odd_last_column_by_the_area_it_covers() { + // 9 × 9, black but for a white last column: a ninth of the print, so the one-pixel level is + // a ninth white (255 / 9 is about 28), not half. + let mut px = vec![]; + for _ in 0..9 { + for x in 0..9 { + px.extend(if x == 8 { [255, 255, 255, 255] } else { [0, 0, 0, 255] }); + } + } + let print = Print::new(Rect::new(0.0, 0.0, 100.0, 100.0), 9, 9, px).expect("a print"); + assert_eq!(print.levels.iter().map(|l| (l.width, l.height)).collect::>(), vec![(9, 9), (5, 5), (3, 3), (2, 2), (1, 1)]); + assert_eq!(print.levels.last().map(|l| l.pixels.clone()), Some(vec![28, 28, 28, 255])); +} + +#[test] +fn the_bounds_take_in_every_folded_panel() { + let (b, f) = + scene_of(vec![panel(vec![square(0.0, 0.0, 10.0, 10.0)]), panel(vec![square(0.0, 0.0, 10.0, 10.0)])], vec![Pose::IDENTITY, moved(-7.0)]); + let (lo, hi) = bounds(&b, &f).expect("bounds"); + assert_eq!((lo, hi), ([0.0, -10.0, -7.0], [10.0, 0.0, 0.0])); +} diff --git a/crates/three-d/src/fold/tests.rs b/crates/three-d/src/fold/tests.rs index ef014300c0..8031a0b2a1 100644 --- a/crates/three-d/src/fold/tests.rs +++ b/crates/three-d/src/fold/tests.rs @@ -913,4 +913,323 @@ proptest! { sorted.sort_by_key(|i| i.code); prop_assert_eq!(sorted, issues); } + + /// Random fold lines fold at any amount without a panic, every pose finite and every panel + /// keeping its shape. + #[test] + fn random_blanks_fold_to_finite_poses( + segs in proptest::collection::vec((1u8..4, -50.0f64..50.0, -50.0f64..50.0, -50.0f64..50.0, -50.0f64..50.0), 1..8), + amount in 0.0f64..=1.0, + ) { + let kinds = [LineKind::Cut, LineKind::Crease, LineKind::PartialCut, LineKind::Perforation]; + let mut lines: Vec = segs + .iter() + .enumerate() + .map(|(i, &(k, a, b, c, d))| line(kinds[usize::from(k)], &[(a, b), (c, d)], false, i as u64)) + .collect(); + lines.push(cut(&[(-40.0, -40.0), (40.0, -40.0), (40.0, 40.0), (-40.0, 40.0)], 99)); + let (blanks, _) = blanks(&lines, TOL); + for b in &blanks { + let Some(f) = fold(b, None, amount, TOL) else { continue }; + prop_assert_eq!(f.panels.len(), b.panels.len()); + prop_assert_eq!(f.order.len(), b.panels.len()); + for p in &f.panels { + prop_assert!(p.pose.m.iter().flatten().chain(&p.pose.t).all(|v| v.is_finite())); + let n = p.pose.normal(); + prop_assert!((n[0] * n[0] + n[1] * n[1] + n[2] * n[2] - 1.0).abs() < 1e-9); + } + } + } +} + +/// The 3D corners of panel `i` of `b` folded as `f` places them. +fn corners(b: &Blank, f: &Folded, i: usize) -> Vec<[f64; 3]> { + let rings = polygon(&b.panels[i].outline, 0.01).expect("a polygon"); + rings.into_iter().flatten().map(|p| f.panels[i].pose.place(p)).collect() +} + +fn flat_center(b: &Blank, i: usize) -> [f64; 3] { + let c = point_in(&b.panels[i].outline).expect("a point inside"); + [c.x, -c.y, 0.0] +} + +#[test] +fn a_slotted_box_folds_every_panel_onto_a_face_of_the_box_with_the_print_outside() { + let (b, issues) = check(¬ched_box()); + assert!(issues.is_empty(), "{issues:?}"); + let b = &b[0]; + let f = fold(b, None, 1.0, TOL).expect("folds"); + // The base panel is the leftmost of the two largest body panels: x 20 to 120, y 30 to 110. + let base = &b.panels[f.base]; + assert_eq!(base.outline.bounds().map(|r| (r.x0.round(), r.y0.round())), Some((20.0, 30.0))); + // The box: the base panel's face (z = 0), 60 deep (the narrow body panels' width). + let (lo, hi) = ([20.0, -110.0, -60.0], [120.0, -30.0, 0.0]); + let middle = [70.0, -70.0, -30.0]; + for i in 0..b.panels.len() { + let points = corners(b, &f, i); + let face = (0..3).find_map(|k| [lo[k], hi[k]].into_iter().find(|&at| points.iter().all(|p| (p[k] - at).abs() < 1e-6)).map(|at| (k, at))); + let (k, at) = face.unwrap_or_else(|| panic!("panel {i} lies on no face of the box: {points:?}")); + for p in &points { + for j in 0..3 { + assert!(p[j] > lo[j] - 1e-6 && p[j] < hi[j] + 1e-6, "panel {i} reaches out of the box: {p:?}"); + } + } + // The printed side faces out of the box. + let n = f.panels[i].pose.normal(); + assert!((n[k].abs() - 1.0).abs() < 1e-9, "panel {i} is square to its face: {n:?}"); + assert!(n[k] * (at - middle[k]) > 0.0, "panel {i}'s print faces out: {n:?}"); + } + assert!(f.hinges.iter().all(|h| h.tree && h.closes && (h.angle - 90.0).abs() < 1e-12), "{:?}", f.hinges); + assert!(f.collisions.is_empty(), "the stacked flaps and the glue flap do not cross: {:?}", f.collisions); + assert_eq!(f.order.first(), Some(&f.base)); + assert_eq!(f.order.len(), 13); +} + +#[test] +fn at_amount_0_the_blank_is_flat() { + let (b, _) = check(¬ched_box()); + let f = fold(&b[0], None, 0.0, TOL).expect("folds"); + for p in &f.panels { + for (row, want) in p.pose.m.iter().zip(Pose::IDENTITY.m) { + assert!(row.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-12), "{:?}", p.pose); + } + assert!(p.pose.t.iter().all(|v| v.abs() < 1e-9), "{:?}", p.pose); + } +} + +/// A 100 × 60 rectangle split by a line of `kind` at x = 60 (drawn upward when `up`), turned by +/// `quarter` quarter turns about the origin and mirrored in x when `mirror`. +fn two_panels(kind: LineKind, quarter: u8, mirror: bool, up: bool) -> Vec { + let at = |(x, y): (f64, f64)| { + let x = if mirror { -x } else { x }; + (0..quarter).fold((x, y), |(x, y), _| (-y, x)) + }; + let outline: Vec<(f64, f64)> = [(0.0, 0.0), (100.0, 0.0), (100.0, 60.0), (0.0, 60.0)].into_iter().map(at).collect(); + let (a, b) = if up { ((60.0, 60.0), (60.0, 0.0)) } else { ((60.0, 0.0), (60.0, 60.0)) }; + vec![cut(&outline, 1), line(kind, &[at(a), at(b)], false, 2)] +} + +#[test] +fn a_crease_folds_away_from_the_print_and_a_partial_cut_toward_it_however_it_is_drawn() { + for quarter in 0..4 { + for mirror in [false, true] { + for up in [false, true] { + for (kind, sign) in [(LineKind::Crease, -1.0), (LineKind::Perforation, -1.0), (LineKind::PartialCut, 1.0)] { + let case = format!("{kind:?}, {quarter} quarter turns, mirrored {mirror}, drawn up {up}"); + let (b, issues) = check(&two_panels(kind, quarter, mirror, up)); + assert!(issues.is_empty(), "{case}: {issues:?}"); + let b = &b[0]; + let f = fold(b, None, 1.0, TOL).expect("folds"); + let child = 1 - f.base; + let h = &b.hinges[0]; + let hinge = [(h.from.x + h.to.x) / 2.0, -(h.from.y + h.to.y) / 2.0, 0.0]; + let c = flat_center(b, child); + let away = [c[0] - hinge[0], c[1] - hinge[1], 0.0]; + let along = [h.to.x - h.from.x, h.from.y - h.to.y]; + let off_line = (along[0] * away[1] - along[1] * away[0]).abs() / along[0].hypot(along[1]); + let placed = f.panels[child].pose.apply(c); + // The child stands up out of the plane: behind it for a crease, in front of it + // for a partial cut, at its distance from the hinge. + assert!(placed[2] * sign > 0.0, "{case}: {placed:?}"); + assert!((placed[2].abs() - off_line).abs() < 1e-6, "{case}: {placed:?} {off_line}"); + // Its printed side faces away from the base panel after a crease, back toward + // it after a partial cut. + let n = f.panels[child].pose.normal(); + assert!((n[0] * away[0] + n[1] * away[1]) * -sign > 0.0, "{case}: {n:?}"); + // Half way, the child is half way round. + let half = fold(b, None, 0.5, TOL).expect("folds"); + let z = half.panels[child].pose.normal()[2]; + assert!((z - std::f64::consts::FRAC_1_SQRT_2).abs() < 1e-9, "{case}: {z}"); + } + } + } + } +} + +/// A 100 × 100 square divided into four panels by a crease across it each way. +fn crossed() -> Vec { + vec![ + cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], 1), + crease((50.0, 0.0), (50.0, 100.0), 2), + crease((0.0, 50.0), (100.0, 50.0), 3), + ] +} + +#[test] +fn a_loop_of_hinges_closes_when_flat_and_reports_its_gap_when_folded() { + let (b, issues) = check(&crossed()); + assert!(issues.is_empty(), "{issues:?}"); + let b = &b[0]; + assert_eq!((b.panels.len(), b.hinges.len()), (4, 4)); + let folded = fold(b, None, 1.0, TOL).expect("folds"); + let closing: Vec<&FoldedHinge> = folded.hinges.iter().filter(|h| !h.tree).collect(); + assert_eq!(closing.len(), 1, "three hinges make the tree, one closes the loop"); + assert!(!closing[0].closes && closing[0].gap > 10.0, "{closing:?}"); + // The gap is measured folded all the way, whatever the amount: flat or half way, the loop is + // still reported open by the same gap. + for amount in [0.0, 0.5] { + let part = fold(b, None, amount, TOL).expect("folds"); + let h = part.hinges.iter().find(|h| !h.tree).expect("a closing hinge"); + assert!(!h.closes && (h.gap - closing[0].gap).abs() < 1e-9, "{amount}: {h:?}"); + } + // The base is the top-left panel: four equal panels tie, and the highest, then leftmost, wins. + assert_eq!(b.panels[folded.base].outline.bounds().map(|r| (r.x0.round(), r.y0.round())), Some((0.0, 0.0))); +} + +#[test] +fn hinges_that_start_at_one_point_fold_the_same_in_any_line_order() { + // About the bottom-right panel, its two hinges both start at the middle of the square. + let lines = crossed(); + let orders = [[0, 1, 2], [0, 2, 1], [2, 1, 0], [1, 2, 0], [1, 0, 2], [2, 0, 1]]; + let mut seen = None; + for order in orders { + let lines: Vec = order.iter().map(|&i| lines[i].clone()).collect(); + let (b, issues) = check(&lines); + assert!(issues.is_empty(), "{order:?}: {issues:?}"); + let b = &b[0]; + let base = panel_at(b, p(75.0, 75.0)).expect("the bottom-right panel"); + let f = fold(b, Some(base), 1.0, TOL).expect("folds"); + let closing = f.hinges.iter().zip(&b.hinges).find(|(h, _)| !h.tree).map(|(_, h)| ((h.from.x + h.to.x) / 2.0, (h.from.y + h.to.y) / 2.0)); + let top_left = panel_at(b, p(25.0, 25.0)).expect("the top-left panel"); + let placed = f.panels[top_left].pose.place(p(25.0, 25.0)).map(|v| (v * 1e6).round()); + let got = (closing, placed); + assert_eq!(seen.get_or_insert(got), &got, "{order:?}"); + } +} + +/// A 100 × 60 rectangle: the left 60 pt is one panel, the right is split across at y = 30, and the +/// line between them bends by `lean` pt over its lower half. +fn leaning(lean: f64) -> Vec { + vec![ + cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 60.0), (0.0, 60.0)], 1), + crease((60.0, 0.0), (60.0, 30.0), 2), + crease((60.0, 30.0), (60.0 + lean, 60.0), 3), + crease((60.0, 30.0), (100.0, 30.0), 4), + ] +} + +#[test] +fn a_loop_closes_within_the_tolerance_or_half_a_percent_of_its_hinge() { + // Both right panels turn about one line, so the hinge between them closes exactly. + let gap = |lean: f64, amount: f64| { + let (b, issues) = check(&leaning(lean)); + assert!(issues.is_empty(), "{lean}: {issues:?}"); + let b = &b[0]; + assert_eq!((b.panels.len(), b.hinges.len()), (3, 3)); + let base = panel_at(b, p(30.0, 30.0)).expect("the left panel"); + let f = fold(b, Some(base), amount, TOL).expect("folds"); + let h = f.hinges.iter().find(|h| !h.tree).expect("a closing hinge").clone(); + (h.closes, h.gap) + }; + let (closes, at) = gap(0.0, 1.0); + assert!(closes && at < 1e-9, "{at}"); + // A small lean opens it by more than the 0.1 pt tolerance but less than 0.5% of its 40 pt + // length (0.2 pt): still closed. + let (closes, at) = gap(0.1, 1.0); + assert!(closes && at > TOL && at <= 0.2, "{at}"); + // A larger lean opens it past both, flat or folded. + for amount in [0.0, 1.0] { + let (closes, at) = gap(1.0, amount); + assert!(!closes && at > 0.2, "{amount}: {at}"); + } +} + +#[test] +fn a_panel_no_hinge_joins_stays_flat_where_it_is() { + let lines = vec![ + cut(&[(0.0, 0.0), (50.0, 0.0), (50.0, 49.95), (100.0, 49.95), (100.0, 99.95), (50.0, 99.95), (50.0, 50.0), (0.0, 50.0)], 1), + crease((50.0, 49.95), (50.0, 50.0), 2), + ]; + let (b, _) = check(&lines); + let b = &b[0]; + assert_eq!((b.panels.len(), b.hinges.len()), (2, 0)); + let f = fold(b, None, 1.0, TOL).expect("folds"); + let loose = 1 - f.base; + assert_eq!(f.panels[loose].parent, None); + assert_eq!(f.panels[loose].pose, Pose::IDENTITY); + assert_eq!(f.order, vec![f.base, loose], "the loose panel comes last"); +} + +#[test] +fn a_child_of_a_notched_panel_folds_away_from_the_print() { + // The base is an L: a 30 × 140 strip with an 80 pt arm along its top running right to x = 300. + // The child, below the arm past a 2 pt slot, is hinged to the strip along x = 30. + let lines = vec![ + cut(&[(0.0, 0.0), (300.0, 0.0), (300.0, 80.0), (30.0, 80.0), (30.0, 82.0), (300.0, 82.0), (300.0, 140.0), (0.0, 140.0)], 1), + crease((30.0, 82.0), (30.0, 140.0), 2), + ]; + let (b, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); + let b = &b[0]; + let base = panel_at(b, p(15.0, 110.0)).expect("the L"); + let child = panel_at(b, p(150.0, 110.0)).expect("the child"); + // The L's inside point lies in its arm, on the child's side of the hinge's line. + let inside = b.panels[base].point_inside().expect("a point inside"); + assert!(inside.x > 30.0, "{inside:?}"); + for (kind, sign) in [(LineKind::Crease, -1.0), (LineKind::PartialCut, 1.0)] { + let mut lines = lines.clone(); + lines[1].kind = kind; + let (b, _) = check(&lines); + let f = fold(&b[0], Some(base), 1.0, TOL).expect("folds"); + let placed = f.panels[child].pose.place(p(150.0, 110.0)); + assert!(placed[2] * sign > 99.0, "{kind:?}: {placed:?}"); + } +} + +#[test] +fn a_lid_folded_over_the_base_crosses_the_taller_wall_opposite() { + // A strip: a 120 pt lid, a 30 pt wall, the 100 pt base and a 60 pt wall, all 50 pt deep. + let lines = vec![ + cut(&[(0.0, 0.0), (310.0, 0.0), (310.0, 50.0), (0.0, 50.0)], 1), + crease((120.0, 0.0), (120.0, 50.0), 2), + crease((150.0, 0.0), (150.0, 50.0), 3), + crease((250.0, 0.0), (250.0, 50.0), 4), + ]; + let (b, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); + let b = &b[0]; + let base = panel_at(b, p(200.0, 25.0)).expect("the base panel"); + let (lid, wall) = (panel_at(b, p(60.0, 25.0)).unwrap(), panel_at(b, p(280.0, 25.0)).unwrap()); + let f = fold(b, Some(base), 1.0, TOL).expect("folds"); + assert_eq!(f.collisions, vec![(lid.min(wall), lid.max(wall))]); + // Half folded, nothing crosses yet. + assert!(fold(b, Some(base), 0.4, TOL).expect("folds").collisions.is_empty()); +} + +#[test] +fn the_base_is_the_panel_under_a_point_and_the_same_in_any_input_order() { + let lines = vec![cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 60.0), (0.0, 60.0)], 1), crease((50.0, 0.0), (50.0, 60.0), 2)]; + let (b, _) = check(&lines); + assert_eq!(panel_at(&b[0], p(500.0, 500.0)), None, "a point outside every panel"); + let right = panel_at(&b[0], p(75.0, 30.0)).expect("the right panel"); + assert_eq!(fold(&b[0], Some(right), 1.0, TOL).expect("folds").base, right); + let mut reversed = lines.clone(); + reversed.reverse(); + let (r, _) = check(&reversed); + for blank in [&b[0], &r[0]] { + let f = fold(blank, None, 1.0, TOL).expect("folds"); + // Equal panels: the leftmost wins. + assert_eq!(blank.panels[f.base].outline.bounds().map(|r| r.x0.round()), Some(0.0)); + } + assert!(fold(&b[0], Some(9), 1.0, TOL).is_none(), "no panel 9"); + assert!(fold(&b[0], None, 1.5, TOL).is_none(), "past 1"); + assert!(fold(&b[0], None, f64::NAN, TOL).is_none()); + assert!(fold(&Blank::default(), None, 1.0, TOL).is_none(), "no panels"); +} + +#[test] +fn a_partial_cut_takes_its_own_angle_and_a_hinge_its_longest_piece_s() { + let (b, _) = check(&two_panels(LineKind::PartialCut, 0, false, false)); + assert_eq!(b[0].hinges[0].angle, -90.0); + let (b, _) = check(&two_panels(LineKind::Perforation, 0, false, false)); + assert_eq!(b[0].hinges[0].angle, 90.0); + // A crease and a short partial cut on one line: the crease is the longer piece. + let lines = vec![ + cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 60.0), (0.0, 60.0)], 1), + line(LineKind::PartialCut, &[(60.0, 0.0), (60.0, 10.0)], false, 2), + crease((60.0, 10.0), (60.0, 60.0), 3), + ]; + let (b, _) = check(&lines); + assert_eq!(b[0].hinges.len(), 1); + assert_eq!(b[0].hinges[0].angle, 90.0); } diff --git a/crates/three-d/src/lib.rs b/crates/three-d/src/lib.rs index 18d371b420..c6b00ed851 100644 --- a/crates/three-d/src/lib.rs +++ b/crates/three-d/src/lib.rs @@ -13,7 +13,7 @@ mod solid; mod visibility; pub use solid::{ Bevel, BevelShape, DepthPlane, Extrude, FaceMap, Facet, Inflate, MeshFace, PlanarFace, TOO_COMPLEX_SOLID, View, extrude, extrude_face_map, - extrude_mesh_face, inflate, inflate_each, inflate_together, plane, plane_face_map, plane_mesh_face, + extrude_mesh_face, extrude_side_size, inflate, inflate_each, inflate_together, plane, plane_face_map, plane_mesh_face, }; pub use visibility::{VisibleFace, visible_faces}; mod shading; @@ -389,7 +389,9 @@ pub struct Face { pub plane: Option, } -/// Where a face of Revolve's swept side lies on the side surface, unrolled flat: x runs around the +/// Where a face of a side surface lies on it unrolled flat, for the graphics mapped onto it. On +/// Extrude & Bevel's side ([`Facet::surface`]) x runs along the outline and y from the front toward +/// the back. On Revolve's swept side x runs around the /// axis and y along the profile, in points. x is the angle from the middle of the surface times the /// point's own distance from the axis, so a graphic keeps its size at every distance and wraps /// farther around the axis where the profile comes closer to it. y is the length along the profile diff --git a/crates/three-d/src/solid.rs b/crates/three-d/src/solid.rs index cc8881d2d9..5029a79910 100644 --- a/crates/three-d/src/solid.rs +++ b/crates/three-d/src/solid.rs @@ -19,6 +19,7 @@ mod inflate; mod membrane; mod outline; mod rings; +mod side; #[cfg(test)] pub(crate) use build::EXTRUDED; @@ -27,7 +28,7 @@ pub(crate) use build::PLANES; #[cfg(test)] use build::{Camera, cuts, edge_distance, newell, section}; pub(crate) use build::{Face3, Keep, extrude_faces, plane_faces}; -pub use build::{extrude, plane}; +pub use build::{extrude, extrude_side_size, plane}; pub use face_map::{FaceMap, MeshFace, extrude_face_map, extrude_mesh_face, plane_face_map, plane_mesh_face}; #[cfg(test)] use inflate::GRID_WORK; @@ -218,11 +219,14 @@ pub struct Extrude { /// Keep the faces of a closed solid that are turned away from the viewer (Draw Hidden Faces, /// and the classic Wireframe surface), drawn behind the faces turned toward it. pub hidden: bool, + /// Graphics are mapped onto the side: the pieces of the walls and bevels of the solid's longest + /// contour carry a [`Facet::surface`]. Off by default, which leaves the facets without one. + pub map_surface: bool, } impl Default for Extrude { fn default() -> Self { - Self { depth: 50.0, twist: 0.0, taper: 1.0, cap: true, bevel: None, hidden: false } + Self { depth: 50.0, twist: 0.0, taper: 1.0, cap: true, bevel: None, hidden: false, map_surface: false } } } @@ -249,21 +253,24 @@ impl Default for Inflate { } } -/// A planar face of a solid that a graphic can be mapped onto: Extrude & Bevel's front cap (the -/// art itself, or a plane's only face) or its back cap. +/// A face of a solid that a graphic can be mapped onto: Extrude & Bevel's front cap (the art itself, +/// or a plane's only face), its back cap, or its side (the walls and bevels, unrolled flat: +/// [`Facet::surface`]). Only the caps are planar. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum PlanarFace { Front, Back, + Side, } impl PlanarFace { - pub const ALL: [PlanarFace; 2] = [Self::Front, Self::Back]; + pub const ALL: [PlanarFace; 3] = [Self::Front, Self::Back, Self::Side]; pub fn id(self) -> &'static str { match self { Self::Front => "front", Self::Back => "back", + Self::Side => "side", } } @@ -296,6 +303,10 @@ pub struct Facet { /// The planar end of the solid the facet is: Extrude & Bevel's front or back cap, or a plane /// (its front). `None` for every other facet. pub end: Option, + /// For a piece of Extrude & Bevel's side built for graphics ([`Extrude::map_surface`]): where + /// its corners lie on the side unrolled flat, for a graphic mapped onto it. x runs along the + /// outline and y from the front toward the back ([`crate::SurfaceCell`]). + pub surface: Option, /// The face's plane in view space and the projection it was drawn with, for its depth at a /// point of the drawing ([`Facet::depth_at`]). `None` for a face whose corners lie more than /// 0.001 pt off one plane (a piece of a twisted wall) or reach the eye. @@ -384,6 +395,8 @@ impl Facet { // A revolved cap is not one of the planar faces graphics map onto. end: None, away: false, + // Revolve's graphics are drawn from its faces, before they become facets. + surface: None, plane: face.plane, #[cfg(test)] view: vec![], diff --git a/crates/three-d/src/solid/build.rs b/crates/three-d/src/solid/build.rs index d734161343..29d5debcc3 100644 --- a/crates/three-d/src/solid/build.rs +++ b/crates/three-d/src/solid/build.rs @@ -5,6 +5,7 @@ use super::rings::{ CURVE_PIECES, MAX_PIECES, MAX_PLANE_POINTS, MAX_SOLID_POINTS, Ring, Span, TOO_COMPLEX_SURFACE, curve_pieces, inset, left, signed_area, solid_rings_traced, square_corners, }; +use super::side; use super::{ Bevel, DepthPlane, Extrude, Facet, FillRule, MAX_FACES, MAX_SOLID_FACES, ParamCurve, PathData, PlanarFace, Point, Rect, Revolve, V3, View, eye_distance, perspective_scale, @@ -211,6 +212,7 @@ impl<'a> Builder<'a> { side: false, away: behind, end: None, + surface: None, plane, #[cfg(test)] view, @@ -249,11 +251,13 @@ impl<'a> Builder<'a> { /// wall with `cuts` (see [`cuts`]) as `cuts[i]` quads along edge `i`. `outward` is the /// direction (before rotation) the band faces away from the solid, for orienting normals. pub(super) fn band(&mut self, a: &[V3], b: &[V3], cuts: &[usize], outward: impl Fn(usize) -> V3) -> Result<(), String> { - self.curved_band(a, b, cuts, outward, None) + self.curved_band(a, b, cuts, outward, None, None) } /// [`Builder::band`], with `curves` the pieces of curve the rings' edges follow and the /// outlines at `a` and `b`: a quad whose edge is not cut keeps its edges along the profile curved. + /// With `side`, each quad carries where its corners lie on the side unrolled flat + /// ([`Facet::surface`]). pub(super) fn curved_band( &mut self, a: &[V3], @@ -261,6 +265,7 @@ impl<'a> Builder<'a> { cuts: &[usize], outward: impl Fn(usize) -> V3, mut curves: Option, + side: Option, ) -> Result<(), String> { let n = a.len().min(b.len()); // At 0 and 1, the corners themselves. @@ -295,6 +300,21 @@ impl<'a> Builder<'a> { && let Some(f) = self.facets.last_mut() { f.side = true; + if let Some(s) = side.as_ref() + && let (Some([x0, x1]), Some(page)) = (s.x.get(i).copied(), f.contours.first()) + { + let (u0, u1) = (x0 + (x1 - x0) * s0, x0 + (x1 - x0) * s1); + let [y0, y1] = s.y; + // The face shows the side's outside when it was neither turned around to + // show its inside (on a hollow solid) nor kept turned away. + let n = normal.unit(); + let outward = !f.away && f.normal[0] * n.0 + f.normal[1] * n.1 + f.normal[2] * n.2 > 0.0; + f.surface = Some(crate::SurfaceCell { + page: page.clone(), + uv: vec![Point::new(u0, y0), Point::new(u1, y0), Point::new(u1, y1), Point::new(u0, y1)], + outward, + }); + } } if let Some(w) = curves.as_mut().filter(|_| pieces == 1) && let Some(span) = w.spans.get(i).copied().flatten() @@ -353,6 +373,13 @@ pub(super) struct WallCurves<'a> { pub(super) budget: &'a mut Budget, } +/// Where a band of the side lies on the side unrolled flat ([`super::side`]): the x of each end of +/// each edge of its rings, and the y of its two rings. +pub(super) struct SideBand<'a> { + pub(super) x: &'a [[f64; 2]], + pub(super) y: [f64; 2], +} + /// Where a point of the art goes in view space at one step: [`Camera::place`] after a [`Turn`], /// at depth `z`, as one affine map worked out once for the step. pub(super) struct Placing { @@ -667,7 +694,17 @@ pub(crate) fn extrude_faces(path: &PathData, rule: FillRule, bounds: Rect, optio }) .collect(); let mut budget = Budget::default(); - for ((ring, traced), pieces) in rings.iter().zip(&traced).zip(&pieces) { + // With graphics on the side, the longest contour's pieces carry where they lie on it unrolled. + let unrolled = o + .map_surface + .then(|| { + let k = side::longest(&rings)?; + let y = side::across_steps(&steps.iter().map(|s| (s.inset, s.t)).collect::>(), o.depth); + Some((k, side::along_ring(rings.get(k)?)?, y)) + }) + .flatten(); + for (r, ((ring, traced), pieces)) in rings.iter().zip(&traced).zip(&pieces).enumerate() { + let unrolled = unrolled.as_ref().filter(|(k, ..)| *k == r); let placed: Vec> = steps.iter().map(|s| ring_at(ring, s)).collect(); for (k, pair) in placed.windows(2).enumerate() { let ([a, c], Some(s0), Some(s1)) = (pair, steps.get(k), steps.get(k + 1)) else { continue }; @@ -684,7 +721,8 @@ pub(crate) fn extrude_faces(path: &PathData, rule: FillRule, bounds: Rect, optio // stay straight, within the sampling tolerance. let (near, far) = (along.get(k).filter(|_| k == 0), along.get(k + 1).filter(|_| k + 2 == steps.len())); let curves = (near.is_some() || far.is_some()).then(|| WallCurves { spans: &traced.spans, near, far, budget: &mut budget }); - b.curved_band(a, c, pieces, |i| outward(ring, i, face), curves)?; + let side = unrolled.and_then(|(_, x, y)| Some(SideBand { x, y: [*y.get(k)?, *y.get(k + 1)?] })); + b.curved_band(a, c, pieces, |i| outward(ring, i, face), curves, side)?; } } if o.cap { @@ -705,6 +743,31 @@ pub(crate) fn extrude_faces(path: &PathData, rule: FillRule, bounds: Rect, optio Ok(b.finish()) } +/// The size of Extrude & Bevel's side unrolled flat ([`super::side`]), for a solid of `path` built +/// as [`extrude`] builds it: the length of its longest contour's outline, the length across its +/// bevels and walls, front to back, and the width about x = 0 that does not reach the side's cut. +/// `None` with a depth of 0, for invalid bounds, and for a shape [`extrude`] refuses. +pub fn extrude_side_size(path: &PathData, rule: FillRule, bounds: Rect, options: Extrude) -> Option<(f64, f64, f64)> { + check_bounds(bounds).ok()?; + let o = options.sanitized(); + if o.depth <= 0.0 { + return None; + } + let steps = steps(&o); + let (bands, caps) = (steps.len().saturating_sub(1), if o.cap { 2 } else { 0 }); + let size = bounds.width().max(bounds.height()); + let most = curve_pieces(path, size, bands, caps).ok()?; + let side = steps.iter().map(|s| s.inset).find(|w| *w != 0.0).unwrap_or(0.0); + let traced: Vec = solid_rings_traced(path, rule, size, MAX_SOLID_POINTS, most).ok()?.iter().map(|r| square_corners(r, side)).collect(); + let rings: Vec<&[Point]> = traced.iter().map(|r| r.points.as_slice()).collect(); + // A solid past the face limit is refused, as [`extrude_faces`] refuses it. + let edges = rings.iter().map(|r| r.len()).fold(0usize, usize::saturating_add); + if edges.saturating_mul(bands).saturating_add(caps) > MAX_SOLID_FACES { + return None; + } + side::size(&rings, &steps.iter().map(|s| (s.inset, s.t)).collect::>(), o.depth) +} + #[cfg(test)] thread_local! { /// How many Rotate planes (and Extrude & Bevel solids with no depth) this thread has built, for diff --git a/crates/three-d/src/solid/face_map.rs b/crates/three-d/src/solid/face_map.rs index ac99348ba3..51a6709df0 100644 --- a/crates/three-d/src/solid/face_map.rs +++ b/crates/three-d/src/solid/face_map.rs @@ -145,7 +145,8 @@ impl FaceMap { /// The map of Extrude & Bevel's cap `face` for a solid built with `bounds`, `options` and `view`, /// as [`super::extrude`] builds it. With a depth of 0 the art is a plane, whose only face is the -/// front. `None` for a hollow solid (no caps), for the back of a plane, and for invalid bounds. +/// front. `None` for a hollow solid (no caps), for the back of a plane, for the side (which is not +/// planar), and for invalid bounds. pub fn extrude_face_map(bounds: Rect, options: Extrude, view: View, face: PlanarFace) -> Option { check_bounds(bounds).ok()?; let o = options.sanitized(); @@ -159,6 +160,7 @@ pub fn extrude_face_map(bounds: Rect, options: Extrude, view: View, face: Planar let (t, side) = match face { PlanarFace::Front => (0.0, 1.0), PlanarFace::Back => (1.0, -1.0), + PlanarFace::Side => return None, }; let placing = Placing::new(&camera, bounds.center(), Turn::new(bounds, o.twist, o.taper, t), o.depth / 2.0 - o.depth * t); let at = placing.place(bounds.center()); @@ -235,7 +237,7 @@ impl MeshFace { /// Extrude & Bevel's cap `face` in the solid's mesh ([`MeshFace`]), for a solid built with /// `bounds`, `options` and `view`, as [`extrude_face_map`] maps it on the page. With a depth of 0 /// the art is a plane ([`plane_mesh_face`]). `None` for a hollow solid, for the back of a plane, -/// and for invalid bounds. +/// for the side, and for invalid bounds. pub fn extrude_mesh_face(bounds: Rect, options: Extrude, view: View, face: PlanarFace) -> Option { check_bounds(bounds).ok()?; let o = options.sanitized(); @@ -249,6 +251,7 @@ pub fn extrude_mesh_face(bounds: Rect, options: Extrude, view: View, face: Plana let (t, side) = match face { PlanarFace::Front => (0.0, 1.0), PlanarFace::Back => (1.0, -1.0), + PlanarFace::Side => return None, }; let placing = Placing::new(&camera, bounds.center(), Turn::new(bounds, o.twist, o.taper, t), o.depth / 2.0 - o.depth * t); Some(MeshFace::new(&camera, &placing, bounds.center(), side, false)) diff --git a/crates/three-d/src/solid/side.rs b/crates/three-d/src/solid/side.rs new file mode 100644 index 0000000000..2a285246ec --- /dev/null +++ b/crates/three-d/src/solid/side.rs @@ -0,0 +1,133 @@ +//! Extrude & Bevel's side unrolled flat, for the graphics mapped onto it ([`super::Facet::surface`]). +//! +//! x runs along the outline of the solid's longest contour, through its corners and curves, and y +//! runs from the front cap's edge toward the back cap's, across the bevels and the walls. Both are +//! lengths in points: x along the art's own outline (the front cap's edge, or with a bevel carved +//! into the shape the walls' outline), y along the outline's steps (the slant +//! of each bevel step and the depth of the walls), before the twist and the taper, which carry the +//! graphic with the side. x is 0 where the contour's top crosses the vertical line through the +//! middle of its bounds and grows clockwise around the outline as the front is seen on the page, so +//! a graphic reads the right way round from outside the side. y is 0 half way along the steps. The +//! side is cut at the anchor of the contour nearest half way around from x = 0. + +use super::rings::signed_area; +use super::{Point, Rect}; + +/// The length of the outline of `ring`. +fn perimeter(ring: &[Point]) -> f64 { + ring.iter().zip(ring.iter().cycle().skip(1)).take(ring.len()).map(|(a, b)| a.distance(*b)).sum() +} + +/// The ring of `rings` with the longest outline (the first of equal ones), which carries the side's +/// graphics. `None` when no ring has a finite length above 0. +pub(super) fn longest(rings: &[&[Point]]) -> Option { + rings + .iter() + .map(|r| perimeter(r)) + .enumerate() + .filter(|(_, l)| l.is_finite() && *l > 0.0) + .fold(None, |best: Option<(usize, f64)>, (k, l)| if best.is_some_and(|(_, top)| top >= l) { best } else { Some((k, l)) }) + .map(|(k, _)| k) +} + +/// The x of each end of each edge of `ring` (point `i` to point `i + 1`, the last back to the first), +/// as the module describes. `None` for a ring with no length or bounds that are not finite. +pub(super) fn along_ring(ring: &[Point]) -> Option> { + let n = ring.len(); + if n < 2 { + return None; + } + let edges = || ring.iter().zip(ring.iter().cycle().skip(1)).map(|(a, b)| (*a, *b)); + let lengths: Vec = edges().map(|(a, b)| a.distance(b)).collect(); + let total: f64 = lengths.iter().sum(); + if !total.is_finite() || total <= 0.0 { + return None; + } + let mut starts = Vec::with_capacity(n); + let mut at = 0.0; + for l in &lengths { + starts.push(at); + at += l; + } + let bounds = ring.iter().fold(None, |b: Option, p| Some(b.map_or(Rect::from_points(*p, *p), |b| b.union_pt(*p))))?; + let middle = bounds.center().x; + // Where x = 0: the crossing of the middle line nearest the top, as a length along the ring. + let mut origin: Option<(f64, f64)> = None; + let mut keep = |y: f64, s: f64| { + if origin.is_none_or(|(top, _)| y < top) { + origin = Some((y, s)); + } + }; + for ((a, b), (s, l)) in edges().zip(starts.iter().zip(&lengths)) { + if (a.x - middle) * (b.x - middle) > 0.0 { + continue; + } + if a.x == b.x { + // An edge along the middle line: its upper end. + if a.y <= b.y { keep(a.y, *s) } else { keep(b.y, s + l) } + } else { + let t = (middle - a.x) / (b.x - a.x); + keep(a.y + (b.y - a.y) * t, s + l * t); + } + } + let (_, origin) = origin?; + // The cut: the anchor nearest half way around from the origin. + let opposite = (origin + total / 2.0).rem_euclid(total); + let round = |d: f64| { + let d = d.rem_euclid(total); + d.min(total - d) + }; + let cut = starts + .iter() + .copied() + .fold(None, |best: Option, s| if best.is_some_and(|b| round(b - opposite) <= round(s - opposite)) { best } else { Some(s) })?; + let from_cut = (origin - cut).rem_euclid(total); + // The ring runs clockwise on the page (y down) when it encloses positive area: x grows along it. + let sign = if signed_area(ring) >= 0.0 { 1.0 } else { -1.0 }; + Some( + starts + .iter() + .zip(&lengths) + .map(|(s, l)| { + let a = (s - cut).rem_euclid(total) - from_cut; + [a * sign, (a + l) * sign] + }) + .collect(), + ) +} + +/// The y of each of an extrusion's `steps`, each its inset (points) and its depth fraction (0 front, +/// 1 back) of a solid `depth` points deep: the length along the steps from their middle, growing +/// toward the back. +pub(super) fn across_steps(steps: &[(f64, f64)], depth: f64) -> Vec { + let mut out = Vec::with_capacity(steps.len()); + let mut at = 0.0; + for (k, (inset, t)) in steps.iter().enumerate() { + if let Some((i0, t0)) = k.checked_sub(1).and_then(|k| steps.get(k)) { + at += (inset - i0).hypot(depth * (t - t0)); + } + out.push(at); + } + let middle = at / 2.0; + out.into_iter().map(|y| y - middle).collect() +} + +/// The size of Extrude & Bevel's side unrolled, around the longest of `rings` and across the steps +/// `steps` (each inset and depth fraction) of a solid `depth` points deep: the length around it, +/// the length across it, and the width about x = 0 that does not reach the side's cut (twice the +/// distance from x = 0 to the nearer end of the cut side). `None` when the side has no length +/// either way. +pub(super) fn size(rings: &[&[Point]], steps: &[(f64, f64)], depth: f64) -> Option<(f64, f64, f64)> { + let ring = rings.get(longest(rings)?)?; + let across = across_steps(steps, depth); + let height = across.last().zip(across.first()).map_or(0.0, |(b, a)| b - a); + let width = perimeter(ring); + let xs = along_ring(ring)?; + let (lo, hi) = xs.iter().flatten().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), x| (lo.min(*x), hi.max(*x))); + let span = 2.0 * (-lo).min(hi); + (width.is_finite() && height.is_finite() && width > 0.0 && height > 0.0).then_some((width, height, span.clamp(0.0, width))) +} + +#[cfg(test)] +#[path = "tests_side.rs"] +mod tests; diff --git a/crates/three-d/src/solid/tests.rs b/crates/three-d/src/solid/tests.rs index 0d9566e5e5..b32faf1097 100644 --- a/crates/three-d/src/solid/tests.rs +++ b/crates/three-d/src/solid/tests.rs @@ -438,9 +438,11 @@ fn malformed_and_degenerate_input_is_bounded() { cap: true, bevel: Some(Bevel { width: f64::NAN, height: 1e12, repeat: usize::MAX, space: 7.0, ..Bevel::default() }), hidden: false, + map_surface: true, }; let f = extrude(&p, FillRule::EvenOdd, b, wild, View { rotation_x: f64::NAN, perspective: 900.0, ..front() }).unwrap(); assert!(f.iter().flat_map(|f| f.contours.iter().flatten()).all(|q| q.x.is_finite() && q.y.is_finite())); + assert!(f.iter().filter_map(|f| f.surface.as_ref()).flat_map(|c| c.uv.iter()).all(|q| q.x.is_finite() && q.y.is_finite())); assert!( inflate( &p, diff --git a/crates/three-d/src/solid/tests_side.rs b/crates/three-d/src/solid/tests_side.rs new file mode 100644 index 0000000000..f2d7ec722a --- /dev/null +++ b/crates/three-d/src/solid/tests_side.rs @@ -0,0 +1,96 @@ +use vectorcraft_geom::{BezPath, FillRule, PathData, Point, Rect}; + +use super::super::{Bevel, Extrude, View, extrude, extrude_side_size}; +use super::{across_steps, along_ring, longest}; + +fn square(r: Rect, hole: Option) -> PathData { + let mut b = BezPath::new(); + b.move_to((r.x0, r.y0)); + b.line_to((r.x1, r.y0)); + b.line_to((r.x1, r.y1)); + b.line_to((r.x0, r.y1)); + b.close_path(); + if let Some(h) = hole { + b.move_to((h.x0, h.y0)); + b.line_to((h.x0, h.y1)); + b.line_to((h.x1, h.y1)); + b.line_to((h.x1, h.y0)); + b.close_path(); + } + PathData::from_bezpath(&b) +} + +/// x is 0 at the top of the middle line and grows clockwise on the page; the side is cut at the +/// anchor nearest half way around (the first of two equally near). +#[test] +fn x_runs_clockwise_from_the_top_middle() { + let ring = [Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(10.0, 10.0), Point::new(0.0, 10.0)]; + assert_eq!(along_ring(&ring).unwrap(), vec![[-5.0, 5.0], [5.0, 15.0], [-25.0, -15.0], [-15.0, -5.0]]); + // The same outline run the other way gives each point the same x, apart from the seam, which + // is now at (0, 10), its first anchor of the two equally near. + let back: Vec = ring.iter().rev().copied().collect(); + let x = along_ring(&back).unwrap(); + assert_eq!(x, vec![[25.0, 15.0], [15.0, 5.0], [5.0, -5.0], [-5.0, -15.0]]); + assert_eq!(along_ring(&[Point::ZERO, Point::ZERO]), None); +} + +#[test] +fn y_runs_across_the_steps_from_their_middle() { + // A 4 × 3 pt bevel step, then 20 pt of wall, on a solid 30 pt deep. + let y = across_steps(&[(0.0, 0.0), (-4.0, 0.1), (-4.0, 0.1 + 20.0 / 30.0)], 30.0); + let expected = [-12.5, -7.5, 12.5]; + for (a, b) in y.iter().zip(expected) { + assert!((a - b).abs() < 1e-9, "{y:?}"); + } +} + +/// With graphics on the side, every piece of the walls of the longest contour carries its place on +/// the side unrolled, and no other facet does: x along the outline and y from the front to the back. +#[test] +fn the_longest_contours_walls_carry_their_place_on_the_side() { + let (outer, inner) = (Rect::new(0.0, 0.0, 100.0, 60.0), Rect::new(30.0, 20.0, 70.0, 40.0)); + let path = square(outer, Some(inner)); + let o = Extrude { depth: 40.0, map_surface: true, ..Extrude::default() }; + // Seen from above: the top wall faces the viewer and keeps its x on the page. + let top = View { rotation_x: -90.0, ..View::default() }; + let facets = extrude(&path, FillRule::NonZero, outer, o, top).unwrap(); + let cells: Vec<_> = facets.iter().filter_map(|f| f.surface.as_ref().map(|c| (f, c))).collect(); + assert!(!cells.is_empty()); + assert!(cells.iter().all(|(f, c)| f.side && f.end.is_none() && c.uv.len() == 4 && c.page.len() == 4)); + let seen: Vec<_> = cells.iter().filter(|(_, c)| c.outward).collect(); + assert_eq!(seen.len(), 1, "only the top wall of the outline faces the viewer"); + for (_, c) in seen { + for (uv, page) in c.uv.iter().zip(&c.page) { + assert!((page.x - (50.0 + uv.x)).abs() < 1e-6, "{uv:?} {page:?}"); + assert!(uv.y.abs() <= 20.0 + 1e-9); + } + } + // Only the outline's top wall is drawn (the walls seen edge-on have no area on the page, and the + // bottom wall faces away); the hole's walls carry none. Without graphics no facet carries one. + assert_eq!(cells.len(), 1); + let turned = View { rotation_x: -60.0, rotation_y: 30.0, ..View::default() }; + let hollow = extrude(&path, FillRule::NonZero, outer, Extrude { cap: false, ..o }, turned).unwrap(); + let hollow: Vec<_> = hollow.iter().filter_map(|f| f.surface.as_ref()).collect(); + // A hollow solid shows the insides of its far walls: they carry a cell that is not outward. + assert!(hollow.iter().any(|c| c.outward) && hollow.iter().any(|c| !c.outward), "{}", hollow.len()); + let plain = extrude(&path, FillRule::NonZero, outer, Extrude { map_surface: false, ..o }, top).unwrap(); + assert!(plain.iter().all(|f| f.surface.is_none())); + assert_eq!(plain.len(), facets.len()); +} + +#[test] +fn the_side_measures_around_the_outline_and_across_the_bevels() { + let outer = Rect::new(0.0, 0.0, 100.0, 60.0); + let path = square(outer, None); + let plain = Extrude { depth: 40.0, ..Extrude::default() }; + // The cut is at a bottom corner, 110 pt each way from the top's middle: 220 pt about x = 0 + // stay clear of it. + assert_eq!(extrude_side_size(&path, FillRule::NonZero, outer, plain), Some((320.0, 40.0, 220.0))); + // A 3 × 4 pt classic bevel outside adds its 5 pt slant and takes 4 pt of the wall. + let bevel = Extrude { bevel: Some(Bevel { width: 3.0, height: 4.0, ..Bevel::default() }), ..plain }; + let (w, h, span) = extrude_side_size(&path, FillRule::NonZero, outer, bevel).unwrap(); + assert!((w - 320.0).abs() < 1e-9 && (h - 41.0).abs() < 1e-9 && (span - 220.0).abs() < 1e-9, "{w} {h} {span}"); + assert_eq!(extrude_side_size(&path, FillRule::NonZero, outer, Extrude { depth: 0.0, ..plain }), None); + let rings = [&[Point::ZERO, Point::new(1.0, 0.0), Point::new(0.0, 1.0)][..], &[Point::ZERO, Point::new(5.0, 0.0), Point::new(0.0, 5.0)][..]]; + assert_eq!(longest(&rings), Some(1)); +} diff --git a/crates/tools/src/addons/anchor_eraser.rs b/crates/tools/src/addons/anchor_eraser.rs index 1eae255bc2..114e2b8e7a 100644 --- a/crates/tools/src/addons/anchor_eraser.rs +++ b/crates/tools/src/addons/anchor_eraser.rs @@ -152,6 +152,16 @@ impl Tool for AnchorEraserTool { _ => {} } } + + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "size" => c::number(key, v, SIZE_RANGE.0, SIZE_RANGE.1), + "tolerance" => c::number(key, v, TOLERANCE_RANGE.0, TOLERANCE_RANGE.1), + "pressure" => c::boolean(key, v), + _ => Err(c::unknown(key)), + } + } } #[cfg(test)] diff --git a/crates/tools/src/addons/box3d.rs b/crates/tools/src/addons/box3d.rs index b0ecdc350e..e4f4b272c5 100644 --- a/crates/tools/src/addons/box3d.rs +++ b/crates/tools/src/addons/box3d.rs @@ -729,4 +729,33 @@ impl Tool for Box3dTool { _ => {} } } + + /// The options within their ranges. Any finite arc angle is taken: it is kept from 0 to 360°. + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + use crate::option_check as c; + let max_radius = crate::shape::MAX_CORNER_RADIUS; + match key { + "shape" => c::one_of(key, v, &["box3d", "rectangle", "ellipse", "polygon", "star", "spiral"]), + "cornerRadius" => c::number(key, v, 0.0, max_radius), + "cornerRadii" => { + let radii = v.as_array().filter(|a| a.len() == 4); + if radii.is_some_and(|a| a.iter().all(|r| r.as_f64().is_some_and(|r| r.is_finite() && (0.0..=max_radius).contains(&r)))) { + Ok(()) + } else { + Err(format!("`cornerRadii` must be four numbers from 0 to {max_radius}")) + } + } + "arcStart" | "arcEnd" => c::finite(key, v), + "arcMode" => c::one_of(key, v, &["whole", "pie", "chord", "arc"]), + "sides" | "points" => c::whole(key, v, 3, 1000), + "starRatio" => c::number(key, v, 0.01, 1.0), + "rounded" | "randomized" => c::number(key, v, -10.0, 10.0), + "turns" => c::number(key, v, 0.01, 1024.0), + "divergence" => c::number(key, v, 0.0, 1000.0), + "innerRadius" => c::number(key, v, 0.0, 0.999), + "angleX" | "angleY" | "angleZ" => c::number(key, v, -180.0, 180.0), + "cornerSymmetry" | "polyIsStar" | "clockwise" | "parallelX" | "parallelY" | "parallelZ" => c::boolean(key, v), + _ => Err(c::unknown(key)), + } + } } diff --git a/crates/tools/src/addons/contour.rs b/crates/tools/src/addons/contour.rs index e77bb29eed..3bac5a6649 100644 --- a/crates/tools/src/addons/contour.rs +++ b/crates/tools/src/addons/contour.rs @@ -248,6 +248,15 @@ impl Tool for ContourTool { } } + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + match key { + "corners" if value.as_str().and_then(Corners::parse).is_some() => Ok(()), + "corners" => Err("`corners` must be one of `sharp`, `round`, `square`".into()), + "miterLimit" => crate::option_check::number(key, value, 1.0, 500.0), + _ => Err(crate::option_check::unknown(key)), + } + } + fn busy(&self) -> bool { self.drag.is_some() } diff --git a/crates/tools/src/addons/corner_tool.rs b/crates/tools/src/addons/corner_tool.rs index 470795579e..05ec27b18b 100644 --- a/crates/tools/src/addons/corner_tool.rs +++ b/crates/tools/src/addons/corner_tool.rs @@ -382,6 +382,16 @@ impl Tool for CornerTool { _ => {} } } + + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "radius" => c::number(key, v, 0.0, MAX_RADIUS), + "kind" if serde_json::from_value::(v.clone()).is_ok() => Ok(()), + "kind" => Err("`kind` must be one of `round`, `invertedRound`, `chamfer`".into()), + _ => Err(c::unknown(key)), + } + } } #[cfg(test)] diff --git a/crates/tools/src/addons/extend_path.rs b/crates/tools/src/addons/extend_path.rs index 816000ac9f..e844da9130 100644 --- a/crates/tools/src/addons/extend_path.rs +++ b/crates/tools/src/addons/extend_path.rs @@ -203,6 +203,14 @@ impl Tool for ExtendPathTool { self.mode = Mode(m); } } + + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + if key != "mode" { + return Err(crate::option_check::unknown(key)); + } + let ids: Vec<&str> = ExtendMode::ALL.iter().map(|m| m.id()).collect(); + crate::option_check::one_of(key, v, &ids) + } } #[cfg(test)] diff --git a/crates/tools/src/addons/parametric_shape.rs b/crates/tools/src/addons/parametric_shape.rs index 33700073c7..e651f5399b 100644 --- a/crates/tools/src/addons/parametric_shape.rs +++ b/crates/tools/src/addons/parametric_shape.rs @@ -475,6 +475,32 @@ impl Tool for ParametricShapeTool { self.next = s; } } + + /// The numbers [`Self::options`] shows, each as [`apply`] checks it; null is not a value. + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + if self.options().get(key).is_none() { + return Err(crate::option_check::unknown(key)); + } + if v.is_null() { + return Err(format!("`{key}` must not be null")); + } + apply(self.next, &json!({ key: v })).map(|_| ()) + } + + /// The options together, as [`apply`] takes them: a `kind` given with them sets the kind + /// first, and the other values are checked against that kind's ranges. + fn check_options(&self, values: &serde_json::Map) -> Result<(), String> { + let options = self.options(); + for (key, v) in values { + if options.get(key).is_none() { + return Err(crate::option_check::unknown(key)); + } + if v.is_null() { + return Err(format!("`{key}` must not be null")); + } + } + apply(self.next, &Value::Object(values.clone())).map(|_| ()) + } } #[cfg(test)] diff --git a/crates/tools/src/addons/shared_edge.rs b/crates/tools/src/addons/shared_edge.rs index d11261800a..703e8e6f3f 100644 --- a/crates/tools/src/addons/shared_edge.rs +++ b/crates/tools/src/addons/shared_edge.rs @@ -214,6 +214,16 @@ impl Tool for SharedEdgeTool { _ => {} } } + + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "diameter" => c::number(key, v, DIAMETER_RANGE.0, DIAMETER_RANGE.1), + "tolerance" => c::number(key, v, 0.0, MAX_COINCIDENCE), + "together" => c::boolean(key, v), + _ => Err(c::unknown(key)), + } + } } #[cfg(test)] diff --git a/crates/tools/src/addons/smart_pen.rs b/crates/tools/src/addons/smart_pen.rs index 43269ed580..805e015159 100644 --- a/crates/tools/src/addons/smart_pen.rs +++ b/crates/tools/src/addons/smart_pen.rs @@ -625,6 +625,10 @@ impl Tool for SmartPenTool { } } } + + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + if key == "next" { crate::option_check::one_of(key, v, &["curved", "straight"]) } else { Err(crate::option_check::unknown(key)) } + } } #[cfg(test)] diff --git a/crates/tools/src/builder.rs b/crates/tools/src/builder.rs index 3dc7c70b96..77ff240f75 100644 --- a/crates/tools/src/builder.rs +++ b/crates/tools/src/builder.rs @@ -211,8 +211,26 @@ pub struct ShapeBuilderTool { prepared: Option>, /// A gesture made while the map of a large selection is being built on another thread. deferred: Option, + /// The button went down with nothing selected: the release says what to select. + empty_press: bool, + /// The last gesture put one of [`SHAPE_BUILDER_STATUS`] in the status bar: the next gesture that + /// builds something clears it. + diagnosed: bool, } +/// The status a Shape Builder gesture gives when the selection holds no path or compound path. +pub const SELECT_PATHS: &str = "Shape Builder: select paths or compound paths"; + +/// The status a Shape Builder gesture that touched nothing gives when it ends over a path or +/// compound path that is not selected. +pub const SELECT_ALL_PATHS: &str = "Shape Builder: select all paths you want to merge"; + +/// The status a Shape Builder gesture that touched nothing gives anywhere else. +pub const NO_REGION: &str = "Shape Builder: no region under the pointer"; + +/// The status messages the Shape Builder tool gives. +pub const SHAPE_BUILDER_STATUS: [&str; 3] = [SELECT_PATHS, SELECT_ALL_PATHS, NO_REGION]; + /// A Shape Builder gesture made while the map of the selection was being built on another /// thread: the map key and the inputs it was made over, its pointer events, which [`Tool::poll`] /// replays once the map is there, and whether the release has come. @@ -455,6 +473,26 @@ impl ShapeBuilderTool { } } + /// Why a gesture released at `p` that touched nothing built nothing: the selection gives no path + /// or compound path ([`SELECT_PATHS`]); the pointer is over a path or compound path that a click + /// can pick and that is neither selected nor inside a selected object ([`SELECT_ALL_PATHS`]); or + /// neither ([`NO_REGION`]). + fn nothing_built(&mut self, cx: &ToolContext, p: Point) -> Action { + self.diagnosed = true; + if self.cache.get(cx, self.opts.open_filled_as_closed).shapes.is_empty() { + return Action::Status(SELECT_PATHS.into()); + } + let unselected = vectorcraft_doc::hit::hit_test(cx.doc, p, cx.hit_options()).is_some_and(|h| { + let chain: Vec = h.ancestry.iter().copied().chain([h.leaf]).collect(); + let path = chain + .iter() + .filter_map(|id| cx.doc.node(*id)) + .any(|n| matches!(n.kind, NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. })); + path && !chain.iter().any(|id| cx.selection.contains(*id)) + }); + Action::Status(if unselected { SELECT_ALL_PATHS } else { NO_REGION }.into()) + } + /// The cursor swatch preview: the swatch before the current fill, the current fill (ringed) /// and the swatch after it, side by side above the pointer. fn swatch_chips(&self, cx: &ToolContext) -> Vec { @@ -479,7 +517,9 @@ impl Tool for ShapeBuilderTool { vec![] } PointerKind::Down => { - // While a merge is being computed, a press starts no gesture. + // While a merge is being computed, a press starts no gesture. With nothing + // selected, the release says what to select. + self.empty_press = cx.selection.is_empty() && !self.editing(); if cx.selection.is_empty() || self.editing() { return vec![]; } @@ -564,7 +604,7 @@ impl Tool for ShapeBuilderTool { let press = points.first().copied().filter(|s| marquee.is_none() && !self.far && s.distance(p) <= cx.tol(CLICK_TOL_PX)); let split = press.filter(|q| self.stroke_at(cx, *q, erase).is_some()); if std::mem::take(&mut self.touched).is_empty() && split.is_none() { - return vec![]; + return vec![self.nothing_built(cx, p)]; } self.stroke = None; let roots = sorted_roots(cx.doc, &cx.selection.objects); @@ -590,11 +630,17 @@ impl Tool for ShapeBuilderTool { if self.opts.swatches { params["pickColorFrom"] = json!("swatches"); } + // The gesture builds something: the reason the last one built nothing goes. + let mut acts: Vec = std::mem::take(&mut self.diagnosed).then(|| Action::Status(String::new())).into_iter().collect(); // A large selection's merge is computed on another thread; `poll` applies it. - if self.start_merge(cx, ¶ms) { - return vec![]; + if !self.start_merge(cx, ¶ms) { + acts.push(Action::Exec("shapeBuilder.merge".into(), params)); } - vec![Action::Exec("shapeBuilder.merge".into(), params)] + acts + } + PointerKind::Up if std::mem::take(&mut self.empty_press) => { + self.diagnosed = true; + vec![Action::Status(SELECT_PATHS.into())] } _ => vec![], } @@ -693,6 +739,7 @@ impl Tool for ShapeBuilderTool { /// Choosing another tool or another document applies the merge being computed first. fn deactivate(&mut self, cx: &ToolContext) -> Vec { + self.empty_press = false; self.finish_edit(cx) } @@ -735,9 +782,11 @@ impl Tool for ShapeBuilderTool { /// With Pick Color From Color Swatches, the Left and Right arrow keys pick the color swatch /// before or after the current fill. Escape during a drag cancels it: the release after it - /// merges and deletes nothing. + /// merges and deletes nothing, and Escape while a press with nothing selected is held keeps its + /// release from showing a status. fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool { - (self.opts.swatches && !self.dragging && matches!(key, ToolKey::Left | ToolKey::Right)) || (self.dragging && key == ToolKey::Escape) + (self.opts.swatches && !self.dragging && matches!(key, ToolKey::Left | ToolKey::Right)) + || ((self.dragging || self.empty_press) && key == ToolKey::Escape) } /// The arrows pick swatches only without modifiers; Shift, Alt and Cmd/Ctrl arrows keep their @@ -753,6 +802,7 @@ impl Tool for ShapeBuilderTool { } if key == ToolKey::Escape { self.dragging = false; + self.empty_press = false; self.points.clear(); self.touched = Touched::default(); // A gesture recorded while the map is being built is canceled with it. @@ -808,6 +858,9 @@ impl Tool for ShapeBuilderTool { self.cache.clear(); self.cache.gap = self.gap(); } + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + check_builder_options(self.id(), &serde_json::Map::from_iter([(key.to_string(), v.clone())])) + } } /// Why `tool.setOption` cannot give the builder-family tool `tool` the options `values`, checked diff --git a/crates/tools/src/builder/live_paint.rs b/crates/tools/src/builder/live_paint.rs index caa9379308..c694240057 100644 --- a/crates/tools/src/builder/live_paint.rs +++ b/crates/tools/src/builder/live_paint.rs @@ -870,6 +870,10 @@ impl Tool for LivePaintBucketTool { self.hover = LpHover::None; } + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + check_live_paint_options(self.id(), &serde_json::Map::from_iter([(key.to_string(), v.clone())])) + } + fn waiting(&self) -> bool { self.cache.waiting() } @@ -1293,4 +1297,8 @@ impl Tool for LivePaintSelectionTool { } self.hover = LpHover::None; } + + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + check_live_paint_options(self.id(), &serde_json::Map::from_iter([(key.to_string(), v.clone())])) + } } diff --git a/crates/tools/src/builder/map.rs b/crates/tools/src/builder/map.rs index 6b524e9af9..437ecde69a 100644 --- a/crates/tools/src/builder/map.rs +++ b/crates/tools/src/builder/map.rs @@ -519,6 +519,58 @@ pub fn sample_polyline(pts: &[Point], step: f64) -> Vec { out } +#[cfg(test)] +thread_local! { + /// The edges [`hatch`] has tested against a scanline on this thread. + pub(super) static HATCH_EDGE_TESTS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// A region's edges in [`hatch`]'s rotated space, met in order of rising scanline. Each line tests +/// only the edges that span it, and the edges with a NaN or infinite end height. +pub(super) struct EdgeSweep { + /// The edges with finite, unequal end heights, by lower end. + edges: Vec<(Point, Point)>, + /// How many of `edges` have reached the active list. + next: usize, + /// The edges whose lower end is at or below the last line and whose upper end is above it. + active: Vec<(Point, Point)>, + /// The edges with a NaN or infinite end height. + loose: Vec<(Point, Point)>, +} + +impl EdgeSweep { + pub(super) fn new(mut edges: Vec<(Point, Point)>) -> Self { + let mut loose = vec![]; + edges.retain(|&(a, c)| { + let finite = a.y.is_finite() && c.y.is_finite(); + if !finite { + loose.push((a, c)); + } + // An edge with equal end heights never crosses a scanline. + finite && a.y != c.y + }); + edges.sort_unstable_by(|(a, c), (b, d)| a.y.min(c.y).total_cmp(&b.y.min(d.y))); + EdgeSweep { edges, next: 0, active: vec![], loose } + } + + /// Pushes the x of each edge crossing the scanline at `y` onto `xs`, in no particular order. + /// `y` is not NaN and never decreases from one call to the next. + pub(super) fn crossings(&mut self, y: f64, xs: &mut Vec) { + while let Some(&(a, c)) = self.edges.get(self.next).filter(|(a, c)| a.y.min(c.y) <= y) { + self.active.push((a, c)); + self.next += 1; + } + self.active.retain(|(a, c)| a.y.max(c.y) > y); + #[cfg(test)] + HATCH_EDGE_TESTS.with(|n| n.set(n.get() + self.active.len() + self.loose.len())); + for (a, c) in self.active.iter().chain(&self.loose) { + if (a.y <= y) != (c.y <= y) { + xs.push(a.x + (y - a.y) / (c.y - a.y) * (c.x - a.x)); + } + } + } +} + /// Diagonal hatch lines filling `path` (the Shape Builder's grey mesh highlight), `gap` apart. pub fn hatch(path: &BezPath, gap: f64) -> BezPath { let mut out = BezPath::new(); @@ -563,6 +615,7 @@ pub fn hatch(path: &BezPath, gap: f64) -> BezPath { } let gap = gap.max((y1 - y0) / 400.0).max(1e-6); let start = (y0 / gap).floor() * gap + gap * 0.5; + let mut sweep = EdgeSweep::new(edges); let mut xs: Vec = vec![]; // Counted, not summed: far from the origin `y + gap` can round back to `y`. The gap is at least // a 400th of the height, so 402 lines cover it. @@ -572,11 +625,7 @@ pub fn hatch(path: &BezPath, gap: f64) -> BezPath { break; } xs.clear(); - for (a, c) in &edges { - if (a.y <= y) != (c.y <= y) { - xs.push(a.x + (y - a.y) / (c.y - a.y) * (c.x - a.x)); - } - } + sweep.crossings(y, &mut xs); xs.sort_by(f64::total_cmp); for pair in xs.as_chunks::<2>().0 { out.move_to(unrot(Point::new(pair[0], y))); diff --git a/crates/tools/src/builder/tests.rs b/crates/tools/src/builder/tests.rs index 78d1c0b838..dc31c1ba79 100644 --- a/crates/tools/src/builder/tests.rs +++ b/crates/tools/src/builder/tests.rs @@ -471,6 +471,106 @@ fn shape_builder_hover_builds_a_small_map_at_once() { assert_eq!((t.cache.builds, t.cache.background), (1, 0)); } +fn status(msg: &str) -> Vec { + vec![Action::Status(msg.into())] +} + +/// A click or drag with nothing selected shows what to select when it is released, and Escape +/// during the press keeps the release quiet. +#[test] +fn shape_builder_with_nothing_selected_says_what_to_select() { + let (d, _, _) = two_rects(); + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = ShapeBuilderTool::default(); + assert!(t.pointer(&cx, &ev(PointerKind::Down, 75.0, 50.0)).is_empty()); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 75.0, 50.0)), status(SELECT_PATHS), "a click"); + assert!(t.pointer(&cx, &ev(PointerKind::Down, 25.0, 50.0)).is_empty()); + assert!(t.pointer(&cx, &ev(PointerKind::Drag, 125.0, 50.0)).is_empty()); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 125.0, 50.0)), status(SELECT_PATHS), "a drag"); + assert!(t.pointer(&cx, &ev(PointerKind::Up, 125.0, 50.0)).is_empty(), "a release without a press"); + t.pointer(&cx, &ev(PointerKind::Down, 75.0, 50.0)); + assert!(t.claims_key(&cx, ToolKey::Escape)); + assert!(t.key(&cx, ToolKey::Escape, Mods::default()).is_empty()); + assert!(t.pointer(&cx, &ev(PointerKind::Up, 75.0, 50.0)).is_empty(), "a canceled press"); + assert!(!t.claims_key(&cx, ToolKey::Escape)); +} + +/// With A of the overlapping squares A and B selected, a click on the part of B outside A builds +/// nothing and says to select every path to merge; a click on empty canvas says there is no +/// region; a click inside A still merges A alone and clears that status, and the click after it +/// gives the merge alone. +#[test] +fn shape_builder_names_the_unselected_path_under_a_release_that_built_nothing() { + let (d, a, _) = two_rects(); + let mut s = Selection::default(); + s.set([a]); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = ShapeBuilderTool::default(); + t.pointer(&cx, &ev(PointerKind::Down, 125.0, 50.0)); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 125.0, 50.0)), status(SELECT_ALL_PATHS)); + t.pointer(&cx, &ev(PointerKind::Down, 300.0, 300.0)); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 300.0, 300.0)), status(NO_REGION)); + t.pointer(&cx, &ev(PointerKind::Down, 75.0, 50.0)); + let acts = t.pointer(&cx, &ev(PointerKind::Up, 75.0, 50.0)); + assert!( + matches!(acts.as_slice(), [Action::Status(m), Action::Exec(id, v)] if m.is_empty() && id == "shapeBuilder.merge" && v["ids"] == json!([a.0])), + "{acts:?}" + ); + t.pointer(&cx, &ev(PointerKind::Down, 75.0, 50.0)); + let acts = t.pointer(&cx, &ev(PointerKind::Up, 75.0, 50.0)); + assert!(matches!(acts.as_slice(), [Action::Exec(id, _)] if id == "shapeBuilder.merge"), "{acts:?}"); + // A locked or hidden B cannot be picked, so the release says there is no region. + for hide in [false, true] { + let (mut d, a, b) = two_rects(); + let n = d.node_mut(b).unwrap(); + if hide { + n.visible = false; + } else { + n.locked = true; + } + let mut s = Selection::default(); + s.set([a]); + let cx = crate::testutil::cx(&d, &s, &p); + let mut t = ShapeBuilderTool::default(); + t.pointer(&cx, &ev(PointerKind::Down, 125.0, 50.0)); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 125.0, 50.0)), status(NO_REGION), "hidden: {hide}"); + } +} + +/// A selection that holds no path or compound path says to select one. +#[test] +fn shape_builder_with_no_path_selected_says_to_select_paths() { + let (mut d, a, _) = two_rects(); + d.node_mut(a).unwrap().locked = true; + let mut s = Selection::default(); + s.set([a]); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = ShapeBuilderTool::default(); + t.pointer(&cx, &ev(PointerKind::Down, 75.0, 50.0)); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 75.0, 50.0)), status(SELECT_PATHS)); +} + +/// A gesture made while the map of a large selection is being built and released over nothing +/// gives its status once, when it is replayed. +#[test] +fn shape_builder_replayed_gesture_over_nothing_gives_its_status_once() { + let (d, s) = square_row(200); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = ShapeBuilderTool::default(); + t.pointer(&cx, &ev(PointerKind::Move, 15.0, 10.0)); + assert!(t.pointer(&cx, &ev(PointerKind::Down, 450.0, 450.0)).is_empty()); + assert_eq!(t.cache.builds, 0, "the gesture did not wait for the map"); + assert!(t.pointer(&cx, &ev(PointerKind::Up, 450.0, 450.0)).is_empty(), "the gesture waits for the map"); + assert!(t.editing()); + assert_eq!(t.finish_edit(&cx), status(NO_REGION)); + assert!(t.finish_edit(&cx).is_empty() && !t.editing()); +} + #[test] fn shape_builder_alt_drag_erases_and_empty_drag_does_nothing() { let (d, a, b) = two_rects(); @@ -485,7 +585,7 @@ fn shape_builder_alt_drag_erases_and_empty_drag_does_nothing() { let Action::Exec(_, v) = &acts[0] else { panic!() }; assert_eq!(v["erase"], true); t.pointer(&cx, &ev(PointerKind::Down, 300.0, 300.0)); - assert!(t.pointer(&cx, &ev(PointerKind::Up, 300.0, 300.0)).is_empty()); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 300.0, 300.0)), status(NO_REGION), "the release edits nothing and says why"); } /// Squares A (0..100) and B (50..150 both ways), overlapping at a corner, selected. @@ -998,9 +1098,9 @@ fn shape_builder_stroke_options_round_trip_and_pick_the_side_under_the_pointer() let acts = t.pointer(&cx, &ev(PointerKind::Up, 0.5, 27.0)); let [Action::Exec(_, v)] = acts.as_slice() else { panic!("{acts:?}") }; assert_eq!((&v["splitStroke"], &v["points"]), (&json!(true), &json!([[-1.0, 25.0]]))); - // A release farther away is a drag, which splits nothing. + // A release farther away is a drag, which splits nothing and says it touched no region. t.pointer(&cx, &ev(PointerKind::Down, -1.0, 25.0)); - assert!(t.pointer(&cx, &ev(PointerKind::Up, -1.0, 30.0)).is_empty()); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, -1.0, 30.0)), status(NO_REGION)); // So is a Straight Line drag that goes away and ends back near the press. t.set_option("selection", &json!("straightLine")); t.pointer(&cx, &ev(PointerKind::Down, -1.0, 25.0)); @@ -1008,11 +1108,12 @@ fn shape_builder_stroke_options_round_trip_and_pick_the_side_under_the_pointer() let acts = t.pointer(&cx, &ev(PointerKind::Up, -0.5, 25.5)); assert!(!acts.iter().any(|a| matches!(a, Action::Exec(_, v) if v.get("splitStroke").is_some())), "{acts:?}"); t.set_option("selection", &json!("freeform")); - // A drag merges as before and sends no switch. + // A drag merges as before and sends no switch; it clears the status the drag before it gave. t.pointer(&cx, &ev(PointerKind::Down, 25.0, 25.0)); t.pointer(&cx, &ev(PointerKind::Drag, 75.0, 75.0)); let acts = t.pointer(&cx, &ev(PointerKind::Up, 75.0, 75.0)); - let [Action::Exec(_, v)] = acts.as_slice() else { panic!("{acts:?}") }; + let [Action::Status(m), Action::Exec(_, v)] = acts.as_slice() else { panic!("{acts:?}") }; + assert!(m.is_empty(), "{m}"); assert!(v.get("splitStroke").is_none(), "{v}"); } @@ -1032,6 +1133,275 @@ fn hatch_far_from_the_origin_ends() { assert!(hatch(&bp, 4.0).elements().len() <= 2 * 402); } +/// [`hatch`] as it tested every edge on every scanline, the reference the sweep must match. +fn hatch_every_edge(path: &BezPath, gap: f64) -> BezPath { + let mut out = BezPath::new(); + let b = path.bounding_box(); + if b.width() <= 0.0 || b.height() <= 0.0 { + return out; + } + let s = std::f64::consts::FRAC_1_SQRT_2; + let rot = |p: Point| Point::new((p.x + p.y) * s, (p.y - p.x) * s); + let unrot = |p: Point| Point::new((p.x - p.y) * s, (p.x + p.y) * s); + let mut edges: Vec<(Point, Point)> = vec![]; + let mut first = Point::ZERO; + let mut last = Point::ZERO; + kurbo::flatten(path.iter(), gap.max(1e-3) * 0.1, |el| match el { + kurbo::PathEl::MoveTo(p) => { + if last != first { + edges.push((rot(last), rot(first))); + } + first = p; + last = p; + } + kurbo::PathEl::LineTo(p) => { + edges.push((rot(last), rot(p))); + last = p; + } + kurbo::PathEl::ClosePath => { + if last != first { + edges.push((rot(last), rot(first))); + } + last = first; + } + _ => {} + }); + if last != first { + edges.push((rot(last), rot(first))); + } + let (mut y0, mut y1) = (f64::INFINITY, f64::NEG_INFINITY); + for (a, c) in &edges { + y0 = y0.min(a.y.min(c.y)); + y1 = y1.max(a.y.max(c.y)); + } + let gap = gap.max((y1 - y0) / 400.0).max(1e-6); + let start = (y0 / gap).floor() * gap + gap * 0.5; + let mut xs: Vec = vec![]; + for i in 0..402u32 { + let y = start + f64::from(i) * gap; + if y.partial_cmp(&y1) != Some(std::cmp::Ordering::Less) { + break; + } + xs.clear(); + for (a, c) in &edges { + if (a.y <= y) != (c.y <= y) { + xs.push(a.x + (y - a.y) / (c.y - a.y) * (c.x - a.x)); + } + } + xs.sort_by(f64::total_cmp); + for pair in xs.as_chunks::<2>().0 { + out.move_to(unrot(Point::new(pair[0], y))); + out.line_to(unrot(Point::new(pair[1], y))); + } + } + out +} + +/// A path's elements with every coordinate as its bits, so NaN and -0.0 compare exactly. +fn path_bits(p: &BezPath) -> Vec<(u8, Vec)> { + let bits = |pts: &[Point]| pts.iter().flat_map(|p| [p.x.to_bits(), p.y.to_bits()]).collect(); + p.elements() + .iter() + .map(|el| match *el { + kurbo::PathEl::MoveTo(a) => (0, bits(&[a])), + kurbo::PathEl::LineTo(a) => (1, bits(&[a])), + kurbo::PathEl::QuadTo(a, b) => (2, bits(&[a, b])), + kurbo::PathEl::CurveTo(a, b, c) => (3, bits(&[a, b, c])), + kurbo::PathEl::ClosePath => (4, vec![]), + }) + .collect() +} + +/// A closed polygon through `pts`. +fn polygon(pts: impl IntoIterator) -> BezPath { + let mut bp = BezPath::new(); + for (i, p) in pts.into_iter().enumerate() { + if i == 0 { + bp.move_to(p); + } else { + bp.line_to(p); + } + } + bp.close_path(); + bp +} + +/// A polygon of `n` sides inscribed in the circle of radius `r` about the origin. +fn circle_polygon(n: u32, r: f64) -> BezPath { + polygon((0..n).map(|i| { + let t = std::f64::consts::TAU * f64::from(i) / f64::from(n); + Point::new(r * t.cos(), r * t.sin()) + })) +} + +/// The paths the hatch is checked on: many edges, a random star, holes, several subpaths, a +/// sliver, curves, edges along the hatch, repeated outlines, an open path, far coordinates, an +/// empty path and NaN and infinite coordinates. +fn hatch_cases() -> Vec<(&'static str, BezPath)> { + let mut seed = 0x2545_f491_4f6c_dd1d_u64; + let mut rand = move || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed >> 11) as f64 / (1u64 << 53) as f64 + }; + let star = polygon((0..300).map(|i| { + let t = std::f64::consts::TAU * f64::from(i) / 300.0; + let r = 100.0 + 300.0 * rand(); + Point::new(r * t.cos(), r * t.sin()) + })); + let mut holes = shapes::rectangle(Rect::new(0.0, 0.0, 300.0, 200.0)).to_bezpath(); + holes.extend(polygon([(50.0, 50.0), (50.0, 150.0), (120.0, 150.0), (120.0, 50.0)].map(Point::from))); + holes.extend(polygon([(180.0, 40.0), (260.0, 100.0), (180.0, 160.0)].map(Point::from))); + holes.extend(circle_polygon(40, 30.0).iter().map(|el| match el { + kurbo::PathEl::MoveTo(p) => kurbo::PathEl::MoveTo(p + kurbo::Vec2::new(400.0, 100.0)), + kurbo::PathEl::LineTo(p) => kurbo::PathEl::LineTo(p + kurbo::Vec2::new(400.0, 100.0)), + other => other, + })); + let mut repeated = BezPath::new(); + for _ in 0..7 { + repeated.extend(shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)).to_bezpath()); + } + let mut open = BezPath::new(); + open.move_to((0.0, 0.0)); + open.line_to((120.0, 10.0)); + open.line_to((60.0, 90.0)); + vec![ + ("2,000-sided circle", circle_polygon(2000, 500.0)), + ("300-point star", star), + ("holes and subpaths", holes), + ("sliver", polygon([(0.0, 0.0), (900.0, 1.0), (900.0, 1.002)].map(Point::from))), + ("curves", kurbo::Circle::new((10.0, -20.0), 300.0).to_path(0.01)), + ("edges along the hatch", polygon([(0.0, 0.0), (10.0, 10.0), (0.0, 20.0), (-10.0, 10.0)].map(Point::from))), + ("repeated outlines", repeated), + ("open path", open), + ("far from the origin", shapes::rectangle(Rect::new(0.0, 1e17, 64.0, 1e17 + 64.0)).to_bezpath()), + ("empty", BezPath::new()), + ("NaN", polygon([(0.0, 0.0), (100.0, f64::NAN), (100.0, 100.0), (0.0, 80.0)].map(Point::from))), + ("infinite", polygon([(0.0, 0.0), (f64::INFINITY, 50.0), (100.0, 100.0)].map(Point::from))), + ] +} + +#[test] +fn hatch_matches_testing_every_edge() { + for (name, bp) in hatch_cases() { + for gap in [0.5, 4.0, 40.0] { + assert_eq!(path_bits(&hatch(&bp, gap)), path_bits(&hatch_every_edge(&bp, gap)), "{name} at gap {gap}"); + } + } +} + +#[test] +fn hatch_tests_only_the_edges_spanning_each_line() { + let bp = circle_polygon(2000, 500.0); + let before = map::HATCH_EDGE_TESTS.with(std::cell::Cell::get); + let h = hatch(&bp, 4.0); + let tests = map::HATCH_EDGE_TESTS.with(std::cell::Cell::get) - before; + // Each line crosses the circle once, so it has one segment. + let lines = h.elements().len() / 2; + assert!(lines > 200, "{lines}"); + assert!(tests * 20 < lines * 2000, "{tests} edge tests on {lines} lines of 2,000 edges"); +} + +#[test] +fn hatch_sweep_finds_the_crossings_of_every_edge() { + let p = Point::new; + let edges = vec![ + (p(0.0, 0.0), p(1.0, 1.0)), + (p(1.0, 1.0), p(0.0, 2.0)), + (p(3.0, 2.0), p(3.0, -1.0)), + (p(5.0, 1.0), p(9.0, 1.0)), + (p(2.0, -0.0), p(2.0, 0.0)), + (p(4.0, -0.0), p(4.0, 3.0)), + (p(6.0, 0.5), p(6.0, 0.5)), + (p(7.0, f64::NAN), p(7.0, 2.0)), + (p(8.0, 0.0), p(8.0, f64::INFINITY)), + (p(f64::NAN, 0.0), p(1.0, 2.0)), + (p(3.0, 2.0), p(3.0, -1.0)), + (p(3.0, 2.0), p(3.0, -1.0)), + ]; + let mut sweep = map::EdgeSweep::new(edges.clone()); + let mut xs = vec![]; + for y in [-2.0, -1.0, -0.0, 0.0, 0.5, 1.0, 1.0, 1.5, 2.0, 2.5, 3.0, 4.0] { + let mut old: Vec = + edges.iter().filter(|(a, c)| (a.y <= y) != (c.y <= y)).map(|(a, c)| a.x + (y - a.y) / (c.y - a.y) * (c.x - a.x)).collect(); + xs.clear(); + sweep.crossings(y, &mut xs); + old.sort_by(f64::total_cmp); + xs.sort_by(f64::total_cmp); + let bits = |v: &[f64]| v.iter().map(|x| x.to_bits()).collect::>(); + assert_eq!(bits(&xs), bits(&old), "at y = {y}"); + } +} + +fn thread_cpu() -> Option { + let stat = std::fs::read_to_string("/proc/thread-self/schedstat").ok()?; + stat.split_whitespace().next()?.parse().ok().map(std::time::Duration::from_nanos) +} + +/// The time `f` takes: this thread's CPU time where Linux reports it, otherwise the wall clock. +fn cpu_time(f: impl FnOnce()) -> std::time::Duration { + match thread_cpu() { + Some(before) => { + f(); + thread_cpu().map_or(std::time::Duration::ZERO, |after| after.saturating_sub(before)) + } + None => { + let start = std::time::Instant::now(); + f(); + start.elapsed() + } + } +} + +/// Timings of 1,000 hatches by the sweep and by testing every edge, on a 2,000-sided circle of +/// radius 500 and on a 40-sided one, run in turn, 7 runs each. Ignored by default; it prints the +/// median, fastest and slowest run and sets no bound on them: +/// `cargo test --release -p vectorcraft-tools --lib hatch_perf -- --ignored --nocapture`. +#[test] +#[ignore = "a benchmark: run with --ignored --nocapture"] +fn hatch_perf() { + const RUNS: usize = 7; + let ms = |d: std::time::Duration| d.as_secs_f64() * 1000.0; + eprintln!("hatch_perf: {}", if thread_cpu().is_some() { "thread CPU time" } else { "wall clock" }); + for (sides, r) in [(2000, 500.0), (2000, 100.0), (40, 100.0)] { + let bp = circle_polygon(sides, r); + assert_eq!(path_bits(&hatch(&bp, 4.0)), path_bits(&hatch_every_edge(&bp, 4.0))); + let (mut old, mut new) = (vec![], vec![]); + let every = || { + for _ in 0..1000 { + std::hint::black_box(hatch_every_edge(std::hint::black_box(&bp), 4.0)); + } + }; + let sweep = || { + for _ in 0..1000 { + std::hint::black_box(hatch(std::hint::black_box(&bp), 4.0)); + } + }; + for run in 0..RUNS { + // The two take turns going first. + if run % 2 == 0 { + old.push(cpu_time(every)); + new.push(cpu_time(sweep)); + } else { + new.push(cpu_time(sweep)); + old.push(cpu_time(every)); + } + } + old.sort(); + new.sort(); + eprintln!( + "hatch_perf: {sides:>5} sides r {r:>5}: every edge {:>9.3} ms ({:.3}-{:.3}), sweep {:>9.3} ms ({:.3}-{:.3})", + ms(old[RUNS / 2]), + ms(old[0]), + ms(old[RUNS - 1]), + ms(new[RUNS / 2]), + ms(new[0]), + ms(new[RUNS - 1]), + ); + } +} + /// An empty hidden sources group for a Live Paint group made in a test. fn empty_sources(d: &mut Document) -> Arc { let mut g = Node::group(d.alloc_id(), vec![]); diff --git a/crates/tools/src/catalog.rs b/crates/tools/src/catalog.rs index 529aa80d18..cd6cbf627a 100644 --- a/crates/tools/src/catalog.rs +++ b/crates/tools/src/catalog.rs @@ -56,6 +56,7 @@ pub const TOOL_GROUPS: &[&[ToolInfo]] = &[ t("rectangle", "Rectangle Tool", Some("M"), "tool-rect"), t("roundedRectangle", "Rounded Rectangle Tool", None, "tool-rounded-rect"), t("ellipse", "Ellipse Tool", Some("L"), "tool-ellipse"), + t(crate::circle::ID, "Circle Tool", None, "tool-circle"), t("polygon", "Polygon Tool", None, "tool-polygon"), t("star", "Star Tool", None, "tool-star"), t("flare", "Flare Tool", None, "tool-flare"), diff --git a/crates/tools/src/circle.rs b/crates/tools/src/circle.rs new file mode 100644 index 0000000000..9e467b35d6 --- /dev/null +++ b/crates/tools/src/circle.rs @@ -0,0 +1,309 @@ +//! The Circle tool draws a circle through points it is given (`shape.circleThroughPoints`). +//! +//! Two points are the ends of a diameter: a drag from one to the other, or a click on each. A click +//! on a first point, then a press on a second point dragged to a third, draws the circle through +//! the three. Shift keeps the second point at 45° steps from the first (from General › Constrain +//! Angle), Alt rounds the diameter of a circle drawn on two points to the nearest tick of the +//! rulers at the current zoom, in the General unit, and every point snaps to Smart Guides. Until +//! the release, the tool shows the circle as a dashed outline (solid once it is more than 50,000 +//! screen points around) with its points, its center as a small cross, a line from the center to +//! each point and, with Measurement Labels on, the diameter by the pointer. The circle is one undo +//! step. Escape, a press dropped part way, and an edit, Undo or Redo made outside the tool drop +//! the first point. A second press within 3 screen points +//! of the first point, or one that snaps to it, is a press on it: let go there (a double-click) it +//! places nothing, and dragged out it draws the circle on the diameter it drags out. Where no +//! circle passes through the points (two are the same, three lie on one line) or the circle would +//! reach past the canvas, the tool shows none and the release draws nothing; for three different +//! points on one line, or a circle past the canvas, the pointer shows "Circle too large". + +use serde_json::{Value, json}; +use vectorcraft_doc::MAX_COORD; +use vectorcraft_geom::{Point, Rect, Vec2, shapes}; + +use crate::guides::{DrawSnap, Leave}; +use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; + +pub const ID: &str = "circle"; + +/// How far (screen points) the pointer travels from a press before the press counts as a drag. +const DRAG_PX: f64 = 2.0; +/// Half the length (screen points) of each arm of the cross at the circle's center. +const CROSS_PX: f64 = 4.0; +/// How near (screen points) the first point a second click counts as a click on it. +const REACH_PX: f64 = 3.0; +/// The longest outline (screen points) the preview draws dashed, about 7,000 dashes. +const DASHED_PX: f64 = 50_000.0; + +/// The press in progress. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Press { + /// The first point `at`, pressed with the pointer at `from` (before snapping): a release after + /// a drag draws the circle on that diameter. + First { at: Point, from: Point, dragged: bool }, + /// The second press, after a click placed the first point, with the pointer at `from` (before + /// snapping). `snapped` is the point it snapped to, and `at` that point with Alt's rounding of + /// the diameter. A release without a drag draws the circle on the diameter to `at`; a drag + /// places the third point and the circle passes through `snapped`. A press within + /// [`REACH_PX`] of the first point, or one that snaps to it (`on_first`), is a press on it: let + /// go there it places nothing, and dragged out it draws the circle on the diameter it drags out. + Second { at: Point, snapped: Point, from: Point, on_first: bool, dragged: bool }, +} + +#[derive(Default)] +pub struct CircleTool { + snap: DrawSnap, + /// The first point, placed by a click (or by the press of a drag in progress). + first: Option, + press: Option, + /// Where the pointer is, snapped: the point the next press or release places. + pointer: Option, +} + +/// The command the tool runs for `points`. +fn command(points: &[Point]) -> (String, Value) { + let pairs: Vec = points.iter().map(|p| json!([p.x, p.y])).collect(); + ("shape.circleThroughPoints".into(), json!({ "points": pairs })) +} + +/// The circle through two points (the ends of a diameter) or three, as `shape.circleThroughPoints` +/// draws it: none where no circle passes through them or it would reach past the canvas. +pub fn circle_of(points: &[Point]) -> Option<(Point, f64)> { + let on_canvas = |(c, r): &(Point, f64)| [c.x - r, c.y - r, c.x + r, c.y + r].iter().all(|v| v.abs() <= MAX_COORD); + shapes::circle_through_points(points).filter(on_canvas) +} + +/// With Alt, `p` moved along the line from `first` so that their distance (the diameter) is on +/// the nearest ruler tick at the current zoom, in the General unit; `p` itself without Alt, and +/// when that rounding leaves no distance. +fn round_diameter(cx: &ToolContext, first: Point, p: Point, mods: Mods) -> Point { + let d = first.distance(p); + let rounded = cx.unit.snap_to_ruler_tick(d, cx.zoom); + if mods.alt && d > 0.0 && rounded > 0.0 && rounded.is_finite() { first + (p - first) * (rounded / d) } else { p } +} + +/// Are the points two or more different points through which no circle is drawn: three on one +/// line, or a circle that would reach past the canvas? +fn too_large(points: &[Point]) -> bool { + let distinct = points.iter().enumerate().all(|(i, p)| !points.iter().take(i).any(|q| q == p)); + points.len() >= 2 && distinct && circle_of(points).is_none() +} + +impl CircleTool { + fn clear(&mut self) { + self.first = None; + self.press = None; + self.pointer = None; + self.snap.clear(); + } + + /// How the second point keeps to the first: Shift's 45° steps and the construction guides. + fn leave(&self, cx: &ToolContext, mods: Mods) -> Option { + self.first.map(|a| Leave::segment(cx, a, mods.shift)) + } + + /// The points the circle passes through as the tool shows it now. + fn points(&self) -> Vec { + let mut out: Vec = self.first.into_iter().collect(); + match self.press { + Some(Press::First { .. }) | None => out.extend(self.pointer.filter(|_| self.first.is_some())), + // A press on the first point adds no point: a drag from it drags out a diameter. + Some(Press::Second { on_first: true, dragged, .. }) => out.extend(self.pointer.filter(|_| dragged)), + Some(Press::Second { at, dragged: false, .. }) => out.push(at), + Some(Press::Second { snapped, dragged: true, .. }) => { + out.push(snapped); + out.extend(self.pointer); + } + } + out + } + + /// The second point as the tool shows it: none for a press on the first point. + fn second(&self) -> Option { + match self.press { + Some(Press::Second { on_first: false, dragged: false, at, .. }) => Some(at), + Some(Press::Second { on_first: false, dragged: true, snapped, .. }) => Some(snapped), + _ => None, + } + } + + /// Runs the circle through `points` and starts afresh; where no circle is drawn through them + /// (the tool showed none), it only starts afresh. + fn draw(&mut self, points: &[Point]) -> Vec { + self.clear(); + if circle_of(points).is_none() { + return vec![]; + } + let (c, v) = command(points); + vec![Action::Exec(c, v)] + } + + /// Is the press a drag at `ev`: dragged already, or `ev` is [`DRAG_PX`] or more from the press? + fn drags(&self, cx: &ToolContext, ev: &PointerEvent) -> bool { + match self.press { + Some(Press::First { from, dragged, .. } | Press::Second { from, dragged, .. }) => dragged || ev.pos.distance(from) >= cx.tol(DRAG_PX), + None => false, + } + } +} + +impl Tool for CircleTool { + fn id(&self) -> &'static str { + ID + } + + fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { + if !ev.pos.is_finite() { + return vec![]; + } + // A drag ends where it is let go: the release moves the points as a drag to it would. A + // click, or a release within DRAG_PX of the press, keeps the points of the press. + if ev.kind == PointerKind::Up && self.drags(cx, ev) { + self.pointer(cx, &PointerEvent { kind: PointerKind::Drag, ..*ev }); + } + match ev.kind { + PointerKind::Move => { + let leave = self.leave(cx, ev.mods); + let p = self.snap.hover(cx, ev.pos, &[], leave.as_ref()); + self.pointer = Some(self.first.map_or(p, |a| round_diameter(cx, a, p, ev.mods))); + vec![] + } + PointerKind::Down => { + match self.first { + None => { + let at = self.snap.press(cx, ev.pos, &[], None); + self.first = Some(at); + self.press = Some(Press::First { at, from: ev.pos, dragged: false }); + self.pointer = Some(at); + } + Some(a) => { + let leave = self.leave(cx, ev.mods); + let snapped = self.snap.press(cx, ev.pos, &[], leave.as_ref()); + let at = round_diameter(cx, a, snapped, ev.mods); + let on_first = snapped == a || ev.pos.distance(a) <= cx.tol(REACH_PX); + self.press = Some(Press::Second { at, snapped, from: ev.pos, on_first, dragged: false }); + self.pointer = Some(at); + } + } + vec![] + } + PointerKind::Drag => { + match &mut self.press { + Some(Press::First { at, from, dragged }) => { + *dragged |= ev.pos.distance(*from) >= cx.tol(DRAG_PX); + let leave = Leave::segment(cx, *at, ev.mods.shift); + self.pointer = Some(round_diameter(cx, *at, self.snap.drag(cx, ev.pos, Some(&leave)), ev.mods)); + } + // Dragged from the first point, the pointer is the other end of a diameter, as + // for a drag from a first press. + Some(Press::Second { from, on_first: true, dragged, .. }) => { + *dragged |= ev.pos.distance(*from) >= cx.tol(DRAG_PX); + let leave = self.first.map(|a| Leave::segment(cx, a, ev.mods.shift)); + let p = self.snap.drag(cx, ev.pos, leave.as_ref()); + self.pointer = Some(self.first.map_or(p, |a| round_diameter(cx, a, p, ev.mods))); + } + Some(Press::Second { from, dragged, .. }) => { + *dragged |= ev.pos.distance(*from) >= cx.tol(DRAG_PX); + self.pointer = Some(self.snap.drag(cx, ev.pos, None)); + } + None => {} + } + vec![] + } + PointerKind::Up => match (self.press.take(), self.first, self.pointer) { + (Some(Press::First { at, dragged: true, .. }), _, Some(b)) if b.distance(at) >= cx.tol(DRAG_PX) => self.draw(&[at, b]), + // A click places the first point; the guides of the press go. + (Some(Press::First { .. }), ..) => { + self.snap.clear(); + vec![] + } + // The second click of a double-click lands on the first point and places nothing; + // a drag from there draws the circle on the diameter it drags out. + (Some(Press::Second { on_first: true, dragged: false, .. }), ..) => vec![], + (Some(Press::Second { on_first: true, dragged: true, .. }), Some(a), Some(c)) => self.draw(&[a, c]), + (Some(Press::Second { at, dragged: false, .. }), Some(a), _) => self.draw(&[a, at]), + // Three points: Alt's rounding of the diameter does not apply. + (Some(Press::Second { snapped, dragged: true, .. }), Some(a), Some(c)) => self.draw(&[a, snapped, c]), + _ => vec![], + }, + PointerKind::DoubleClick | PointerKind::TripleClick => vec![], + } + } + + fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { + if key == ToolKey::Escape { + self.clear(); + } + vec![] + } + + fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool { + key == ToolKey::Escape && self.first.is_some() + } + + /// A first point placed: Escape drops it. + fn ends_on_escape(&self, _cx: &ToolContext) -> bool { + self.first.is_some() + } + + fn busy(&self) -> bool { + self.first.is_some() + } + + /// A dropped press (a second finger, a canceled touch) drops the points placed so far. + fn drop_press(&mut self, _cx: &ToolContext) -> Vec { + self.clear(); + vec![] + } + + fn deactivate(&mut self, _cx: &ToolContext) -> Vec { + self.clear(); + vec![] + } + + fn hover_ended(&mut self, _cx: &ToolContext) { + if self.press.is_none() { + self.pointer = None; + self.snap.clear(); + } + } + + /// An edit, Undo or Redo made outside the tool, or another document, drops the first point. + fn history_moved(&mut self) { + self.clear(); + } + + fn overlays(&self, cx: &ToolContext) -> Vec { + let mut o = self.snap.guides().to_vec(); + let points = self.points(); + let color = crate::draw2::FEEDBACK; + if let Some((c, r)) = circle_of(&points) { + let path = shapes::ellipse(Rect::new(c.x - r, c.y - r, c.x + r, c.y + r)).to_bezpath(); + // The canvas draws a dashed outline dash by dash along its whole length: a circle longer + // than DASHED_PX on screen is drawn solid instead. + let dashed = std::f64::consts::TAU * r <= cx.tol(DASHED_PX); + o.push(Overlay::Path { path, color, width: 1.0, dashed }); + for p in &points { + o.push(Overlay::Line { a: c, b: *p, color, dashed: false }); + } + let arm = cx.tol(CROSS_PX); + o.push(Overlay::Line { a: c - Vec2::new(arm, 0.0), b: c + Vec2::new(arm, 0.0), color, dashed: false }); + o.push(Overlay::Line { a: c - Vec2::new(0.0, arm), b: c + Vec2::new(0.0, arm), color, dashed: false }); + if let Some(p) = self.pointer.filter(|_| cx.measurement_labels) { + o.push(Overlay::Measure { p: p + Vec2::new(cx.tol(12.0), cx.tol(12.0)), text: format!("D: {}", cx.len(2.0 * r)) }); + } + } else if let Some(p) = self.pointer.filter(|_| too_large(&points)) { + o.push(Overlay::Label { p, text: "Circle too large".into(), color }); + } + for p in self.first.into_iter().chain(self.second()) { + o.push(Overlay::Anchor { p, color, filled: true, size: 6.0 }); + } + o + } + + fn cursor(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> Cursor { + Cursor::Crosshair + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/tools/src/circle/tests.rs b/crates/tools/src/circle/tests.rs new file mode 100644 index 0000000000..e262d242ef --- /dev/null +++ b/crates/tools/src/circle/tests.rs @@ -0,0 +1,352 @@ +use super::*; +use crate::testutil::*; +use vectorcraft_doc::Selection; + +fn ev(kind: PointerKind, (x, y): (f64, f64), mods: Mods) -> PointerEvent { + PointerEvent::new(kind, x, y).with_mods(mods) +} + +fn click(t: &mut CircleTool, cx: &ToolContext, p: (f64, f64)) -> Vec { + let mut acts = t.pointer(cx, &ev(PointerKind::Down, p, Mods::default())); + acts.extend(t.pointer(cx, &ev(PointerKind::Up, p, Mods::default()))); + acts +} + +/// A press at `from`, dragged through `path` and let go at its last point. +fn drag(t: &mut CircleTool, cx: &ToolContext, from: (f64, f64), path: &[(f64, f64)], mods: Mods) -> Vec { + let mut acts = t.pointer(cx, &ev(PointerKind::Down, from, mods)); + for p in path { + acts.extend(t.pointer(cx, &ev(PointerKind::Drag, *p, mods))); + } + let end = path.last().copied().unwrap_or(from); + acts.extend(t.pointer(cx, &ev(PointerKind::Up, end, mods))); + acts +} + +fn circle(points: &[(f64, f64)]) -> Vec { + let pairs: Vec = points.iter().map(|(x, y)| json!([x, y])).collect(); + vec![Action::Exec("shape.circleThroughPoints".into(), json!({ "points": pairs }))] +} + +/// The dashed circle the tool shows: its bounding box. +fn preview(o: &[Overlay]) -> Option { + o.iter().find_map(|o| match o { + Overlay::Path { path, dashed: true, .. } => Some(vectorcraft_geom::Shape::bounding_box(path)), + _ => None, + }) +} + +fn near(a: Rect, b: Rect) -> bool { + [(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(p, q)| (p - q).abs() < 1e-9) +} + +/// A drag from one point to another draws the circle with those two as the ends of a diameter. +#[test] +fn a_drag_draws_the_circle_on_its_diameter() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CircleTool::default(); + assert_eq!(drag(&mut t, &cx, (300.0, 300.0), &[(340.0, 330.0), (380.0, 360.0)], Mods::default()), circle(&[(300.0, 300.0), (380.0, 360.0)])); + assert!(!t.ends_on_escape(&cx) && t.overlays(&cx).is_empty()); +} + +/// A click places the first point and a second click the other end of the diameter. In between, +/// the tool shows the circle through the first point and the pointer, its center cross, its radii +/// and its diameter. +#[test] +fn two_clicks_draw_the_circle_on_their_diameter() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CircleTool::default(); + assert_eq!(click(&mut t, &cx, (300.0, 300.0)), vec![]); + assert!(t.ends_on_escape(&cx) && t.claims_key(&cx, ToolKey::Escape)); + t.pointer(&cx, &ev(PointerKind::Move, (380.0, 360.0), Mods::default())); + let o = t.overlays(&cx); + // Center (340, 330), radius 50. + assert!(near(preview(&o).expect("the circle is shown"), Rect::new(290.0, 280.0, 390.0, 380.0)), "{o:?}"); + let center = Point::new(340.0, 330.0); + let lines = o.iter().filter(|o| matches!(o, Overlay::Line { a, .. } if *a == center)).count(); + assert_eq!(lines, 2, "a radius to each point: {o:?}"); + assert!(o.iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text.starts_with("D: 100"))), "{o:?}"); + let without_labels = ToolContext { measurement_labels: false, ..cx }; + assert!(!t.overlays(&without_labels).iter().any(|o| matches!(o, Overlay::Measure { .. }))); + assert_eq!(click(&mut t, &cx, (380.0, 360.0)), circle(&[(300.0, 300.0), (380.0, 360.0)])); + assert!(!t.ends_on_escape(&cx)); +} + +/// A click, then a press on a second point dragged to a third, draws the circle through the three. +#[test] +fn a_click_and_a_drag_draw_the_circle_through_three_points() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CircleTool::default(); + click(&mut t, &cx, (300.0, 300.0)); + t.pointer(&cx, &ev(PointerKind::Down, (380.0, 300.0), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, (300.0, 360.0), Mods::default())); + // (300, 300), (380, 300) and (300, 360): the right angle stands on the diameter, center + // (340, 330), radius 50. + let o = t.overlays(&cx); + assert!(near(preview(&o).expect("the circle is shown"), Rect::new(290.0, 280.0, 390.0, 380.0)), "{o:?}"); + assert_eq!(o.iter().filter(|o| matches!(o, Overlay::Anchor { .. })).count(), 2, "{o:?}"); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (300.0, 360.0), Mods::default())), circle(&[(300.0, 300.0), (380.0, 300.0), (300.0, 360.0)])); +} + +/// A drag ends where it is let go, also when the release is away from the last drag: from a first +/// press, from a second press, and from a press on the first point. A release within 2 screen +/// points of a second press is still a click and keeps the point of the press. +#[test] +fn a_drag_ends_where_it_is_let_go() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let (down, drag, up) = (PointerKind::Down, PointerKind::Drag, PointerKind::Up); + let mut t = CircleTool::default(); + t.pointer(&cx, &ev(down, (300.0, 300.0), Mods::default())); + t.pointer(&cx, &ev(drag, (380.0, 300.0), Mods::default())); + assert_eq!(t.pointer(&cx, &ev(up, (400.0, 300.0), Mods::default())), circle(&[(300.0, 300.0), (400.0, 300.0)])); + click(&mut t, &cx, (300.0, 300.0)); + t.pointer(&cx, &ev(down, (380.0, 300.0), Mods::default())); + t.pointer(&cx, &ev(drag, (300.0, 340.0), Mods::default())); + assert_eq!(t.pointer(&cx, &ev(up, (300.0, 360.0), Mods::default())), circle(&[(300.0, 300.0), (380.0, 300.0), (300.0, 360.0)])); + click(&mut t, &cx, (300.0, 300.0)); + t.pointer(&cx, &ev(down, (300.0, 300.0), Mods::default())); + t.pointer(&cx, &ev(drag, (300.0, 380.0), Mods::default())); + assert_eq!(t.pointer(&cx, &ev(up, (300.0, 400.0), Mods::default())), circle(&[(300.0, 300.0), (300.0, 400.0)])); + click(&mut t, &cx, (300.0, 300.0)); + t.pointer(&cx, &ev(down, (380.0, 360.0), Mods::default())); + assert_eq!(t.pointer(&cx, &ev(up, (381.0, 360.0), Mods::default())), circle(&[(300.0, 300.0), (380.0, 360.0)])); +} + +/// Three points on one line show no circle, and the release draws nothing and starts afresh. A +/// circle past the canvas is not shown either. +#[test] +fn points_on_one_line_show_no_circle() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CircleTool::default(); + click(&mut t, &cx, (100.0, 100.0)); + t.pointer(&cx, &ev(PointerKind::Down, (200.0, 200.0), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, (300.0, 300.0), Mods::default())); + assert_eq!(preview(&t.overlays(&cx)), None); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (300.0, 300.0), Mods::default())), vec![]); + assert!(!t.ends_on_escape(&cx) && t.overlays(&cx).is_empty()); + assert_eq!(circle_of(&[Point::new(0.0, 0.0), Point::new(4.1e6, 0.0)]), None); + assert_eq!(circle_of(&[Point::new(0.0, 0.0), Point::new(200.0, 0.0), Point::new(100.0, 0.001)]), None); +} + +/// Shift keeps the second point at 45° steps from the first. +#[test] +fn shift_keeps_the_diameter_at_45_degree_steps() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let shift = Mods { shift: true, ..Mods::default() }; + let mut t = CircleTool::default(); + let acts = drag(&mut t, &cx, (300.0, 300.0), &[(400.0, 310.0)], shift); + let [Action::Exec(_, v)] = acts.as_slice() else { panic!("one circle: {acts:?}") }; + let end = &v["points"][1]; + assert!((end[1].as_f64().unwrap() - 300.0).abs() < 1e-9, "level with the first point: {v}"); +} + +/// Alt rounds the diameter to the nearest ruler tick at the current zoom: every 5 pt at 100% and +/// every 2.5 pt at 200% in points, keeping the direction from the first point; for a drag, for a +/// second click and in the preview. +#[test] +fn alt_rounds_the_diameter_to_ruler_ticks() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let alt = Mods { alt: true, ..Mods::default() }; + // The second point of the one circle `acts` draws. + let second = |acts: Vec| { + let [Action::Exec(_, v)] = acts.as_slice() else { panic!("one circle: {acts:?}") }; + Point::new(v["points"][1][0].as_f64().unwrap(), v["points"][1][1].as_f64().unwrap()) + }; + let mut t = CircleTool::default(); + let end = second(drag(&mut t, &cx, (300.0, 300.0), &[(373.0, 300.0)], alt)); + assert!(end.distance(Point::new(375.0, 300.0)) < 1e-9, "{end:?}"); + // (31.2, 41.6) is 52 from the origin, and Alt makes it 50: (30, 40). + click(&mut t, &cx, (0.0, 0.0)); + t.pointer(&cx, &ev(PointerKind::Move, (31.2, 41.6), alt)); + assert!(near(preview(&t.overlays(&cx)).expect("the circle is shown"), Rect::new(-10.0, -5.0, 40.0, 45.0)), "{:?}", t.overlays(&cx)); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Down, (31.2, 41.6), alt)), vec![]); + let end = second(t.pointer(&cx, &ev(PointerKind::Up, (31.2, 41.6), alt))); + assert!(end.distance(Point::new(30.0, 40.0)) < 1e-9, "{end:?}"); + let zoomed = ToolContext { zoom: 2.0, ..cx }; + for (to, want) in [(51.0, 50.0), (51.5, 52.5)] { + let end = second(drag(&mut t, &zoomed, (0.0, 0.0), &[(0.0, to)], alt)); + assert!(end.distance(Point::new(0.0, want)) < 1e-9, "{to}: {end:?}"); + } + // Without Alt the pointer is used as it is. + assert_eq!(drag(&mut t, &cx, (300.0, 300.0), &[(373.0, 300.0)], Mods::default()), circle(&[(300.0, 300.0), (373.0, 300.0)])); +} + +/// Alt rounds only a diameter: a second press dragged to a third point keeps the second point +/// where it was pressed, and a second press 2.6 pt from the first point, which Alt's rounding +/// would move to 5 pt, is still a press on the first point and places nothing. +#[test] +fn alt_leaves_three_points_and_presses_on_the_first_point_alone() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let alt = Mods { alt: true, ..Mods::default() }; + let mut t = CircleTool::default(); + click(&mut t, &cx, (0.0, 0.0)); + assert_eq!(drag(&mut t, &cx, (31.2, 41.6), &[(45.0, 20.0), (60.0, 0.0)], alt), circle(&[(0.0, 0.0), (31.2, 41.6), (60.0, 0.0)])); + click(&mut t, &cx, (300.0, 300.0)); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Down, (302.6, 300.0), alt)), vec![]); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (302.6, 300.0), alt)), vec![]); + assert!(t.ends_on_escape(&cx), "the first point stays"); +} + +/// Three different points on one line show "Circle too large" by the pointer instead of a circle; +/// a pointer back on the first point does not. +#[test] +fn points_on_one_line_say_the_circle_is_too_large() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let label = |t: &CircleTool| { + t.overlays(&cx).iter().find_map(|o| match o { + Overlay::Label { p, text, .. } => Some((*p, text.clone())), + _ => None, + }) + }; + let mut t = CircleTool::default(); + click(&mut t, &cx, (100.0, 100.0)); + t.pointer(&cx, &ev(PointerKind::Down, (200.0, 200.0), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, (300.0, 300.0), Mods::default())); + assert_eq!(label(&t), Some((Point::new(300.0, 300.0), "Circle too large".to_string()))); + t.pointer(&cx, &ev(PointerKind::Drag, (300.0, 290.0), Mods::default())); + assert_eq!(label(&t), None, "a circle is shown"); + t.pointer(&cx, &ev(PointerKind::Drag, (200.0, 200.0), Mods::default())); + assert_eq!(label(&t), None, "the third point is on the second"); + assert!(too_large(&[Point::new(0.0, 0.0), Point::new(4.1e6, 0.0)])); + assert!(!too_large(&[Point::new(0.0, 0.0)]) && !too_large(&[Point::new(1.0, 0.0), Point::new(1.0, 0.0)])); +} + +/// Escape drops the first point; so do a dropped press and an edit made outside the tool. A +/// second click on the first point places nothing. +#[test] +fn escape_and_outside_edits_drop_the_first_point() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CircleTool::default(); + click(&mut t, &cx, (300.0, 300.0)); + assert_eq!(click(&mut t, &cx, (300.5, 300.0)), vec![], "a double-click places one point"); + assert!(t.ends_on_escape(&cx)); + t.key(&cx, ToolKey::Escape, Mods::default()); + assert!(!t.ends_on_escape(&cx) && t.overlays(&cx).is_empty()); + click(&mut t, &cx, (300.0, 300.0)); + t.history_moved(); + assert!(!t.ends_on_escape(&cx)); + click(&mut t, &cx, (300.0, 300.0)); + t.pointer(&cx, &ev(PointerKind::Down, (380.0, 300.0), Mods::default())); + t.drop_press(&cx); + assert!(!t.ends_on_escape(&cx)); + // After all of that, two clicks start a new circle. + click(&mut t, &cx, (10.0, 10.0)); + assert_eq!(click(&mut t, &cx, (30.0, 10.0)), circle(&[(10.0, 10.0), (30.0, 10.0)])); +} + +/// The points snap to Smart Guides: a press near the rectangle's corner anchor at (100, 100) places +/// the point on it. +#[test] +fn points_snap_to_smart_guides() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let mut t = CircleTool::default(); + t.pointer(&cx, &ev(PointerKind::Move, (101.0, 101.5), Mods::default())); + click(&mut t, &cx, (101.0, 101.5)); + assert_eq!(click(&mut t, &cx, (300.0, 100.0)), circle(&[(100.0, 100.0), (300.0, 100.0)])); +} + +/// A click is measured from where the pointer was pressed, not from the point it snapped to: a +/// second press pulled 1.8 pt onto the corner anchor at (100, 100) and moved 0.5 pt before the +/// release still draws the circle on that diameter. +#[test] +fn a_snapped_second_click_is_not_a_drag() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let mut t = CircleTool::default(); + click(&mut t, &cx, (300.0, 100.0)); + t.pointer(&cx, &ev(PointerKind::Down, (101.0, 101.5), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, (101.5, 101.5), Mods::default())); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (101.5, 101.5), Mods::default())), circle(&[(300.0, 100.0), (100.0, 100.0)])); +} + +/// A second press within 3 screen points of the first point is a press on it: dragged out, it +/// draws the circle on the diameter it drags out, whether it landed on the first point or next to +/// it; a press farther away and dragged places the second and third points. +#[test] +fn a_drag_from_the_first_point_draws_the_circle_on_its_diameter() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CircleTool::default(); + click(&mut t, &cx, (300.0, 300.0)); + let acts = drag(&mut t, &cx, (301.0, 300.0), &[(300.0, 350.0), (300.0, 400.0)], Mods::default()); + assert_eq!(acts, circle(&[(300.0, 300.0), (300.0, 400.0)])); + click(&mut t, &cx, (300.0, 300.0)); + let acts = drag(&mut t, &cx, (304.0, 300.0), &[(300.0, 350.0), (300.0, 400.0)], Mods::default()); + assert_eq!(acts, circle(&[(300.0, 300.0), (304.0, 300.0), (300.0, 400.0)])); + click(&mut t, &cx, (300.0, 300.0)); + t.pointer(&cx, &ev(PointerKind::Down, (300.0, 300.0), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, (300.0, 400.0), Mods::default())); + assert!(near(preview(&t.overlays(&cx)).expect("the circle is shown"), Rect::new(250.0, 300.0, 350.0, 400.0)), "{:?}", t.overlays(&cx)); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (300.0, 400.0), Mods::default())), circle(&[(300.0, 300.0), (300.0, 400.0)])); +} + +/// A second press farther than 3 screen points from the first point that snaps to it is a press on +/// it too: the first point is the rectangle's corner anchor at (100, 100), and a press 3.2 pt away +/// snaps back to that anchor. +#[test] +fn a_second_press_that_snaps_to_the_first_point_is_a_press_on_it() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let mut t = CircleTool::default(); + click(&mut t, &cx, (100.0, 100.0)); + t.pointer(&cx, &ev(PointerKind::Down, (103.2, 100.0), Mods::default())); + assert_eq!(t.second(), None, "the press snapped to the first point: {:?}", t.press); + t.pointer(&cx, &ev(PointerKind::Drag, (100.0, 150.0), Mods::default())); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (100.0, 150.0), Mods::default())), circle(&[(100.0, 100.0), (100.0, 150.0)])); +} + +/// A circle more than 50,000 screen points around is previewed solid, not dashed: three points +/// nearly on one line give a radius of about 1,250,000 pt. +#[test] +fn a_huge_circle_is_previewed_solid() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CircleTool::default(); + click(&mut t, &cx, (0.0, 0.0)); + t.pointer(&cx, &ev(PointerKind::Down, (1000.0, 0.0), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, (500.0, 0.1), Mods::default())); + let o = t.overlays(&cx); + assert_eq!(preview(&o), None, "{o:?}"); + assert!(o.iter().any(|o| matches!(o, Overlay::Path { dashed: false, .. })), "{o:?}"); + // At 100% a circle 100 pt across is dashed. + t.pointer(&cx, &ev(PointerKind::Drag, (500.0, 300.0), Mods::default())); + assert!(preview(&t.overlays(&cx)).is_some()); +} + +/// The tool is in the Ellipse tool's group, after the Ellipse tool. +#[test] +fn the_circle_tool_follows_the_ellipse_tool() { + let tool = crate::create(ID); + assert_eq!(tool.id(), ID); + let group = crate::catalog::group_of(ID).unwrap(); + assert_eq!(crate::catalog::group_of("ellipse"), Some(group)); + let ids: Vec<&str> = crate::TOOL_GROUPS[group].iter().map(|t| t.id).collect(); + let ellipse = ids.iter().position(|id| *id == "ellipse").unwrap(); + assert_eq!(ids.get(ellipse + 1), Some(&ID)); +} diff --git a/crates/tools/src/cropimage.rs b/crates/tools/src/cropimage.rs index 13691da613..2e23159e5c 100644 --- a/crates/tools/src/cropimage.rs +++ b/crates/tools/src/cropimage.rs @@ -419,6 +419,24 @@ impl Tool for CropImageTool { }; } + /// `rect` is `[x, y, width, height]`, or null to put the box back where it starts. `ppi`, + /// `reference` and `linked` take the values [`check_options`] takes (the selected image's + /// limit on `ppi` is checked by `tool.setOption`, which knows the selection). + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + if matches!(key, "ppi" | "reference" | "linked") { + return check_options(&serde_json::Map::from_iter([(key.to_string(), value.clone())]), None); + } + if key != "rect" { + return Err(crate::option_check::unknown(key)); + } + let numbers = value.as_array().filter(|a| a.len() == 4).and_then(|a| a.iter().map(Value::as_f64).collect::>>()); + match numbers.as_deref() { + _ if value.is_null() => Ok(()), + Some([x, y, w, h]) if [x, y, w, h].iter().all(|n| n.is_finite()) && *w >= 0.0 && *h >= 0.0 => Ok(()), + _ => Err(format!("`{key}` must be [x, y, width, height]: four finite numbers, width and height not negative")), + } + } + fn deactivate(&mut self, _cx: &ToolContext) -> Vec { self.reset(); vec![] @@ -635,6 +653,15 @@ mod tests { ] { assert_eq!(check_options(&values(v.clone()), Some(36.0)), Err(want.to_string()), "{v}"); } + // The tool takes the same values on its own, without an image's limit. + let t = CropImageTool::default(); + for (k, v) in [("ppi", json!(72)), ("ppi", json!(null)), ("reference", json!(0)), ("linked", json!(true)), ("rect", json!(null))] { + assert_eq!(t.check_option(k, &v), Ok(()), "{k}: {v}"); + } + assert_eq!(t.check_option("reference", &json!(9)), Err("`reference` must be a whole number from 0 to 8, not 9".into())); + assert_eq!(t.check_option("linked", &json!(1)), Err("`linked` must be true or false, not 1".into())); + assert_eq!(t.check_option("ppi", &json!(2401)), Err("`ppi` must be a number from 1 to 2400 or null, not 2401".into())); + assert_eq!(t.check_option("size", &json!(1)), Err("unknown option `size`".into())); } /// An image's own resolution, and the most it can be cropped to. diff --git a/crates/tools/src/cut.rs b/crates/tools/src/cut.rs index 906a632fb3..514e41e4c0 100644 --- a/crates/tools/src/cut.rs +++ b/crates/tools/src/cut.rs @@ -214,6 +214,15 @@ impl Tool for CutTool { _ => {} } } + /// Mirror & Cut's `axis` and `keep`; the other cutting tools have no options. + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + use crate::option_check as c; + match (self.id, key) { + ("mirrorCut", "axis") => c::one_of(key, v, &["vertical", "horizontal", "free"]), + ("mirrorCut", "keep") => c::one_of(key, v, &["left", "right", "top", "bottom"]), + _ => Err(c::unknown(key)), + } + } } #[cfg(test)] diff --git a/crates/tools/src/dimension.rs b/crates/tools/src/dimension.rs index d78850e78e..3e50415434 100644 --- a/crates/tools/src/dimension.rs +++ b/crates/tools/src/dimension.rs @@ -579,6 +579,13 @@ impl Tool for DimensionTool { self.style = o; } } + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + match key { + "mode" => crate::option_check::one_of(key, value, &["linear", "angular", "radial", "radius", "diameter"]), + "style" => DimensionOptions::from_params(value.clone()).map(|_| ()), + _ => Err(crate::option_check::unknown(key)), + } + } fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { self.at = ev.pos; self.shift = ev.mods.shift; diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index 6586cb8586..66cc842a53 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -384,6 +384,18 @@ pub(crate) fn spines(cx: &ToolContext) -> Vec<(NodeId, PathData)> { v } +/// [`spines`] of the blends that are themselves selected, topmost first. When no selected object +/// is a blend, it returns an empty list without walking the document or building any spine. +pub(crate) fn selected_spines(cx: &ToolContext) -> Vec<(NodeId, PathData)> { + let is_blend = |id: &NodeId| cx.doc.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Blend { .. })); + if !cx.selection.objects.iter().any(is_blend) { + return vec![]; + } + let mut v = spines(cx); + v.retain(|(id, _)| cx.selection.contains(*id)); + v +} + /// The spine point under `p`: (blend, anchor, where it is). fn hit_spine_point(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, usize, Point)> { spines(cx).into_iter().find_map(|(id, path)| { @@ -395,7 +407,7 @@ fn hit_spine_point(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, usiz /// The segment of a selected blend's spine passing within `tol` of `p`: (blend, segment, t, whether /// it is straight). pub(crate) fn hit_spine_segment(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, usize, f64, bool)> { - spines(cx).into_iter().filter(|(id, _)| cx.selection.contains(*id)).find_map(|(id, path)| { + selected_spines(cx).into_iter().find_map(|(id, path)| { let (si, seg, t, _, dist) = path.nearest(p)?; (dist <= tol).then(|| (id, seg, t, path.subpaths.get(si).is_some_and(|sp| sp.segment_is_line(seg)))) }) @@ -1348,7 +1360,7 @@ impl DirectSelectionTool { if hit.as_ref().and_then(|h| cx.doc.node(h.leaf)).is_some_and(|n| matches!(n.kind, NodeKind::Text(_))) { return vec![Action::SwitchTool("type".into())]; } - // Outside the isolated art it leaves isolation mode, as with the Selection tool (#4466). + // Outside the isolated art it runs Exit Isolation Mode, as with the Selection tool (#4466). if hit.is_none() && cx.isolation.is_some() { return vec![Action::Exec("object.exitIsolation".into(), json!({}))]; } @@ -1722,7 +1734,7 @@ impl DirectSelectionTool { // marquee that holds none of them drops the points picked before. let mut spined: Option = None; if !self.group { - let found = spines(cx).into_iter().filter(|(id, _)| cx.selection.contains(*id)).find_map(|(id, path)| { + let found = selected_spines(cx).into_iter().find_map(|(id, path)| { let inside: BTreeSet = path.anchors().filter(|(s, _, a)| *s == 0 && r.contains(a.p)).map(|(_, i, _)| i).collect(); (!inside.is_empty()).then_some((id, inside)) }); diff --git a/crates/tools/src/direct/tests.rs b/crates/tools/src/direct/tests.rs index a0fabb9cb8..50244eb260 100644 --- a/crates/tools/src/direct/tests.rs +++ b/crates/tools/src/direct/tests.rs @@ -416,6 +416,141 @@ fn spine_segments_bend_with_the_anchor_point_tool_and_direct_selection() { assert_eq!(t.pointer(&curved, &PointerEvent::new(PointerKind::Up, 160.0, 345.0)), vec![Action::Commit]); } +/// [`selected_spines`] written as a filter of every spine, for comparing results. +fn every_spine_then_selected(cx: &ToolContext) -> Vec<(NodeId, PathData)> { + spines(cx).into_iter().filter(|(id, _)| cx.selection.contains(*id)).collect() +} + +/// [`hit_spine_segment`] written over [`every_spine_then_selected`], for comparing results. +fn hit_spine_segment_of_every_spine(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, usize, f64, bool)> { + every_spine_then_selected(cx).into_iter().find_map(|(id, path)| { + let (si, seg, t, _, dist) = path.nearest(p)?; + (dist <= tol).then(|| (id, seg, t, path.subpaths.get(si).is_some_and(|sp| sp.segment_is_line(seg)))) + }) +} + +/// [`blend_doc`] with a stored spine the keys are spread along (not pinned to anchors), whose +/// layout builds a [`vectorcraft_doc::blend::Spine`], and the id of the plain rectangle beside it. +fn blend_doc_with_spread_spine() -> (vectorcraft_doc::Document, NodeId, NodeId, NodeId) { + let (mut d, g, k1) = blend_doc(); + let Some(rect) = d.layers[0].children().into_iter().flatten().map(|n| n.id).find(|id| *id != g) else { panic!("rectangle") }; + let mut sp = vectorcraft_geom::SubPath::polyline(&[Point::new(110.0, 310.0), Point::new(210.0, 310.0)], false); + sp.bend_segment(0, 0.5, vectorcraft_geom::Vec2::new(0.0, 20.0)); + let Some(NodeKind::Blend { spec, .. }) = d.node_mut(g).map(|n| &mut n.kind) else { panic!("blend") }; + (spec.spine, spec.key_anchors) = (Some(PathData::single(sp)), vec![]); + (d, g, k1, rect) +} + +/// With no blend among the selected objects, the selected-spine check builds no blend spine; with +/// the blend selected it still finds the spine. +#[test] +fn the_selected_spine_check_builds_no_spine_without_a_selected_blend() { + let (d, g, _, rect) = blend_doc_with_spread_spine(); + let p = paint(); + let mut s = Selection::default(); + s.set([rect]); + let c = cx(&d, &s, &p); + let before = vectorcraft_doc::blend::spines_built(); + assert_eq!(hit_spine_segment(&c, Point::new(160.0, 330.0), 4.0), None); + assert!(selected_spines(&c).is_empty()); + assert_eq!(vectorcraft_doc::blend::spines_built() - before, 0, "no spine built"); + s.set([rect, g]); + let c = cx(&d, &s, &p); + assert!(hit_spine_segment(&c, Point::new(160.0, 330.0), 4.0).is_some_and(|h| h.0 == g)); +} + +/// The selected-spine check gives what a filter of every spine gives, for selections with and +/// without the blend, its key, a stale id, and the blend locked, hidden or without a spine. +#[test] +fn the_selected_spine_check_matches_a_filter_of_every_spine() { + let (d, g, k1, rect) = blend_doc_with_spread_spine(); + let p = paint(); + let mut docs = vec![d.clone()]; + for change in 0..3 { + let mut d = d.clone(); + if let Some(n) = d.node_mut(g) { + match change { + 0 => n.locked = true, + 1 => n.visible = false, + _ => { + if let NodeKind::Blend { spec, .. } = &mut n.kind { + spec.no_spine = true; + } + } + } + } + docs.push(d); + } + let selections: [&[NodeId]; 7] = [&[], &[rect], &[g], &[rect, g], &[g, rect], &[k1], &[NodeId(9_999)]]; + for (di, d) in docs.iter().enumerate() { + for ids in selections { + let mut s = Selection::default(); + s.set(ids.iter().copied()); + let c = cx(d, &s, &p); + assert_eq!(selected_spines(&c), every_spine_then_selected(&c), "doc {di}, {ids:?}"); + for x in (90..=230).step_by(5) { + for y in (295..=340).step_by(5) { + let at = Point::new(f64::from(x), f64::from(y)); + assert_eq!(hit_spine_segment(&c, at, 4.0), hit_spine_segment_of_every_spine(&c, at, 4.0), "doc {di}, {ids:?}, {at:?}"); + } + } + } + } +} + +/// Times the selected-spine check on 20,000 paths and 200 blends with curved spines, against the +/// same check written as a filter of every spine, in one process: 500 points, the median of 7 +/// runs. Case A selects one plain path, case B one blend. +#[test] +#[ignore = "manual large-document timing"] +fn selected_spine_check_timing() { + let mut d = vectorcraft_doc::Document::new(4000.0, 4000.0); + let l = d.layers[0].id; + for i in 0..20_000_u32 { + let (x, y) = (f64::from(i % 200) * 20.0, f64::from(i / 200) * 20.0); + let id = d.alloc_id(); + let r = vectorcraft_geom::shapes::rectangle(Rect::new(x, y, x + 10.0, y + 10.0)); + d.insert(Some(l), 0, vectorcraft_doc::Node::path(id, r, vectorcraft_doc::Appearance::default_art())).unwrap(); + } + let first_path = d.layers[0].children().into_iter().flatten().map(|n| n.id).next(); + let mut blends = vec![]; + for i in 0..200_u32 { + let (x, y) = (f64::from(i % 20) * 200.0, 2050.0 + f64::from(i / 20) * 190.0); + let key = |id: NodeId, x: f64| { + let r = vectorcraft_geom::shapes::rectangle(Rect::new(x, y, x + 20.0, y + 20.0)); + std::sync::Arc::new(vectorcraft_doc::Node::path(id, r, vectorcraft_doc::Appearance::default_art())) + }; + let (g, k1, k2) = (d.alloc_id(), d.alloc_id(), d.alloc_id()); + let mut sp = vectorcraft_geom::SubPath::polyline(&[Point::new(x + 10.0, y + 10.0), Point::new(x + 110.0, y + 10.0)], false); + sp.bend_segment(0, 0.5, vectorcraft_geom::Vec2::new(0.0, 20.0)); + let spec = vectorcraft_doc::BlendSpec { spine: Some(PathData::single(sp)), ..Default::default() }; + let b = vectorcraft_doc::Node::new(g, NodeKind::Blend { children: vec![key(k1, x), key(k2, x + 100.0)], spec: Box::new(spec) }); + d.insert(Some(l), 0, b).unwrap(); + blends.push(g); + } + let points: Vec = (0..500_u32).map(|i| Point::new(f64::from(i * 37 % 4000), f64::from(i * 53 % 4000))).collect(); + let p = paint(); + let (Some(plain), Some(&blend)) = (first_path, blends.first()) else { panic!("fixture") }; + for (case, id) in [("A: one plain path selected", plain), ("B: one blend selected", blend)] { + let mut s = Selection::default(); + s.set([id]); + let c = cx(&d, &s, &p); + let (mut old, mut new) = (vec![], vec![]); + for _ in 0..7 { + let t = std::time::Instant::now(); + let a: Vec<_> = points.iter().map(|q| hit_spine_segment_of_every_spine(&c, *q, 4.0)).collect(); + old.push(t.elapsed()); + let t = std::time::Instant::now(); + let b: Vec<_> = points.iter().map(|q| hit_spine_segment(&c, *q, 4.0)).collect(); + new.push(t.elapsed()); + assert_eq!(a, b, "{case}"); + } + old.sort(); + new.sort(); + eprintln!("{case}: 500 checks, median of 7: every spine then filter {:?}, selected spines {:?}", old[3], new[3]); + } +} + /// Shift held while a curved segment is dragged sends `perpendicular`. The test drags a path's /// segment with Direct Selection, and a blend spine's segment with Direct Selection and with the /// Anchor Point tool. diff --git a/crates/tools/src/distort.rs b/crates/tools/src/distort.rs index 30cb1cd4c5..b4cd0a957c 100644 --- a/crates/tools/src/distort.rs +++ b/crates/tools/src/distort.rs @@ -27,7 +27,7 @@ use crate::Tool; pub use liquify::LiquifyTool; pub use perspective::{PerspectiveGridTool, PerspectiveSelectionTool}; pub use puppet::{PinSet, PuppetWarpTool, mesh_for, mesh_input, rest_and_pins, warp_from_rest}; -pub use width::{WidthTool, stroke_owner}; +pub use width::{KEEPS_SIZE, WidthTool, stroke_owner}; /// Create a distortion tool by id (None = not one of ours). pub fn create(id: &str) -> Option> { diff --git a/crates/tools/src/distort/liquify.rs b/crates/tools/src/distort/liquify.rs index 0dc599444f..f93bf3e699 100644 --- a/crates/tools/src/distort/liquify.rs +++ b/crates/tools/src/distort/liquify.rs @@ -829,6 +829,25 @@ impl Tool for LiquifyTool { } } } + /// The options of [`LiquifyParams::from_json`] within its ranges, `diameter` for both sizes, + /// `showBrush`, and `tool` naming this tool. A percentage is a fraction up to 1 and a percent + /// above it. + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "tool" if value.as_str() == Some(self.params.kind.id()) => Ok(()), + "tool" => Err(format!("`tool` must be `{}`", self.params.kind.id())), + "diameter" | "width" | "height" => c::number(key, value, 0.5, 10_000.0), + "angle" => c::finite(key, value), + "intensity" | "horizontal" | "vertical" => c::number(key, value, 0.0, 100.0), + "detail" => c::number(key, value, 1.0, 10.0), + "simplify" => c::number(key, value, 0.0, 100.0), + "rate" => c::number(key, value, -180.0, 180.0), + "complexity" => c::number(key, value, 0.0, 15.0), + "showBrush" | "usePressure" | "simplifyOn" | "affectAnchors" | "affectIn" | "affectOut" => c::boolean(key, value), + _ => Err(c::unknown(key)), + } + } /// The tool claims Escape during an Alt-drag that sizes the brush. fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool { key == ToolKey::Escape && self.sizing.is_some() diff --git a/crates/tools/src/distort/puppet.rs b/crates/tools/src/distort/puppet.rs index 2ca6ec0631..5aae36826e 100644 --- a/crates/tools/src/distort/puppet.rs +++ b/crates/tools/src/distort/puppet.rs @@ -515,6 +515,15 @@ impl Tool for PuppetWarpTool { _ => {} } } + /// `showMesh`, `selectAllPins` and `expand`; `pins` and `selected` are read only. + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "showMesh" | "selectAllPins" => c::boolean(key, value), + "expand" => c::number(key, value, 0.0, 1000.0), + _ => Err(c::unknown(key)), + } + } fn busy(&self) -> bool { self.drag.is_some() } diff --git a/crates/tools/src/distort/width.rs b/crates/tools/src/distort/width.rs index 4ebbac4981..005b8e9473 100644 --- a/crates/tools/src/distort/width.rs +++ b/crates/tools/src/distort/width.rs @@ -19,8 +19,18 @@ //! A compound path's stroke is the compound's: its members are edited through it, and the width //! points show on every subpath of the stroke (one profile runs along each). The cursor says what a //! drag does: add a width point on a stroke, or move or widen the one under it. +//! +//! A stroke drawn with a brush is left alone, as a width profile does not change it: a press or a +//! double-click on it sends no command and shows why in the status bar ([`KEEPS_SIZE`]). Without +//! Shift, the press or double-click deselects the width points, and the cursor over it offers no +//! edit. Its width points selected before it took the brush show no handles, and Delete, +//! Backspace and Escape do what they do with no width points selected. + +use std::cell::Cell; +use std::sync::Arc; use serde_json::json; +use vectorcraft_brush::Brush; use vectorcraft_doc::{Document, NodeId, NodeKind, StrokeLayer}; use vectorcraft_geom::{Point, Vec2}; @@ -107,8 +117,14 @@ pub struct WidthTool { selected: Option<(NodeId, Vec)>, /// The selected width points when the button went down: a dropped press puts them back. before_press: Option<(NodeId, Vec)>, + /// The document's brush library as it was at a revision, so pointer moves and overlays do not + /// parse it again ([`Self::keeps_size`]). + brushes: Cell>, } +/// A document revision and its brush library ([`WidthTool::keeps_size`]). +type BrushesAt = ((u64, u64), Arc>); + /// The object whose stroke path `id` draws with: its compound path, if it is a member of one. pub fn stroke_owner(doc: &Document, id: NodeId) -> NodeId { doc.parent_of(id).filter(|p| doc.node(*p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }))).unwrap_or(id) @@ -132,6 +148,9 @@ fn paths_of(doc: &Document, owner: NodeId) -> Vec { out } +/// The status message for a press on a stroke the tool leaves alone ([`WidthTool::keeps_size`]). +pub const KEEPS_SIZE: &str = "The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile."; + /// Side widths (points) of a stroke at fraction `t`. pub fn sides_at(st: &StrokeLayer, t: f64) -> (f64, f64) { let (l, r) = st.profile.as_ref().map(|p| p.at(t)).unwrap_or((1.0, 1.0)); @@ -139,8 +158,46 @@ pub fn sides_at(st: &StrokeLayer, t: f64) -> (f64, f64) { } impl WidthTool { - /// The stroked path nearest to `p` within reach (stroke half-width + a few pixels). - fn spot_at(cx: &ToolContext, p: Point) -> Option { + /// Does `owner`'s stroke draw with a brush ([`vectorcraft_brush::keeps_brush_size`])? A width + /// profile does not change it, so the tool adds and edits no width points on it. The library is + /// parsed once per document revision. + fn keeps_size(&self, cx: &ToolContext, owner: NodeId) -> bool { + let Some(st) = stroke_of(cx.doc, owner).filter(|s| s.brush.is_some()) else { return false }; + let lib = self + .brushes + .take() + .filter(|(rev, _)| *rev == cx.revision) + .map(|(_, lib)| lib) + .unwrap_or_else(|| Arc::new(vectorcraft_brush::library(cx.doc))); + let keeps = vectorcraft_brush::keeps_brush_size(&lib, st); + self.brushes.set(Some((cx.revision, lib))); + keeps + } + + /// Where a press at `p` lands: the nearest stroke the tool edits ([`Self::spot_at`] without + /// brushed strokes), so a plain stroke under a selected brushed one stays reachable. `Err(true)` + /// when only brushed strokes are within reach, `Err(false)` when no stroke is. + fn edit_spot_at(&self, cx: &ToolContext, p: Point) -> Result { + // `spot_at` asks `skip` only about strokes within reach, so one search tells both apart. + let passed_over = Cell::new(false); + let skip = |owner| { + let keeps = self.keeps_size(cx, owner); + passed_over.set(passed_over.get() || keeps); + keeps + }; + Self::spot_at(cx, p, &skip).ok_or_else(|| passed_over.get()) + } + + /// The hovered stroke while the tool still edits it: a brush applied since the last pointer + /// move takes away its handles and its edit cursor. + fn live_hover(&self, cx: &ToolContext) -> Option { + self.hover.filter(|s| !self.keeps_size(cx, s.owner)) + } + + /// The stroked path nearest to `p` within reach (stroke half-width + a few pixels), passing over + /// the strokes whose owner `skip` returns true for. `skip` is asked only about strokes within + /// reach. + fn spot_at(cx: &ToolContext, p: Point, skip: &dyn Fn(NodeId) -> bool) -> Option { let editable = cx.doc.editable(); let consider = |id: NodeId| -> Option<(f64, Spot)> { if !editable(id) { @@ -156,7 +213,7 @@ impl WidthTool { return None; } let (sub, t, q, tan, d) = nearest_fraction(path, p)?; - if d > reach { + if d > reach || skip(owner) { return None; } let (left, right) = sides_at(st, t); @@ -297,12 +354,22 @@ impl Tool for WidthTool { let p = ev.pos; match ev.kind { PointerKind::Move => { - self.hover = Self::spot_at(cx, p); + // A brushed stroke takes no width points, so the cursor offers no edit over it. + self.hover = self.edit_spot_at(cx, p).ok(); vec![] } PointerKind::TripleClick => vec![], PointerKind::DoubleClick => { - let Some(spot) = Self::spot_at(cx, p) else { return vec![] }; + let spot = match self.edit_spot_at(cx, p) { + Ok(spot) => spot, + Err(false) => return vec![], + Err(true) => { + if !ev.mods.shift { + self.selected = None; + } + return vec![Action::Status(KEEPS_SIZE.into())]; + } + }; let Some((w, _)) = Self::hit(cx, &spot, p) else { self.selected = Some((spot.owner, vec![spot.t])); return vec![Action::Dialog("widthPoint".into(), json!({"id": spot.owner.0, "t": spot.t}))]; @@ -312,11 +379,14 @@ impl Tool for WidthTool { } PointerKind::Down => { self.before_press = self.selected.clone(); - let Some(spot) = Self::spot_at(cx, p) else { - if !ev.mods.shift { - self.selected = None; + let spot = match self.edit_spot_at(cx, p) { + Ok(spot) => spot, + Err(brushed) => { + if !ev.mods.shift { + self.selected = None; + } + return if brushed { vec![Action::Status(KEEPS_SIZE.into())] } else { vec![] }; } - return vec![]; }; let drag = match Self::hit(cx, &spot, p) { Some((w, part)) => { @@ -399,11 +469,12 @@ impl Tool for WidthTool { } /// Delete/Backspace remove the selected width points and Escape deselects them; with none /// selected the keys do what they do with other tools (Clear deletes the selected objects, and - /// Escape leaves isolation mode, for one). + /// Escape leaves isolation mode, for one). Width points of a brushed stroke, which show no + /// handles, count as none selected. fn claims_key(&self, cx: &ToolContext, key: ToolKey) -> bool { matches!(key, ToolKey::Delete | ToolKey::Backspace | ToolKey::Escape) && self.drag.is_none() - && self.selected.as_ref().is_some_and(|(id, _)| !self.selected_indices(cx, *id).is_empty()) + && self.selected.as_ref().is_some_and(|(id, _)| !self.selected_indices(cx, *id).is_empty() && !self.keeps_size(cx, *id)) } /// A dropped press ends the drag, and the width points selected when the button went down are /// selected again. @@ -426,12 +497,16 @@ impl Tool for WidthTool { return vec![]; } self.selected = None; + if self.keeps_size(cx, id) { + return vec![]; + } vec![Action::Exec("stroke.widthPoint.remove".into(), json!({"id": id.0, "indices": indices}))] } fn overlays(&self, cx: &ToolContext) -> Vec { let mut out = vec![]; let r = cx.tol(4.0); - let focus = self.drag.as_ref().map(|d| d.spot).or(self.hover); + let hover = self.live_hover(cx); + let focus = self.drag.as_ref().map(|d| d.spot).or(hover); // Every subpath's width points of the stroke under the pointer, and of the selected ones'. let show = |owner: NodeId, out: &mut Vec| { for w in Self::all_points(cx, owner) { @@ -445,8 +520,11 @@ impl Tool for WidthTool { if let Some(s) = focus { show(s.owner, &mut out); } + // Width points selected before their stroke took a brush show no handles: the tool no + // longer edits them. if let Some((owner, _)) = &self.selected && focus.is_none_or(|s| s.owner != *owner) + && !self.keeps_size(cx, *owner) { show(*owner, &mut out); } @@ -457,7 +535,7 @@ impl Tool for WidthTool { if cx.measurement_labels { out.push(Overlay::Measure { p: q + d.spot.n * (d.left + r * 3.0), text: format!("W: {}", cx.stroke_unit.readout(d.left + d.right)) }); } - } else if let Some(h) = &self.hover { + } else if let Some(h) = &hover { out.push(Overlay::Line { a: h.p + h.n * h.left, b: h.p - h.n * h.right, color: BLUE, dashed: true }); out.push(Overlay::Path { path: diamond(h.p, r), color: BLUE, width: 1.0, dashed: false }); } @@ -468,7 +546,7 @@ impl Tool for WidthTool { return Cursor::WidthPoint; } // The stroke under the pointer, as the last move found it (no search every frame). - match self.hover { + match self.live_hover(cx) { Some(spot) if Self::hit(cx, &spot, p).is_some() => Cursor::WidthPoint, Some(_) => Cursor::WidthAdd, None => Cursor::Width, @@ -538,6 +616,169 @@ mod tests { assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 150.0, 220.0)), vec![Action::Commit]); } + /// A stroke drawn with a brush of the library (the 3 pt. Round calligraphic brush) is left + /// alone: a press or a double-click sends no command and says why. A brush name the library + /// lacks draws a plain stroke, which the tool edits as usual. + #[test] + fn brushed_stroke_is_left_alone_with_a_reason() { + let (mut d, id) = doc_line(); + d.node_mut(id).unwrap().appearance.stroke_mut().unwrap().brush = Some("3 pt. Round".into()); + let (s, p) = (Selection::default(), paint()); + let mut t = WidthTool::default(); + let c = cx(&d, &s, &p); + let refused = vec![Action::Status(KEEPS_SIZE.into())]; + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 201.0)), refused); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 150.0, 220.0)), vec![], "no drag began"); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 150.0, 220.0)), vec![]); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::DoubleClick, 150.0, 201.0)), refused); + + d.node_mut(id).unwrap().appearance.stroke_mut().unwrap().brush = Some("No Such Brush".into()); + let c = cx(&d, &s, &p); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 201.0)), vec![Action::Begin("Width Point".into())]); + } + + /// A selected brushed stroke lying on a plain one does not hide the plain one: a press there + /// edits the plain stroke. + #[test] + fn a_plain_stroke_under_a_selected_brushed_one_stays_reachable() { + let (mut d, _) = doc_line(); + let l = d.layers[0].id; + let brushed = d.alloc_id(); + let mut ap = Appearance::default_art(); + let st = ap.stroke_mut().unwrap(); + st.width = 10.0; + st.brush = Some("3 pt. Round".into()); + let path = PathData::single(SubPath::polyline(&[Point::new(100.0, 200.0), Point::new(300.0, 200.0)], false)); + d.insert(Some(l), 0, Node::path(brushed, path, ap)).unwrap(); + let (s, p) = (Selection { objects: vec![brushed], ..Default::default() }, paint()); + let mut t = WidthTool::default(); + let c = cx(&d, &s, &p); + t.pointer(&c, &PointerEvent::new(PointerKind::Move, 150.0, 201.0)); + assert_eq!(t.cursor(&c, Point::new(150.0, 201.0), Mods::default()), Cursor::WidthAdd); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 201.0)), vec![Action::Begin("Width Point".into())]); + } + + /// A brush applied to the hovered stroke, with the pointer still, takes away its handles and its + /// edit cursor before the next pointer move. + #[test] + fn a_brush_applied_under_a_still_pointer_takes_away_the_hover() { + let (mut d, id) = doc_line(); + let (s, p) = (Selection::default(), paint()); + let mut t = WidthTool::default(); + let c = cx(&d, &s, &p); + t.pointer(&c, &PointerEvent::new(PointerKind::Move, 150.0, 201.0)); + assert_eq!(t.cursor(&c, Point::new(150.0, 201.0), Mods::default()), Cursor::WidthAdd); + assert!(!t.overlays(&c).is_empty()); + d.node_mut(id).unwrap().appearance.stroke_mut().unwrap().brush = Some("3 pt. Round".into()); + let c = ToolContext { revision: (0, 1), ..cx(&d, &s, &p) }; + assert_eq!(t.cursor(&c, Point::new(150.0, 201.0), Mods::default()), Cursor::Width); + assert!(t.overlays(&c).is_empty()); + } + + /// The brush library is read once per document revision: a brush added to the library under a + /// new revision is seen, so a stroke naming it is then left alone. + #[test] + fn a_brush_added_to_the_library_is_seen_at_the_next_revision() { + let (mut d, id) = doc_line(); + d.node_mut(id).unwrap().appearance.stroke_mut().unwrap().brush = Some("Added Later".into()); + let (s, p) = (Selection::default(), paint()); + let mut t = WidthTool::default(); + let c = cx(&d, &s, &p); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 201.0)), vec![Action::Begin("Width Point".into())]); + t.pointer(&c, &PointerEvent::new(PointerKind::Up, 150.0, 201.0)); + let mut lib = vectorcraft_brush::library(&d); + let mut added = lib[0].clone(); + added.name = "Added Later".into(); + lib.push(added); + vectorcraft_brush::store(&mut d, &lib); + let c = ToolContext { revision: (0, 1), ..cx(&d, &s, &p) }; + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 201.0)), vec![Action::Status(KEEPS_SIZE.into())]); + } + + /// Width points selected before the stroke took a brush show no handles and count as none + /// selected: the tool leaves Delete and Escape to the app, and removes none. + #[test] + fn delete_leaves_the_width_points_of_a_brushed_stroke() { + let (mut d, id) = doc_line(); + d.node_mut(id).unwrap().appearance.stroke_mut().unwrap().profile = + Some(WidthProfile { points: vec![(0.0, 1.0, 1.0), (0.5, 2.0, 2.0), (1.0, 1.0, 1.0)] }); + let (s, p) = (Selection::default(), paint()); + let mut t = WidthTool::default(); + let c = cx(&d, &s, &p); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, 200.0, 200.0)); + t.pointer(&c, &PointerEvent::new(PointerKind::Up, 200.0, 200.0)); + assert!(t.claims_key(&c, ToolKey::Delete), "a width point is selected"); + assert!(!t.overlays(&c).is_empty(), "the selected point shows its handles"); + d.node_mut(id).unwrap().appearance.stroke_mut().unwrap().brush = Some("3 pt. Round".into()); + let c = ToolContext { revision: (0, 1), ..cx(&d, &s, &p) }; + assert!(t.overlays(&c).is_empty(), "no handles show on a stroke the tool no longer edits"); + for key in [ToolKey::Delete, ToolKey::Backspace, ToolKey::Escape] { + assert!(!t.claims_key(&c, key), "{key:?} is the app's"); + } + assert_eq!(t.key(&c, ToolKey::Delete, Mods::default()), vec![]); + assert!(t.selected.is_none()); + } + + /// With Shift held, a press or a double-click on a brushed stroke keeps the width points of + /// another stroke selected, as a Shift-press that misses every stroke does. + #[test] + fn shift_on_a_brushed_stroke_keeps_the_selected_width_points() { + let (mut d, _) = doc_three_points(); + let l = d.layers[0].id; + let other = d.alloc_id(); + let mut ap = Appearance::default_art(); + let st = ap.stroke_mut().unwrap(); + st.width = 10.0; + st.brush = Some("3 pt. Round".into()); + let path = PathData::single(SubPath::polyline(&[Point::new(100.0, 400.0), Point::new(300.0, 400.0)], false)); + d.insert(Some(l), 0, Node::path(other, path, ap)).unwrap(); + let (s, p) = (Selection::default(), paint()); + let shift = Mods { shift: true, ..Default::default() }; + let mut t = WidthTool::default(); + let c = cx(&d, &s, &p); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, 200.0, 200.0)); + t.pointer(&c, &PointerEvent::new(PointerKind::Up, 200.0, 200.0)); + let kept = t.selected.clone(); + assert!(kept.is_some(), "the plain stroke's width point is selected"); + for kind in [PointerKind::Down, PointerKind::DoubleClick] { + assert_eq!(t.pointer(&c, &ev(kind, 200.0, 401.0, shift)), vec![Action::Status(KEEPS_SIZE.into())]); + assert_eq!(t.selected, kept, "{kind:?} with Shift keeps the selection"); + } + assert_eq!(t.pointer(&c, &ev(PointerKind::DoubleClick, 200.0, 401.0, Mods::default())), vec![Action::Status(KEEPS_SIZE.into())]); + assert!(t.selected.is_none(), "a double-click without Shift deselects"); + } + + /// A press on a brushed stroke deselects the width points of another stroke, as a press that + /// misses every stroke does, so a later Delete does not edit that other stroke. The cursor over + /// a brushed stroke offers no edit. + #[test] + fn a_press_on_a_brushed_stroke_deselects_and_its_cursor_offers_no_edit() { + let (mut d, _) = doc_three_points(); + let l = d.layers[0].id; + let other = d.alloc_id(); + let mut ap = Appearance::default_art(); + let st = ap.stroke_mut().unwrap(); + st.width = 10.0; + st.brush = Some("3 pt. Round".into()); + let path = PathData::single(SubPath::polyline(&[Point::new(100.0, 400.0), Point::new(300.0, 400.0)], false)); + d.insert(Some(l), 0, Node::path(other, path, ap)).unwrap(); + let (s, p) = (Selection::default(), paint()); + let mut t = WidthTool::default(); + let c = cx(&d, &s, &p); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, 200.0, 200.0)); + t.pointer(&c, &PointerEvent::new(PointerKind::Up, 200.0, 200.0)); + assert!(t.claims_key(&c, ToolKey::Delete), "the plain stroke's width point is selected"); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 200.0, 401.0)), vec![Action::Status(KEEPS_SIZE.into())]); + t.pointer(&c, &PointerEvent::new(PointerKind::Up, 200.0, 401.0)); + assert!(!t.claims_key(&c, ToolKey::Delete), "nothing is left to delete"); + assert_eq!(t.key(&c, ToolKey::Delete, Mods::default()), vec![]); + + t.pointer(&c, &PointerEvent::new(PointerKind::Move, 200.0, 401.0)); + assert_eq!(t.cursor(&c, Point::new(200.0, 401.0), Mods::default()), Cursor::Width); + t.pointer(&c, &PointerEvent::new(PointerKind::Move, 220.0, 201.0)); + assert_eq!(t.cursor(&c, Point::new(220.0, 201.0), Mods::default()), Cursor::WidthAdd, "the plain stroke still offers one"); + } + #[test] fn alt_drag_changes_one_side_and_move_slides() { let (mut d, id) = doc_line(); diff --git a/crates/tools/src/draw2/anchor.rs b/crates/tools/src/draw2/anchor.rs index 58664704ad..3389746f2d 100644 --- a/crates/tools/src/draw2/anchor.rs +++ b/crates/tools/src/draw2/anchor.rs @@ -168,7 +168,7 @@ impl AnchorTool { | State::SpineHandle { id, .. } | State::Reshape { id, .. } => Some((cx.selection.contains(id), cx.doc.index_path(id))), }; - for (id, path) in crate::direct::spines(cx).into_iter().filter(|(id, _)| cx.selection.contains(*id)) { + for (id, path) in crate::direct::selected_spines(cx) { let candidate = if let Some((ai, out)) = Self::spine_handle(cx, &path, p, point) { State::SpineHandle { id, ai, out, start: p, began: false } } else if let Some(ai) = Self::spine_point(&path, p, point) { @@ -192,7 +192,7 @@ impl AnchorTool { /// tool switch. Show the handles on selected blends so they stay editable. fn spine_overlays(cx: &ToolContext) -> Vec { let mut out = vec![]; - for (id, path) in crate::direct::spines(cx).into_iter().filter(|(id, _)| cx.selection.contains(*id)) { + for (id, path) in crate::direct::selected_spines(cx) { let anchors: Vec<_> = path.anchors().filter(|(si, _, _)| *si == 0).collect(); if !cx.handles_multiple && anchors.len() > 1 { continue; diff --git a/crates/tools/src/draw2/family.rs b/crates/tools/src/draw2/family.rs index 8bdbb4db0f..87c11abba9 100644 --- a/crates/tools/src/draw2/family.rs +++ b/crates/tools/src/draw2/family.rs @@ -529,11 +529,32 @@ impl Tool for FamilyTool { } } } + /// The options the tool shows ([`Self::options`]): those of the arc, the spiral or the grid. + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + use crate::option_check as c; + if self.options().get(key).is_none() { + return Err(c::unknown(key)); + } + let skew = vectorcraft_geom::shapes::GRID_SKEW_MAX; + match key { + "lengthX" | "lengthY" => c::number(key, v, 1e-9, 1e6), + "width" | "height" => c::positive(key, v, 1e6), + "reference" => c::whole(key, v, 0, 8), + "baseAlong" => c::one_of(key, v, &["x", "y", "X", "Y"]), + "slope" => c::number(key, v, -100.0, 100.0), + "decay" => c::number(key, v, 5.0, 99.99), + "segments" => c::whole(key, v, 2, 1000), + "rows" | "concentric" | "columns" | "radial" => c::whole(key, v, 0, 999), + "rowSkew" | "concentricSkew" | "columnSkew" | "radialSkew" => c::number(key, v, -skew, skew), + _ => c::boolean(key, v), + } + } } -/// Arc segment length from a dialog or preference value. +/// Arc segment length from a dialog or preference value, from 1e-9 to 1e6 pt (as the option check +/// takes it). fn arc_length(v: &Value, current: f64) -> f64 { - v.as_f64().filter(|n| n.is_finite()).map_or(current, |n| n.abs().max(1e-9)) + v.as_f64().filter(|n| n.is_finite()).map_or(current, |n| n.abs().clamp(1e-9, 1e6)) } /// A grid's Default Size side from option value `v`: a finite positive length (at most 1e6 pt), @@ -578,6 +599,28 @@ mod tests { } } + /// A number `tool.setOption` takes is kept as given, and a number the tool would keep as + /// another value is refused: `decay` past 99.99 is an error. + #[test] + fn family_tools_keep_the_numbers_their_option_check_takes() { + let tries = [-1e9, -150.0, -100.0, -1.0, 0.0, 1e-12, 0.5, 1.0, 2.0, 5.0, 8.0, 99.99, 100.0, 120.0, 150.0, 999.0, 1000.0, 1e6, 1e9]; + for id in ["arc", "spiral", "rectangularGrid", "polarGrid"] { + let defaults = FamilyTool::new(id).options(); + for (k, _) in defaults.as_object().into_iter().flatten().filter(|(_, v)| v.is_number()) { + for n in tries { + let mut t = FamilyTool::new(id); + if t.check_option(k, &json!(n)).is_ok() { + t.set_option(k, &json!(n)); + assert_eq!(t.options()[k].as_f64(), Some(n), "{id} `{k}` = {n}"); + } + } + } + } + let t = FamilyTool::new("spiral"); + assert_eq!(t.check_option("decay", &json!(120.0)).err(), Some("`decay` must be a number from 5 to 99.99".into())); + assert!(t.check_option("decay", &json!(99.99)).is_ok()); + } + #[test] fn normalized_spiral_decay_preserves_existing_capped_paths_within_roundoff() { for requested in [100.0, 150.0] { @@ -1067,6 +1110,10 @@ mod tests { "fillArc": true, }) ); + // A length past 1e6 pt is kept at 1e6, which `tool.setOption` takes back. + t.set_option("lengthX", &json!(-1e9)); + assert_eq!(t.options()["lengthX"], json!(1e6)); + assert_eq!(t.check_option("lengthX", &t.options()["lengthX"]), Ok(())); } /// While an arc is dragged out, C switches it between open and closed, F switches its base diff --git a/crates/tools/src/draw2/gesture.rs b/crates/tools/src/draw2/gesture.rs index 502fd16dbd..75f0fde6d6 100644 --- a/crates/tools/src/draw2/gesture.rs +++ b/crates/tools/src/draw2/gesture.rs @@ -2059,6 +2059,32 @@ impl Tool for GestureTool { _ => {} } } + /// The options the tool shows ([`Self::options`]), and the Smooth tool's Fidelity that the + /// Pencil, Paintbrush and Blob Brush smooth with while Alt is held (`smoothFidelity`). + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + use crate::option_check as c; + let smooth_store = key == "smoothFidelity" && matches!(self.id, "pencil" | "paintbrush" | "blobBrush"); + if !smooth_store && self.options().get(key).is_none() { + return Err(c::unknown(key)); + } + match key { + "fidelity" => c::number(key, v, super::min_fidelity(self.id), 100.0), + "smoothFidelity" => c::number(key, v, super::min_fidelity("smooth"), 100.0), + "size" => c::number(key, v, 0.1, 1000.0), + "sizeVariation" => c::number(key, v, 0.0, 1000.0), + "angle" => c::number(key, v, -180.0, 180.0), + "roundness" => c::number(key, v, if self.id == "blobBrush" { 0.0 } else { 1.0 }, 100.0), + "editWithin" | "closeWithin" => c::number(key, v, 0.0, 100.0), + "angleVariation" => c::number(key, v, 0.0, 180.0), + "roundnessVariation" => c::number(key, v, 0.0, 100.0), + // The Blob Brush's Size is Fixed or Pressure; the Eraser's Angle, Roundness and Size + // take any mode (`set_option`). + "sizeMode" if self.id != "eraser" => c::one_of(key, v, &[Variation::Fixed.id(), Variation::Pressure.id()]), + "sizeMode" | "angleMode" | "roundnessMode" => c::one_of(key, v, &Variation::ALL.map(Variation::id)), + "fill" | "altSmooth" | "livePreview" | "liveFit" | "keepSelected" | "mergeOnlySelection" => c::boolean(key, v), + _ => Err(c::unknown(key)), + } + } } #[cfg(test)] diff --git a/crates/tools/src/draw2/gesture/tests.rs b/crates/tools/src/draw2/gesture/tests.rs index 550e7f9d32..3ebc50cd02 100644 --- a/crates/tools/src/draw2/gesture/tests.rs +++ b/crates/tools/src/draw2/gesture/tests.rs @@ -3087,6 +3087,20 @@ fn the_eraser_tip_follows_its_variation_modes() { [&o["angleMode"], &o["angleVariation"], &o["roundnessMode"], &o["roundnessVariation"], &o["sizeMode"], &o["sizeVariation"]], [&json!("rotation"), &json!(90.0), &json!("random"), &json!(10.0), &json!("tilt"), &json!(8.0)] ); + // `tool.setOption` takes back what the tool reports, and refuses a mode or Variation it does + // not take. + let reported = o.as_object().unwrap().clone(); + assert_eq!(t.check_options(&reported), Ok(())); + for mode in Variation::ALL { + for k in ["sizeMode", "angleMode", "roundnessMode"] { + assert_eq!(t.check_option(k, &json!(mode.id())), Ok(()), "{k} {mode:?}"); + } + } + let modes = "must be one of `fixed`, `random`, `pressure`, `tilt`, `bearing`, `rotation`"; + assert_eq!(t.check_option("angleMode", &json!("wheel")), Err(format!("`angleMode` {modes}"))); + assert_eq!(t.check_option("angleVariation", &json!(181)), Err("`angleVariation` must be a number from 0 to 180".into())); + assert_eq!(t.check_option("roundnessVariation", &json!(500)), Err("`roundnessVariation` must be a number from 0 to 100".into())); + assert_eq!(GestureTool::new("blobBrush").check_option("sizeMode", &json!("tilt")), Err("`sizeMode` must be one of `fixed`, `pressure`".into())); // A mode it does not have leaves the mode as it was; a Variation is kept within its range. t.set_option("angleMode", &json!("wheel")); t.set_option("roundnessVariation", &json!(500)); diff --git a/crates/tools/src/extra.rs b/crates/tools/src/extra.rs index 4c6a6c6d45..5eed055eaa 100644 --- a/crates/tools/src/extra.rs +++ b/crates/tools/src/extra.rs @@ -400,6 +400,18 @@ impl Tool for FlareTool { } } } + /// The switches and [`FLARE_OPTIONS`] within their ranges, the counts whole. + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + use crate::option_check as c; + if matches!(key, "raysOn" | "ringsOn") { + return c::boolean(key, v); + } + let Some(&(_, _, lo, hi)) = FLARE_OPTIONS.iter().find(|(k, ..)| *k == key) else { return Err(c::unknown(key)) }; + if is_count(key) && v.as_f64().is_none_or(|n| n.fract() != 0.0) { + return Err(format!("`{key}` must be a whole number from {lo} to {hi}")); + } + c::number(key, v, lo, hi) + } } /// Where a Reshape press landed on a selected path. diff --git a/crates/tools/src/input.rs b/crates/tools/src/input.rs index 5362147b97..9fa2eab661 100644 --- a/crates/tools/src/input.rs +++ b/crates/tools/src/input.rs @@ -214,8 +214,15 @@ pub enum Action { Exec(String, Value), /// Ask the UI to open a dialog (e.g. click with the Rectangle tool → size dialog). Dialog(String, Value), + /// Ask the UI to show and select a panel (e.g. a double-click on a corner widget with a shape + /// tool → Transform). + Panel(String), /// Switch to another tool (e.g. after placing a text frame). SwitchTool(String), /// Call the tool's `notify` after the preceding actions ran (e.g. to pick up a created object). Notify(String), + /// Show this English message in the status bar (e.g. why a Shape Builder gesture built + /// nothing); an empty message clears the status bar. It changes nothing in the document and + /// records no undo step. + Status(String), } diff --git a/crates/tools/src/intertwine.rs b/crates/tools/src/intertwine.rs index 7ea841b4a7..35a0f1747d 100644 --- a/crates/tools/src/intertwine.rs +++ b/crates/tools/src/intertwine.rs @@ -364,6 +364,10 @@ impl Tool for IntertwineTool { } } + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + if key == "prev" { crate::option_check::string_or_null(key, value) } else { Err(crate::option_check::unknown(key)) } + } + fn busy(&self) -> bool { self.dragging } diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index 7526717665..43e59de7da 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -12,6 +12,7 @@ pub mod bbox; pub mod blendwidget; pub mod builder; pub mod catalog; +pub mod circle; pub mod corners; pub mod cropimage; pub mod cut; @@ -27,6 +28,7 @@ pub mod meshedit; pub mod mirror; pub mod nineslice; pub mod objects_on_path; +pub mod option_check; pub mod params; pub mod pathtype; pub mod pen; @@ -160,6 +162,18 @@ pub trait Tool: Send { Value::Null } fn set_option(&mut self, _key: &str, _value: &Value) {} + /// Whether [`Self::set_option`] takes `value` for option `key` as it is: an error names an + /// option the tool doesn't have, a value of the wrong type or a number out of range + /// (`tool.setOption` checks every option it is given with this before it sets any). A tool + /// without options takes none. + fn check_option(&self, key: &str, _value: &Value) -> Result<(), String> { + Err(option_check::unknown(key)) + } + /// Whether [`Self::set_option`] takes all of `values`, set together in one call: by default + /// each one checked on its own with [`Self::check_option`]. + fn check_options(&self, values: &serde_json::Map) -> Result<(), String> { + values.iter().try_for_each(|(k, v)| self.check_option(k, v)) + } /// Is an interaction in progress (drag, open pen path)? fn busy(&self) -> bool { false @@ -272,8 +286,8 @@ pub trait Tool: Send { false } /// What the Info panel shows for the tool as it is now: the drag in progress (a move of the - /// selection, a gradient vector, a Scale, Rotate, Reflect or Shear tool drag), or the - /// Paintbrush's brush. None for a tool with nothing of its own to show. + /// selection, a gradient vector, a handle the Pen pulls out, a Scale, Rotate, Reflect or Shear + /// tool drag), or the Paintbrush's brush. None for a tool with nothing of its own to show. fn readout(&self, _cx: &ToolContext) -> Option { None } @@ -282,7 +296,8 @@ pub trait Tool: Send { vec![] } /// The tool, already active, is chosen again (its toolbar button, its shortcut, `tool.select`). - /// Most tools keep their state; the Blend tool finishes the blend it is adding to. + /// Most tools keep their state; the Blend tool finishes the blend it is adding to, and the Pen + /// ends the path it is drawing. fn chosen_again(&mut self, _cx: &ToolContext) -> Vec { vec![] } @@ -364,6 +379,7 @@ pub fn create(id: &str) -> Box { "dimension" => Box::new(dimension::DimensionTool::default()), "type" | "areaType" | "typeOnPath" | "verticalType" | "verticalAreaType" | "verticalTypeOnPath" => Box::new(text::TypeTool::new(id)), "rectangle" | "roundedRectangle" | "ellipse" | "polygon" | "star" | "lineSegment" => Box::new(shape::ShapeTool::new(id)), + circle::ID => Box::new(circle::CircleTool::default()), // Not in the toolbar: `file.place.queue` loads it. "place" => Box::new(place::PlaceTool::default()), other => symbolism::create(other) diff --git a/crates/tools/src/objects_on_path.rs b/crates/tools/src/objects_on_path.rs index fe956691e1..dbb6f8bfdf 100644 --- a/crates/tools/src/objects_on_path.rs +++ b/crates/tools/src/objects_on_path.rs @@ -1106,6 +1106,15 @@ impl Tool for ObjectsOnPathTool { } } + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "pivot" => c::whole(key, value, 0, 8), + "rotate" => c::number(key, value, -360.0, 360.0), + _ => Err(c::unknown(key)), + } + } + fn busy(&self) -> bool { self.press.is_some() || self.rotating.is_some() || self.spacing.is_some() || self.moving.is_some() || self.member.is_some() } diff --git a/crates/tools/src/option_check.rs b/crates/tools/src/option_check.rs new file mode 100644 index 0000000000..dd26fa28f0 --- /dev/null +++ b/crates/tools/src/option_check.rs @@ -0,0 +1,245 @@ +//! Checks of tool option values ([`crate::Tool::check_option`]) and of `tool.setOption`'s +//! parameters. Each error names the option and what it takes. + +use serde_json::{Map, Value}; + +use crate::Tool; + +/// The error for an option the tool doesn't have. +pub fn unknown(key: &str) -> String { + format!("unknown option `{key}`") +} + +/// `v` is a finite number from `lo` to `hi`. +pub fn number(key: &str, v: &Value, lo: f64, hi: f64) -> Result<(), String> { + match v.as_f64() { + Some(n) if n.is_finite() && (lo..=hi).contains(&n) => Ok(()), + _ => Err(format!("`{key}` must be a number from {lo} to {hi}")), + } +} + +/// `v` is a finite number. +pub fn finite(key: &str, v: &Value) -> Result<(), String> { + match v.as_f64() { + Some(n) if n.is_finite() => Ok(()), + _ => Err(format!("`{key}` must be a finite number")), + } +} + +/// `v` is a finite number above 0 and at most `hi`. +pub fn positive(key: &str, v: &Value, hi: f64) -> Result<(), String> { + match v.as_f64() { + Some(n) if n > 0.0 && n <= hi => Ok(()), + _ => Err(format!("`{key}` must be a number above 0 and at most {hi}")), + } +} + +/// `v` is a whole number (written without a fraction) from `lo` to `hi`. +pub fn whole(key: &str, v: &Value, lo: u64, hi: u64) -> Result<(), String> { + match v.as_u64() { + Some(n) if (lo..=hi).contains(&n) => Ok(()), + _ => Err(format!("`{key}` must be a whole number from {lo} to {hi}")), + } +} + +/// `v` is true or false. +pub fn boolean(key: &str, v: &Value) -> Result<(), String> { + if v.is_boolean() { Ok(()) } else { Err(format!("`{key}` must be true or false")) } +} + +/// `v` is one of the strings `choices`. +pub fn one_of(key: &str, v: &Value, choices: &[&str]) -> Result<(), String> { + if v.as_str().is_some_and(|s| choices.contains(&s)) { + Ok(()) + } else { + let list: Vec = choices.iter().map(|c| format!("`{c}`")).collect(); + Err(format!("`{key}` must be one of {}", list.join(", "))) + } +} + +/// `v` is a string, or null. +pub fn string_or_null(key: &str, v: &Value) -> Result<(), String> { + if v.is_string() || v.is_null() { Ok(()) } else { Err(format!("`{key}` must be a string or null")) } +} + +/// What `tool.setOption {tool?, key?, value?, values?}` sets: the tool named (none: the active +/// tool) and the options, `key` and `value` among `values`. A parameter of the wrong type, a +/// `value` without a `key` or a `key` without a `value`, and an option given both as `key` and in +/// `values` are errors, and so are parameters that are not an object. With none of `key` and +/// `values`, or with no parameters (null), the options are empty: the command reads them. +pub fn set_option_params(p: &Value) -> Result<(Option<&str>, Map), String> { + if !p.is_object() && !p.is_null() { + return Err(format!("the params must be an object, not {}", shown(p))); + } + let tool = match p.get("tool") { + None => None, + Some(t) => Some(t.as_str().ok_or("`tool` must be a tool id")?), + }; + let mut values = match p.get("values") { + None => Map::new(), + Some(v) => v.as_object().cloned().ok_or("`values` must be an object")?, + }; + match (p.get("key"), p.get("value")) { + (None, None) => {} + (Some(k), v) => { + let k = k.as_str().ok_or("`key` must be a string")?; + let v = v.ok_or_else(|| format!("`value` is missing for `{k}`"))?; + if values.contains_key(k) { + return Err(format!("`{k}` is given both as `key` and in `values`")); + } + values.insert(k.to_string(), v.clone()); + } + (None, Some(_)) => return Err("`value` needs a `key`".into()), + } + Ok((tool, values)) +} + +/// The JSON text of `v` as a parameter error shows it: cut to 40 characters, with `…` when it was +/// longer. The text is written only up to the cut. +fn shown(v: &Value) -> String { + struct Cut { + text: String, + left: usize, + } + impl std::fmt::Write for Cut { + fn write_str(&mut self, s: &str) -> std::fmt::Result { + for c in s.chars() { + if self.left == 0 { + return Err(std::fmt::Error); + } + self.left -= 1; + self.text.push(c); + } + Ok(()) + } + } + let mut out = Cut { text: String::new(), left: 40 }; + if std::fmt::Write::write_fmt(&mut out, format_args!("{v}")).is_err() { + out.text.push('…'); + } + out.text +} + +/// Check every one of `values` as an option of `tool` ([`Tool::check_options`]), before any is +/// set: the first one the tool doesn't take is an error that names the tool. +pub fn check_values(tool: &dyn Tool, values: &Map) -> Result<(), String> { + tool.check_options(values).map_err(|e| format!("tool `{}`: {e}", tool.id())) +} + +#[cfg(test)] +mod tests { + use serde_json::json; + + use super::*; + + #[test] + fn numbers_are_checked_against_their_range() { + assert!(number("fidelity", &json!(0.05), 0.05, 100.0).is_ok()); + assert!(number("fidelity", &json!(100), 0.05, 100.0).is_ok()); + for bad in [json!(-3), json!(1e9), json!("abc"), json!(true), json!(null), json!(0.04)] { + assert_eq!(number("fidelity", &bad, 0.05, 100.0), Err("`fidelity` must be a number from 0.05 to 100".into()), "{bad}"); + } + assert!(whole("sides", &json!(3), 3, 1000).is_ok()); + for bad in [json!(2), json!(3.5), json!(1001), json!(-1), json!("6")] { + assert!(whole("sides", &bad, 3, 1000).is_err(), "{bad}"); + } + assert!(positive("width", &json!(0), 1e6).is_err()); + assert!(positive("width", &json!(1e6), 1e6).is_ok()); + assert!(finite("angle", &json!(720)).is_ok()); + assert!(finite("angle", &json!("720")).is_err()); + } + + #[test] + fn other_values_are_checked_by_kind() { + assert!(boolean("fill", &json!(false)).is_ok()); + assert_eq!(boolean("fill", &json!(0)), Err("`fill` must be true or false".into())); + assert!(one_of("axis", &json!("free"), &["vertical", "free"]).is_ok()); + assert_eq!(one_of("axis", &json!("diagonal"), &["vertical", "free"]), Err("`axis` must be one of `vertical`, `free`".into())); + assert!(string_or_null("prev", &json!(null)).is_ok()); + assert!(string_or_null("prev", &json!(3)).is_err()); + } + + /// Every tool takes back the options it reports, each on its own and all together: a dialog's + /// OK sends every field the tool showed it. The state a tool reports and doesn't take (the + /// picked mesh points, the text being edited, the pins, the queue of files to place) is left + /// out. + #[test] + fn every_tool_takes_the_options_it_reports() { + const TYPE: &[&str] = &["type", "areaType", "typeOnPath", "verticalType", "verticalAreaType", "verticalTypeOnPath"]; + const READ_ONLY: &[(&[&str], &[&str])] = &[ + (&["directSelection", "groupSelection", "lasso", "polygonalLasso", "mesh", "magicWand"], &["meshPoints"]), + (TYPE, &["editing"]), + (&["puppetWarp"], &["pins", "selected"]), + // With nothing queued, `current` (0) is no file's index either. + (&["place"], &["count", "current", "name", "width", "height", "names"]), + ]; + let read_only = |id: &str, k: &str| READ_ONLY.iter().any(|(ids, keys)| ids.contains(&id) && keys.contains(&k)); + // Tools that `create` makes and the catalog doesn't list. + let extra = ["place", "dimension", crate::cropimage::ID, "intertwine"]; + let mut refused = Vec::new(); + let mut check = |id: &str, tool: &dyn Tool, after: &str| { + let Some(mut options) = tool.options().as_object().cloned() else { return }; + options.retain(|k, _| !read_only(id, k)); + for (k, v) in &options { + if let Err(e) = tool.check_option(k, v) { + refused.push(format!("tool `{id}`{after}, option `{k}` = {v}: {e}")); + } + } + if let Err(e) = check_values(tool, &options) { + refused.push(format!("{e}{after}")); + } + }; + for id in crate::catalog::all_tools().map(|t| t.id).chain(extra) { + let tool = crate::create(id); + check(id, tool.as_ref(), ""); + // A number set past either end, or a true-or-false option flipped, is still taken back + // as the tool then reports it. + let Some(defaults) = tool.options().as_object().cloned() else { continue }; + for (k, v) in defaults.iter().filter(|(k, _)| !read_only(id, k)) { + let tries = match v { + Value::Number(_) => vec![json!(-1e9), json!(1e9)], + Value::Bool(b) => vec![json!(!b)], + _ => continue, + }; + for value in tries { + let mut changed = crate::create(id); + changed.set_option(k, &value); + check(id, changed.as_ref(), &format!(" after setting `{k}` to {value}")); + } + } + } + assert!(refused.is_empty(), "{}", refused.join("\n")); + } + + #[test] + fn set_option_params_reads_the_tool_and_the_options() { + let p = json!({"tool": "smooth", "key": "fidelity", "value": 2, "values": {"x": 1}}); + let (tool, values) = set_option_params(&p).unwrap(); + assert_eq!(tool, Some("smooth")); + assert_eq!(Value::Object(values), json!({"fidelity": 2, "x": 1})); + let empty = json!({}); + let (tool, values) = set_option_params(&empty).unwrap(); + assert!(tool.is_none() && values.is_empty()); + // Omitted parameters arrive as null: a read, like `{}`. + let (tool, values) = set_option_params(&Value::Null).unwrap(); + assert!(tool.is_none() && values.is_empty()); + for (bad, got) in [(json!(true), "true"), (json!(7), "7"), (json!([]), "[]"), (json!("x"), "\"x\"")] { + assert_eq!(set_option_params(&bad).err(), Some(format!("the params must be an object, not {got}")), "{bad}"); + } + // A long value is shown cut, as the other parameter errors show it. + let long = json!("a".repeat(100)); + let shown = format!("\"{}…", "a".repeat(39)); + assert_eq!(set_option_params(&long).err(), Some(format!("the params must be an object, not {shown}"))); + assert_eq!(set_option_params(&json!({"tool": 3})).err(), Some("`tool` must be a tool id".into())); + assert_eq!(set_option_params(&json!({"values": [1]})).err(), Some("`values` must be an object".into())); + assert_eq!(set_option_params(&json!({"key": 3, "value": 1})).err(), Some("`key` must be a string".into())); + assert_eq!(set_option_params(&json!({"key": "fill"})).err(), Some("`value` is missing for `fill`".into())); + assert_eq!(set_option_params(&json!({"value": 1})).err(), Some("`value` needs a `key`".into())); + assert_eq!( + set_option_params(&json!({"key": "fill", "value": true, "values": {"fill": false}})).err(), + Some("`fill` is given both as `key` and in `values`".into()) + ); + // An explicit null is a value: the Type tool's triggers take one. + assert!(set_option_params(&json!({"key": "stopEditing", "value": null})).is_ok()); + } +} diff --git a/crates/tools/src/pen.rs b/crates/tools/src/pen.rs index 24a21d08ca..b1077d5a12 100644 --- a/crates/tools/src/pen.rs +++ b/crates/tools/src/pen.rs @@ -29,6 +29,7 @@ //! the other art and of the path being drawn, into line with them, onto the construction guides //! through the last anchor; with Shift held it slides along its 45° step into line. Hovering shows //! where the next one would go. +//! While a drag pulls a handle out, the Info panel shows it from the anchor to the handle's end. use serde_json::json; use vectorcraft_doc::{NodeId, NodeKind}; @@ -62,6 +63,10 @@ pub struct PenTool { /// The pointer has moved past the drag threshold since the press: a press released inside it /// is a click, so the anchor stays a corner without handles. dragged: bool, + /// The handle a drag past the threshold is pulling out, from the anchor it shapes to the + /// handle's end as last previewed (the outgoing handle, or the incoming one of the first + /// anchor closing the path): what the Info panel shows ([`Tool::readout`]). + vector: Option, /// The last anchor of the path being drawn, while a click retracts its outgoing handle or a /// drag pulls a new one out: (path, subpath, anchor, its position). handle: Option<(NodeId, usize, usize, Point)>, @@ -256,6 +261,12 @@ impl Tool for PenTool { fn ends_on_escape(&self, cx: &ToolContext) -> bool { self.active(cx).is_some() } + /// The handle a drag is pulling out of the anchor it shapes: the outgoing handle of a new or + /// added anchor or of the last anchor, or the incoming handle of the first anchor closing the + /// path. None for a click, a hover or an Alt gesture. + fn readout(&self, _cx: &ToolContext) -> Option { + self.vector.filter(|_| self.dragged && (self.drag.is_some() || self.handle.is_some())).map(crate::Readout::drag) + } fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { let tol = cx.tol(5.0).max(cx.point_tol()); // The path a press began is the selected one by the next event. @@ -292,6 +303,7 @@ impl Tool for PenTool { self.last = ev.pos; self.pressed = ev.pos; self.dragged = false; + self.vector = None; if let Some((id, si, first, last, _)) = active { let end = last_anchor(cx, id, Some(si)); let closing_end = end.filter(|(_, ai)| *ai > 0).map(|_| first); @@ -391,6 +403,7 @@ impl Tool for PenTool { if ev.mods.shift { h = a + vectorcraft_geom::constrain_angle_from(ev.pos - a, 45.0, cx.constrain_angle); } + self.vector = Some(h - a); return vec![set_out_handle(id, si, ai, h)]; } let Some(Place { at: mut a, path, subpath, closing, mut moved }) = self.drag else { return vec![] }; @@ -412,6 +425,8 @@ impl Tool for PenTool { if ev.mods.shift { out_h = a + vectorcraft_geom::constrain_angle_from(ev.pos - a, 45.0, cx.constrain_angle); } + // A closing drag shapes the first anchor's incoming handle, which mirrors the pointer. + self.vector = Some(if closing { a - out_h } else { out_h - a }); let alt = ev.mods.alt; let Some(id) = path else { // First anchor of a new path: re-issue create with handles. @@ -436,6 +451,7 @@ impl Tool for PenTool { } PointerKind::Up => { self.snap.clear(); + self.vector = None; if let Some(mut t) = self.convert.take() { return t.pointer(cx, ev); } @@ -458,6 +474,12 @@ impl Tool for PenTool { _ => vec![], } } + /// Choosing the Pen again (P, its toolbar button, `tool.select`) ends the path being drawn as + /// Escape does: the path stays open, the Pen stays chosen, and the next click starts a new + /// path. With no path being drawn it changes nothing. + fn chosen_again(&mut self, cx: &ToolContext) -> Vec { + self.deactivate(cx) + } /// A dropped press drops only the anchor it was placing, a handle it was dragging or the /// close it was making: the path being drawn goes on with the next click. fn drop_press(&mut self, _cx: &ToolContext) -> Vec { @@ -465,6 +487,7 @@ impl Tool for PenTool { self.first = None; self.handle = None; self.convert = None; + self.vector = None; self.snap.clear(); vec![] } @@ -476,6 +499,7 @@ impl Tool for PenTool { let placing = self.drag.take().is_some(); self.first = None; let handling = self.handle.take().is_some(); + self.vector = None; // Finish the preview as it stands; clearing state alone leaves its transaction open. let mut acts = self.convert.take().map(|mut t| t.deactivate(cx)).unwrap_or_default(); if placing || handling { @@ -684,7 +708,7 @@ fn auto_add_delete(cx: &ToolContext, p: Point, m: Mods, tol: f64) -> Option Option> { - for (id, path) in crate::direct::spines(cx).into_iter().filter(|(id, _)| cx.selection.contains(*id)) { + for (id, path) in crate::direct::selected_spines(cx) { let Some(NodeKind::Blend { children, spec }) = cx.doc.node(id).map(|n| &n.kind) else { continue }; let keys = vectorcraft_doc::live::blend_spine(children, spec).and_then(|(_, a)| a).unwrap_or_default(); if let Some((_, ai, _)) = path.anchors().find(|(_, _, a)| a.p.distance(p) <= tol) { diff --git a/crates/tools/src/pen/tests.rs b/crates/tools/src/pen/tests.rs index badb8193a7..710c39ae7a 100644 --- a/crates/tools/src/pen/tests.rs +++ b/crates/tools/src/pen/tests.rs @@ -570,6 +570,98 @@ fn ending_during_a_pen_gesture_commits_and_clears_it() { } } +/// Choosing the Pen again ends the path being drawn as Escape does, with the rubber band on or off +/// and for a one-anchor path: the preview goes, nothing is added to the document, and the next +/// click starts a new path. Mid-drag it commits the anchor being placed first. With no path being +/// drawn it changes nothing. +#[test] +fn choosing_the_pen_again_ends_the_path() { + let p = paint(); + let created = |acts: &[Action]| matches!(acts, [Action::Begin(_), Action::Preview(c, _)] if c == "path.create"); + let preview = |o: &[Overlay]| o.iter().any(|o| matches!(o, Overlay::Path { .. } | Overlay::Measure { .. })); + for pts in [vec![Point::new(100.0, 300.0), Point::new(200.0, 300.0)], vec![Point::new(100.0, 300.0)]] { + let (d, _, s) = drawing(vectorcraft_geom::SubPath::polyline(&pts, false)); + for band in [true, false] { + let cx = ToolContext { pen_rubber_band: band, ..cx(&d, &s, &p) }; + let mut t = PenTool { drawing: true, ..PenTool::default() }; + t.pointer(&cx, &PointerEvent::new(PointerKind::Move, 300.0, 410.0)); + assert!(preview(&t.overlays(&cx)), "band {band}"); + assert_eq!(t.cursor(&cx, Point::new(300.0, 410.0), Mods::default()), Cursor::PenDrawing); + assert!(t.chosen_again(&cx).is_empty(), "nothing to commit"); + assert!(!preview(&t.overlays(&cx)), "band {band}"); + assert_eq!(t.cursor(&cx, Point::new(300.0, 410.0), Mods::default()), Cursor::Pen); + let acts = click(&mut t, &cx, 300.0, 410.0, Mods::default()); + assert!(created(&acts), "{} anchors, band {band}: {acts:?}", pts.len()); + } + // Chosen again (through `tool.select`) while a drag places an anchor: it is committed. + let cx = cx(&d, &s, &p); + let mut t = PenTool { drawing: true, ..PenTool::default() }; + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 300.0, 410.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 320.0, 440.0)); + assert_eq!(t.chosen_again(&cx), vec![Action::Commit]); + assert!(!t.busy()); + assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 320.0, 440.0)).is_empty()); + assert!(created(&click(&mut t, &cx, 300.0, 500.0, Mods::default()))); + } + let (d, _, s) = drawing(vectorcraft_geom::SubPath::polyline(&[Point::new(100.0, 300.0), Point::new(200.0, 300.0)], false)); + let cx = cx(&d, &s, &p); + let mut t = PenTool::default(); + assert!(t.chosen_again(&cx).is_empty()); + assert_eq!(t.cursor(&cx, Point::new(300.0, 410.0), Mods::default()), Cursor::Pen); +} + +/// Choosing the Pen again while it draws a path inside a compound path ends that path as Escape +/// and Enter do: the compound path is selected, the path is not closed, no undo step is added, +/// and the next click starts a new path. Ending a path outside any compound path sends no +/// selection change. +#[test] +fn choosing_the_pen_again_selects_the_compound_parent_of_the_path_being_drawn() { + let (mut d, _) = doc_with_rect(); + let l = d.layers[0].id; + let (a, b, compound) = (d.alloc_id(), d.alloc_id(), d.alloc_id()); + let open = |x: f64| { + vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&[Point::new(x, 300.0), Point::new(x + 100.0, 300.0)], false)) + }; + let path = |id, x| std::sync::Arc::new(vectorcraft_doc::Node::path(id, open(x), vectorcraft_doc::Appearance::default_art())); + let mut node = vectorcraft_doc::Node::new( + compound, + NodeKind::Compound { children: vec![path(a, 10.0), path(b, 300.0)], rule: vectorcraft_geom::FillRule::NonZero }, + ); + node.appearance = vectorcraft_doc::Appearance::default_art().into(); + d.insert(Some(l), 1, node).unwrap(); + let p = paint(); + // The member path alone is the selection while the Pen draws it. + let mut s = Selection::default(); + s.set([a]); + let inside = cx(&d, &s, &p); + // The selection once the engine ran `select.set`: the compound path. + let mut sc = Selection::default(); + sc.set([compound]); + let after = cx(&d, &sc, &p); + let select_compound = vec![Action::Exec("select.set".into(), json!({"ids": [compound.0]}))]; + for key in [None, Some(ToolKey::Escape), Some(ToolKey::Enter)] { + let mut t = PenTool { drawing: true, path: Some(a), subpath: Some(0), ..PenTool::default() }; + assert_eq!(t.cursor(&inside, Point::new(250.0, 450.0), Mods::default()), Cursor::PenDrawing, "{key:?}"); + let acts = match key { + Some(k) => t.key(&inside, k, Mods::default()), + None => t.chosen_again(&inside), + }; + assert_eq!(acts, select_compound, "{key:?}: only the selection changes, with no close and no undo step"); + assert!(!t.busy() && t.active(&after).is_none(), "{key:?}: the path is done"); + assert_eq!(t.cursor(&after, Point::new(250.0, 450.0), Mods::default()), Cursor::Pen, "{key:?}"); + let next = click(&mut t, &after, 250.0, 450.0, Mods::default()); + assert!( + matches!(next.as_slice(), [Action::Begin(_), Action::Preview(c, _)] if c == "path.create"), + "{key:?}: the next click starts a new path: {next:?}" + ); + } + let (d, id, s) = drawing(vectorcraft_geom::SubPath::polyline(&[Point::new(100.0, 300.0), Point::new(200.0, 300.0)], false)); + let plain = cx(&d, &s, &p); + let mut t = PenTool { drawing: true, path: Some(id), subpath: Some(0), ..PenTool::default() }; + assert!(t.chosen_again(&plain).is_empty()); + assert!(!t.busy() && t.active(&plain).is_none()); +} + /// #501: a press on the first anchor closes the path, however far the drag then goes: the /// closing preview leaves the path closed (so not one the pen extends), and each move still /// previews the close with the incoming handle mirroring the pointer (Alt keeps the outgoing one @@ -970,3 +1062,128 @@ fn continuing_a_compound_member_at_its_first_anchor_reverses_that_path_by_id() { ); assert_eq!((pen.path, pen.subpath), (Some(a), Some(0))); } + +/// A context with snapping off, so each point goes where the pointer is. +fn plain<'a>(d: &'a vectorcraft_doc::Document, s: &'a Selection, p: &'a crate::PaintDefaults) -> ToolContext<'a> { + ToolContext { zoom: 1.0, smart_guides: false, snap_to_point: false, snap_to_pixel: false, snap_to_grid: false, ..cx(d, s, p) } +} + +fn drag_readout(dx: f64, dy: f64) -> Option { + Some(crate::Readout::Drag { dx, dy }) +} + +/// The Info panel shows the handle a drag pulls out of a new anchor, from the anchor to the +/// handle's end, once the drag passes the threshold and until the button comes up. +#[test] +fn info_readout_tracks_the_handle_of_a_new_anchor() { + let (d, s, p) = (vectorcraft_doc::Document::new(500.0, 500.0), Selection::default(), paint()); + let cx = plain(&d, &s, &p); + let mut t = PenTool::default(); + assert_eq!(t.readout(&cx), None, "hovering"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 100.0)); + assert_eq!(t.readout(&cx), None, "pressed"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 101.0, 101.0)); + assert_eq!(t.readout(&cx), None, "inside the drag threshold"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 130.0, 60.0)); + let r = t.readout(&cx); + assert_eq!(r, drag_readout(30.0, -40.0)); + let (dist, angle) = r.and_then(|r| r.distance_angle()).unwrap_or_default(); + assert!((dist - 50.0).abs() < 1e-9 && (angle - 53.130_102_354_155_98).abs() < 1e-9, "{dist} {angle}"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 130.0, 60.0)); + assert_eq!(t.readout(&cx), None, "released"); + // A click shows nothing. + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 200.0, 200.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 201.0, 200.0)); + assert_eq!(t.readout(&cx), None); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 201.0, 200.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Move, 250.0, 250.0)); + assert_eq!(t.readout(&cx), None, "hovering after a click"); +} + +/// An anchor added to the path being drawn and the first anchor closing it: the handle the drag +/// shapes is measured from the anchor it belongs to. +#[test] +fn info_readout_tracks_added_and_closing_anchors() { + let pts = [Point::new(100.0, 300.0), Point::new(200.0, 300.0), Point::new(200.0, 400.0)]; + let (d, _, s) = drawing(vectorcraft_geom::SubPath::polyline(&pts, false)); + let p = paint(); + let cx = plain(&d, &s, &p); + let mut t = PenTool { drawing: true, ..PenTool::default() }; + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 300.0, 400.0)); + assert!(matches!(&a[..], [Action::Begin(_), Action::Preview(c, _)] if c == "path.appendAnchor"), "{a:?}"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 330.0, 440.0)); + assert_eq!(t.readout(&cx), drag_readout(30.0, 40.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 330.0, 440.0)); + assert_eq!(t.readout(&cx), None); + // A press on the first anchor, a pixel off it, closes: the readout is that anchor's incoming + // handle, which mirrors the pointer. + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 101.0, 301.0)); + assert!(matches!(&a[..], [Action::Begin(c), _] if c == "Close Path"), "{a:?}"); + let acts = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 130.0, 260.0)); + let [Action::Preview(c, v)] = acts.as_slice() else { panic!("not a close preview: {acts:?}") }; + assert_eq!((c.as_str(), &v["in"]), ("path.close", &json!([70.0, 340.0]))); + assert_eq!(t.readout(&cx), drag_readout(-30.0, 40.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 130.0, 260.0)); + assert_eq!(t.readout(&cx), None); +} + +/// A drag from the last anchor pulls its outgoing handle out on its own; with Shift the readout +/// gives the constrained handle the preview shows. +#[test] +fn info_readout_tracks_the_last_anchor_handle() { + let (d, id, s) = drawing(vectorcraft_geom::SubPath::polyline(&[Point::new(10.0, 300.0), Point::new(60.0, 300.0)], false)); + let p = paint(); + let cx = plain(&d, &s, &p); + let mut t = PenTool { drawing: true, ..PenTool::default() }; + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 60.0, 300.0)); + assert_eq!(t.readout(&cx), None, "a click retracts the handle"); + assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 70.0, 280.0)), vec![set_out(id, 1, 70.0, 280.0)]); + assert_eq!(t.readout(&cx), drag_readout(10.0, -20.0)); + let shift = Mods { shift: true, ..Mods::default() }; + // 26.6° from the anchor: Shift turns it to the 45° step nearest. + let acts = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 80.0, 290.0).with_mods(shift)); + let [Action::Preview(_, v)] = acts.as_slice() else { panic!("not a handle preview: {acts:?}") }; + let (hx, hy) = (v["x"].as_f64().unwrap_or(f64::NAN), v["y"].as_f64().unwrap_or(f64::NAN)); + assert!(((hx - 60.0) + (hy - 300.0)).abs() < 1e-9, "constrained to 45°: {v}"); + assert_eq!(t.readout(&cx), drag_readout(hx - 60.0, hy - 300.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 80.0, 290.0)); + assert_eq!(t.readout(&cx), None); +} + +/// Space moves the anchor and its handles together, so the handle keeps its length; Alt leaves +/// the incoming handle behind and the readout follows the outgoing one. +#[test] +fn info_readout_follows_space_and_alt() { + let (d, s, p) = (vectorcraft_doc::Document::new(500.0, 500.0), Selection::default(), paint()); + let cx = plain(&d, &s, &p); + let mut t = PenTool::default(); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 400.0, 420.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 450.0, 420.0)); + assert_eq!(t.readout(&cx), drag_readout(50.0, 0.0)); + let space = Mods { space: true, ..Mods::default() }; + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 450.0, 380.0).with_mods(space)); + assert_eq!(t.readout(&cx), drag_readout(50.0, 0.0), "the anchor moved with the handle"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 460.0, 400.0)); + assert_eq!(t.readout(&cx), drag_readout(60.0, 20.0), "measured from the moved anchor"); + let alt = Mods { alt: true, ..Mods::default() }; + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 400.0, 450.0).with_mods(alt)); + assert_eq!(t.readout(&cx), drag_readout(0.0, 70.0)); +} + +/// A dropped press and switching tools clear the readout. +#[test] +fn info_readout_clears_on_a_dropped_press_and_deactivate() { + let (d, s, p) = (vectorcraft_doc::Document::new(500.0, 500.0), Selection::default(), paint()); + let cx = plain(&d, &s, &p); + let mut t = PenTool::default(); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 100.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 120.0, 100.0)); + assert_eq!(t.readout(&cx), drag_readout(20.0, 0.0)); + t.drop_press(&cx); + assert_eq!(t.readout(&cx), None, "dropped"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 100.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 100.0, 130.0)); + assert_eq!(t.readout(&cx), drag_readout(0.0, 30.0)); + t.deactivate(&cx); + assert_eq!(t.readout(&cx), None, "deactivated"); +} diff --git a/crates/tools/src/place.rs b/crates/tools/src/place.rs index 66d3fbc5f1..813ec99429 100644 --- a/crates/tools/src/place.rs +++ b/crates/tools/src/place.rs @@ -188,6 +188,33 @@ impl Tool for PlaceTool { } } + /// A queue whose every entry has its `params` object and a finite `width` and `height`, and + /// `current` within the queue held. + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + match key { + "queue" => check_queue(value).map(drop), + "current" => check_current(value, self.entries.len()), + _ => Err(crate::option_check::unknown(key)), + } + } + + /// As [`Self::check_option`], except that a `current` given with a `queue` is an index into + /// that queue (the queue is set first). + fn check_options(&self, values: &serde_json::Map) -> Result<(), String> { + let mut held = self.entries.len(); + if let Some(queue) = values.get("queue") { + held = check_queue(queue)?; + } + for (k, v) in values { + match k.as_str() { + "queue" => {} + "current" => check_current(v, held)?, + _ => self.check_option(k, v)?, + } + } + Ok(()) + } + /// Switching tools discards what the cursor holds. fn deactivate(&mut self, _cx: &ToolContext) -> Vec { self.entries.clear(); @@ -196,6 +223,35 @@ impl Tool for PlaceTool { } } +/// The number of files `queue` holds, or an error when an entry lacks its `params` object or a +/// finite `width` and `height`. +fn check_queue(queue: &Value) -> Result { + let entry = |e: &Value| { + e.get("params").is_some_and(Value::is_object) + && e.get("name").is_none_or(Value::is_string) + && ["width", "height"].iter().all(|k| e.get(k).and_then(Value::as_f64).is_some_and(f64::is_finite)) + }; + let entries = match queue.get("entries") { + None => Some(0), + Some(e) => e.as_array().filter(|a| a.iter().all(entry)).map(Vec::len), + }; + match entries { + Some(n) if queue.is_object() && queue.get("prev").is_none_or(Value::is_string) => Ok(n), + _ => Err("`queue` must be {entries: [{params, name, width, height}], prev?}: each entry with a params object and a finite \ + width and height" + .into()), + } +} + +/// `current` is the index of one of the `held` files. +fn check_current(current: &Value, held: usize) -> Result<(), String> { + match held { + _ if current.as_u64().is_some_and(|i| i < held as u64) => Ok(()), + 0 => Err("`current` can't be set: no file is queued".into()), + _ => Err(format!("`current` must be the index of a queued file, from 0 to {}", held - 1)), + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/tools/src/shape.rs b/crates/tools/src/shape.rs index 1b2cfa3086..d4c8d4f36c 100644 --- a/crates/tools/src/shape.rs +++ b/crates/tools/src/shape.rs @@ -815,6 +815,11 @@ impl Tool for ShapeTool { vec![Action::Dialog(self.id.into(), args)] } } + // A double-click on a corner widget of the selected live shape shows the Transform + // panel; the tool and the selection stay as they are. + PointerKind::DoubleClick if shows_shape_widgets(self.id) && corners::over_widget(cx, ev.pos, false) => { + vec![Action::Panel("transform".into())] + } _ => vec![], } } @@ -1083,6 +1088,21 @@ impl Tool for ShapeTool { } } } + /// The options every shape tool keeps ([`Self::options`]). Any finite angle is taken: it is + /// kept as the same direction from 0 to 360°. + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "sides" | "points" => c::whole(key, v, 3, 1000), + "anchors" => c::whole(key, v, 2, 1000), + "cornerRadius" => c::number(key, v, 0.0, MAX_CORNER_RADIUS), + "starRatio" => c::number(key, v, 0.01, 1.0), + "length" => c::number(key, v, 0.0, 1e6), + "angle" => c::finite(key, v), + "fillLine" => c::boolean(key, v), + _ => Err(c::unknown(key)), + } + } } #[cfg(test)] diff --git a/crates/tools/src/shape/tests.rs b/crates/tools/src/shape/tests.rs index b8c6f9c647..ec911f4cfb 100644 --- a/crates/tools/src/shape/tests.rs +++ b/crates/tools/src/shape/tests.rs @@ -1309,6 +1309,86 @@ fn a_shape_tool_drags_the_selected_shapes_widgets() { assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 200.0, 20.0)), vec![Action::Commit]); } +/// A double-click on a corner widget of a selected live shape, with a shape tool that shows the +/// widgets, asks for the Transform panel and nothing else: neither click draws, edits or begins an +/// undo step, and the tool stays idle. Line Segment, a plain path, a pie widget, a hidden or +/// angle-excluded corner widget and a spot off the widgets ask for nothing. +#[test] +fn a_double_click_on_a_corner_widget_shows_the_transform_panel() { + use vectorcraft_doc::{Appearance, LiveShape, Node, NodeKind}; + let live = |shape: LiveShape| { + let mut d = vectorcraft_doc::Document::new(500.0, 500.0); + let (l, id) = (d.layers[0].id, d.alloc_id()); + let mut n = Node::path(id, shape.to_path(), Appearance::default_art()); + if let NodeKind::Path { live: slot, .. } = &mut n.kind { + *slot = Some(Box::new(shape)); + } + d.insert(Some(l), 0, n).unwrap(); + let mut s = Selection::default(); + s.add(id); + (d, s) + }; + let double_click = |t: &mut ShapeTool, c: &ToolContext, at: Point| { + let mut out = vec![]; + for kind in [PointerKind::Down, PointerKind::Up, PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick] { + out.push(t.pointer(c, &PointerEvent::new(kind, at.x, at.y))); + } + out + }; + let panel = vec![Action::Panel("transform".into())]; + let xf = Affine::translate((100.0, 100.0)); + let (d, s) = live(LiveShape::Rectangle { w: 100.0, h: 100.0, radii: [0.0; 4], kinds: Default::default(), radii_relative: false, xf }); + let p = paint(); + let c = cx(&d, &s, &p); + let at = Point::new(110.0, 110.0); + for id in ["rectangle", "roundedRectangle", "ellipse", "polygon", "star"] { + let mut t = ShapeTool::new(id); + let out = double_click(&mut t, &c, at); + assert!(out[..4].iter().all(Vec::is_empty), "{id}: {out:?}"); + assert_eq!(out[4], panel, "{id}"); + assert!(!t.busy() && !t.transforming(), "{id}"); + // Off the widgets, a double-click asks for nothing. + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::DoubleClick, 300.0, 300.0)).is_empty(), "{id}"); + } + // Line Segment has no shape widgets. + let mut t = ShapeTool::new("lineSegment"); + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::DoubleClick, at.x, at.y)).is_empty()); + // Show Corner Widget off, or the corner wider than the angle limit: the widget is hidden. + let mut hidden = cx(&d, &s, &p); + hidden.corner_widgets = false; + let mut t = ShapeTool::new("rectangle"); + assert!(t.pointer(&hidden, &PointerEvent::new(PointerKind::DoubleClick, at.x, at.y)).is_empty()); + let mut narrow = cx(&d, &s, &p); + narrow.corner_widget_max_angle = 80.0; + assert!(t.pointer(&narrow, &PointerEvent::new(PointerKind::DoubleClick, at.x, at.y)).is_empty()); + // A live polygon's corner widget asks for the panel too. + let (d, s) = live(LiveShape::Polygon { + radius: 100.0, + sides: 6, + xf: Affine::translate((250.0, 250.0)), + radii: vec![], + kinds: vec![], + radii_relative: false, + }); + let c = cx(&d, &s, &p); + let w = corners::CornerWidgets::for_tool(&c, false).and_then(|w| w.visible().next()).unwrap(); + let mut t = ShapeTool::new("polygon"); + assert_eq!(double_click(&mut t, &c, w)[4], panel); + // A plain path shows no corner widget to a shape tool. + let (d, id) = doc_with_rect(); + let mut s = Selection::default(); + s.add(id); + let c = cx(&d, &s, &p); + let mut t = ShapeTool::new("rectangle"); + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::DoubleClick, at.x, at.y)).is_empty()); + // A live ellipse's pie widget, 12 px right of (300, 150), is not a corner widget. + let (d, s) = live(LiveShape::Ellipse { w: 200.0, h: 100.0, pie: (0.0, 360.0), xf }); + let c = cx(&d, &s, &p); + let mut t = ShapeTool::new("ellipse"); + assert!(double_click(&mut t, &c, Point::new(312.0, 150.0)).iter().all(Vec::is_empty)); + assert!(!t.busy()); +} + /// A selected live 100 × 100 rectangle at (100, 100)–(200, 200) with no paint: its centre point /// (Attributes › Show Center) is at (150, 150) and its corners at the box's. fn unfilled_live_rect() -> (vectorcraft_doc::Document, Selection) { @@ -1579,6 +1659,18 @@ fn a_move_from_the_centre_point_snaps_and_shows_the_hollow_arrow() { assert_eq!(t.cursor(&c, Point::new(160.0, 150.0), Mods::default()), Cursor::Arrow); } +/// `tool.setOption` takes an ellipse's anchor count from 2 to 1000, as the tool keeps it. +#[test] +fn the_anchor_count_is_checked_against_its_range() { + let t = ShapeTool::new("ellipse"); + for n in [2, 4, 1000] { + assert_eq!(t.check_option("anchors", &json!(n)), Ok(()), "{n}"); + } + for bad in [json!(1), json!(1001), json!(4.5), json!("4")] { + assert_eq!(t.check_option("anchors", &bad), Err("`anchors` must be a whole number from 2 to 1000".into()), "{bad}"); + } +} + /// A drag event to `(x, y)` with Backtick held or not. fn quote_drag(x: f64, y: f64, held: bool) -> PointerEvent { PointerEvent { backquote: held, ..PointerEvent::new(PointerKind::Drag, x, y) } diff --git a/crates/tools/src/symbolism.rs b/crates/tools/src/symbolism.rs index ba00ec4125..b4dd9e631b 100644 --- a/crates/tools/src/symbolism.rs +++ b/crates/tools/src/symbolism.rs @@ -222,6 +222,15 @@ impl Tool for SymbolismTool { _ => {} } } + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "diameter" => c::number(key, v, 2.0, 2000.0), + "intensity" | "density" => c::number(key, v, 1.0, 10.0), + "symbol" | "style" => c::string_or_null(key, v), + _ => Err(c::unknown(key)), + } + } } /// Paintbrush: the freehand gesture, painting with the current brush. @@ -293,6 +302,9 @@ impl Tool for BrushPaintTool { self.inner.set_option(key, v); } } + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + if key == "brush" { crate::option_check::string_or_null(key, v) } else { self.inner.check_option(key, v) } + } fn wants_samples(&self) -> bool { self.inner.wants_samples() } diff --git a/crates/tools/src/text.rs b/crates/tools/src/text.rs index 763325f90e..fb7e38bd0f 100644 --- a/crates/tools/src/text.rs +++ b/crates/tools/src/text.rs @@ -137,6 +137,15 @@ fn text_hash(s: &str) -> u64 { /// The edited text's layout, keyed by [`vectorcraft_text::layout_inputs`] and the text. type CachedLayout = ((u64, TextObject), Arc); +/// The layouts of the frames other than the edited one that the overlays draw (the ports of the +/// selected area type and type on a path, the other frames of a selected story), by frame, each +/// kept with the layout inputs and the text it was made from ([`TypeTool::frame_layout`]). +type FrameLayouts = std::collections::HashMap; + +/// The most other frames' layouts [`TypeTool::frames`] keeps: every port drawn ([`PORTS_MAX`]) +/// and a long story's frames. The frames an overlays call draws past it are laid out on each call. +const FRAME_LAYOUTS_MAX: usize = 2_048; + /// Process-global Type-tool edit-session counter: the IME target's replacement epoch. /// /// A per-tool counter restarts at zero when the tool is recreated (a document switch, File › @@ -220,6 +229,9 @@ pub struct TypeTool { /// The state at the start of each `command.batch` still running, innermost last. batches: Vec, cache: Mutex>, + /// The other frames' layouts the last overlays drew ([`FrameLayouts`]): each overlays call + /// keeps only the frames it draws. + frames: Mutex, } struct BeforePress { @@ -296,6 +308,28 @@ impl TypeTool { l } + /// Layout of `t`, frame `id`, for an overlays call that draws a frame other than the edited + /// one: the layout kept in `now` or `was` for `id` when it was made from the layout inputs + /// `fonts` and the same text, otherwise a new one. It is kept in `now` either way while `now` + /// holds fewer than [`FRAME_LAYOUTS_MAX`]. + fn frame_layout(now: &mut FrameLayouts, was: &mut FrameLayouts, fonts: u64, id: NodeId, t: &TextObject) -> Arc { + if let Some(((g, k), l)) = now.get(&id) + && *g == fonts + && k == t + { + return l.clone(); + } + let kept = match was.remove(&id) { + Some(((g, k), l)) if g == fonts && &k == t => ((g, k), l), + _ => ((fonts, t.clone()), Arc::new(vectorcraft_text::layout(FontDb::global(), t))), + }; + let l = kept.1.clone(); + if now.len() < FRAME_LAYOUTS_MAX { + now.insert(id, kept); + } + l + } + /// The edited text used to find word and paragraph boundaries for selection: the typing session's /// runs, or the document's current text when there is no live session or it has gone stale. fn plain(&self, cx: &ToolContext) -> String { diff --git a/crates/tools/src/text/tests.rs b/crates/tools/src/text/tests.rs index 94063166bc..89a24cc3bf 100644 --- a/crates/tools/src/text/tests.rs +++ b/crates/tools/src/text/tests.rs @@ -1636,10 +1636,276 @@ fn the_edited_types_ports_follow_the_limit_too() { tool.start_editing(id, 0); let boxes = |o: &[Overlay]| o.iter().filter(|o| matches!(o, Overlay::Highlight { color: [255, 255, 255, 255], .. })).count(); assert_eq!(boxes(&tool.overlays(&cx(&d, &sel, &p))), 2 * PORTS_MAX, "at the limit, the edited one's included"); + assert_eq!(kept_frames(&tool), PORTS_MAX - 1, "the other frames' layouts are kept"); let copy = d.alloc_id(); d.insert(Some(l), 1, Node::new(copy, node.kind.clone())).unwrap(); sel.add(copy); assert_eq!(boxes(&tool.overlays(&cx(&d, &sel, &p))), 0, "past it, not even the edited one's"); + assert_eq!(kept_frames(&tool), 0, "no ports drawn, no layouts kept"); +} + +/// How many other frames' layouts the Type tool keeps between overlays calls. +fn kept_frames(tool: &TypeTool) -> usize { + tool.frames.lock().unwrap().len() +} + +/// The value `f` returns, and how many layouts this thread started while it ran. +fn counted(f: impl FnOnce() -> T) -> (T, u64) { + let before = vectorcraft_text::test_fonts::layouts_on_this_thread(); + let v = f(); + (v, vectorcraft_text::test_fonts::layouts_on_this_thread() - before) +} + +/// A document with area type frames of `texts` (each 120 × 40 pt, one under the other) and their ids. +fn area_frames(texts: &[&str]) -> (Document, Vec) { + let mut d = Document::new(500.0, 2000.0); + let l = d.layers[0].id; + let mut ids = Vec::new(); + for (i, s) in texts.iter().enumerate() { + let id = d.alloc_id(); + let mut t = TextObject::point(Point::new(50.0, 50.0 + 60.0 * i as f64), s, CharStyle::default()); + t.kind = area_kind(120.0, 40.0); + d.insert(Some(l), 0, Node::new(id, NodeKind::Text(Box::new(t)))).unwrap(); + ids.push(id); + } + (d, ids) +} + +/// Area type in a `w` × `h` pt frame. +fn area_kind(w: f64, h: f64) -> TextKind { + TextKind::Area { frame: vectorcraft_geom::PathData::from_bezpath(&Rect::new(0.0, 0.0, w, h).to_path(0.1)) } +} + +fn text_mut(d: &mut Document, id: NodeId) -> &mut TextObject { + match &mut d.node_mut(id).unwrap().kind { + NodeKind::Text(t) => t, + _ => panic!("not text"), + } +} + +const OVERFLOWS: &str = "This text is far too long to fit in a frame of one hundred and twenty by forty points."; + +/// The Type tools draw the ports of several different selected frames, with and without one of +/// them being edited, without laying any of them out again on the next frame, and draw the same +/// overlays as a tool that lays every frame out afresh. +#[test] +fn type_overlays_keep_the_selected_frames_layouts() { + let (d, ids) = area_frames(&["One", "Two words", "Three words here", OVERFLOWS]); + let (mut sel, p) = (Selection::default(), paint()); + sel.set(ids.iter().copied()); + let c = cx(&d, &sel, &p); + let mut probe = Vec::new(); + push_port(&mut probe, Point::ZERO, PortState::Overflow, [0, 0, 0], 1.0); + let Some(Overlay::Line { color: red, .. }) = probe.last().cloned() else { panic!("the red plus is drawn with lines") }; + let red_plus = |o: &[Overlay]| o.iter().filter(|o| matches!(o, Overlay::Line { color, .. } if *color == red)).count(); + for editing in [None, Some(ids[0])] { + let mut tool = TypeTool::new("areaType"); + if let Some(id) = editing { + tool.start_editing(id, 0); + } + let (first, n) = counted(|| tool.overlays(&c)); + assert!(n > 0, "{editing:?}: the first frame lays the frames out"); + let (second, n) = counted(|| tool.overlays(&c)); + assert_eq!(n, 0, "{editing:?}: the next frame lays none out again"); + assert_eq!(first, second, "{editing:?}"); + let mut fresh = TypeTool::new("areaType"); + if let Some(id) = editing { + fresh.start_editing(id, 0); + } + assert_eq!(second, fresh.overlays(&c), "{editing:?}: what laying out afresh draws"); + assert!(red_plus(&second) > 0, "{editing:?}: the overflowing frame's out port shows its red plus"); + } +} + +/// After Select All in threaded text, the story's other frames are highlighted without laying them +/// out again on the next frame. +#[test] +fn type_overlays_keep_a_selected_storys_layouts() { + let (mut d, ids) = area_frames(&["Story one ", "story two ", "story three ", "story four"]); + d.text_threads.push(ids.clone()); + let (mut sel, p) = (Selection::default(), paint()); + sel.set([ids[0]]); + let story = json!({ "story": ids.iter().map(|id| id.0).collect::>() }); + let c = cx(&d, &sel, &p); + let mut tool = TypeTool::new("areaType"); + tool.start_editing(ids[0], 0); + tool.set_option("selectAll", &story); + assert_eq!(tool.story_others(&c).len(), 3); + let highlights = |o: &[Overlay]| o.iter().filter(|o| matches!(o, Overlay::Highlight { color: [60, 120, 255, 90], .. })).count(); + let (first, n) = counted(|| tool.overlays(&c)); + assert!(n > 0); + let (second, n) = counted(|| tool.overlays(&c)); + assert_eq!(n, 0, "the story's other frames are not laid out again"); + assert_eq!(first, second); + let mut fresh = TypeTool::new("areaType"); + fresh.start_editing(ids[0], 0); + fresh.set_option("selectAll", &story); + assert_eq!(second, fresh.overlays(&c), "what laying out afresh draws"); + assert!(highlights(&second) >= 4, "every frame's text is highlighted: {}", highlights(&second)); +} + +/// A kept layout is used only while its frame's text object is unchanged: editing the text, +/// changing the frame and undoing both lay out just the frames that changed, a frame that is no +/// longer drawn is dropped, and choosing another tool drops them all. +#[test] +fn type_overlays_lay_out_again_only_the_frames_that_changed() { + let (mut d, ids) = area_frames(&["One", "Two", "Three", OVERFLOWS]); + let (mut sel, p) = (Selection::default(), paint()); + sel.set(ids.iter().copied()); + let mut tool = TypeTool::new("areaType"); + let fresh = |d: &Document, sel: &Selection| TypeTool::new("areaType").overlays(&cx(d, sel, &p)); + tool.overlays(&cx(&d, &sel, &p)); + let start = d.clone(); + // Edit the text of one frame. + text_mut(&mut d, ids[1]).runs[0].text = OVERFLOWS.into(); + let (o, n) = counted(|| tool.overlays(&cx(&d, &sel, &p))); + assert_eq!(n, 1, "only the edited frame"); + assert_eq!(o, fresh(&d, &sel)); + // Make another frame tall enough for its text. + text_mut(&mut d, ids[3]).kind = area_kind(120.0, 400.0); + let (o, n) = counted(|| tool.overlays(&cx(&d, &sel, &p))); + assert_eq!(n, 1, "only the changed frame"); + assert_eq!(o, fresh(&d, &sel)); + // Undo puts both back. + let (o, n) = counted(|| tool.overlays(&cx(&start, &sel, &p))); + assert_eq!(n, 2, "the two frames undo changed"); + assert_eq!(o, fresh(&start, &sel)); + // A smaller selection keeps only its frames; the others are laid out again when selected again. + let mut one = Selection::default(); + one.set([ids[0]]); + assert_eq!(counted(|| tool.overlays(&cx(&start, &one, &p))).1, 0); + assert_eq!(kept_frames(&tool), 1); + let (o, n) = counted(|| tool.overlays(&cx(&start, &sel, &p))); + assert_eq!(n, 3); + assert_eq!(o, fresh(&start, &sel)); + tool.deactivate(&cx(&start, &sel, &p)); + assert_eq!(kept_frames(&tool), 0, "another tool chosen"); +} + +/// A story of more frames than [`FRAME_LAYOUTS_MAX`] keeps that many layouts, lays the rest out on +/// each call, and draws what laying every frame out afresh draws. +#[test] +fn type_overlays_keep_at_most_frame_layouts_max() { + let texts = vec!["a "; FRAME_LAYOUTS_MAX + 3]; + let (mut d, ids) = area_frames(&texts); + d.text_threads.push(ids.clone()); + let (mut sel, p) = (Selection::default(), paint()); + sel.set([ids[0]]); + let story = json!({ "story": ids.iter().map(|id| id.0).collect::>() }); + let c = cx(&d, &sel, &p); + let mut tool = TypeTool::new("areaType"); + tool.start_editing(ids[0], 0); + tool.set_option("selectAll", &story); + let first = tool.overlays(&c); + assert_eq!(kept_frames(&tool), FRAME_LAYOUTS_MAX); + let (second, n) = counted(|| tool.overlays(&c)); + assert_eq!(n, 2, "the two other frames past the limit"); + assert_eq!(kept_frames(&tool), FRAME_LAYOUTS_MAX); + assert_eq!(first, second); +} + +#[test] +fn frame_layouts_follow_fonts_and_hyphenation_exceptions() { + // Other tests can load system fonts; this assertion needs its own process-wide database. + #[cfg(not(target_arch = "wasm32"))] + if std::env::var("VECTORCRAFT_FONT_CACHE_TEST_CHILD").as_deref() != Ok("1") { + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "text::tests::frame_layouts_follow_fonts_and_hyphenation_exceptions", "--nocapture", "--test-threads=1"]) + .env("VECTORCRAFT_FONT_CACHE_TEST_CHILD", "1") + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"), + "isolated font cache test failed:\n{stdout}\n{}", + String::from_utf8_lossy(&output.stderr), + ); + return; + } + let (mut d, ids) = area_frames(&["One", "Two", "Three ", "four"]); + d.text_threads.push(vec![ids[2], ids[3]]); + let (mut sel, p) = (Selection::default(), paint()); + sel.set([ids[0], ids[1], ids[2]]); + let c = cx(&d, &sel, &p); + let mut tool = TypeTool::new("areaType"); + tool.start_editing(ids[2], 0); + tool.set_option("selectAll", &json!({ "story": [ids[2].0, ids[3].0] })); + tool.overlays(&c); + assert_eq!(counted(|| tool.overlays(&c)).1, 0); + // Two selected frames, the story's other frame and the edited one. + let font = vectorcraft_text::test_fonts::variable_font().unwrap(); + assert!(FontDb::global().add_font(font) > 0, "the test font is new to this process"); + assert_eq!(counted(|| tool.overlays(&c)).1, 4, "a font added after the layouts refreshes them"); + assert_eq!(counted(|| tool.overlays(&c)).1, 0); + vectorcraft_text::set_hyphenation_exceptions(&vectorcraft_text::hyphenation_exceptions()); + assert_eq!(counted(|| tool.overlays(&c)).1, 4, "new hyphenation exceptions refresh them"); +} + +/// Times the Type tool's overlays on 200 selected area type frames of about 400 characters, one of +/// them edited, and on a 5-frame story after Select All, laying every frame out on each call as the +/// tool did before it kept their layouts (base) against keeping them (kept). Run with +/// `cargo test --release -p vectorcraft-tools --lib type_overlays_timing -- --ignored --nocapture`. +#[test] +#[ignore = "timing, run by hand"] +fn type_overlays_timing() { + use std::time::Instant; + let words = "The quick brown fox jumps over the lazy dog while seven wizards box. ".repeat(6); + let texts: Vec = (0..200).map(|i| format!("{i} {words}")).collect(); + let (mut d, ids) = area_frames(&texts.iter().map(String::as_str).collect::>()); + for id in &ids { + text_mut(&mut d, *id).kind = area_kind(200.0, 200.0); + } + let story: Vec = ids[..5].to_vec(); + d.text_threads.push(story.clone()); + let p = paint(); + let mut all = Selection::default(); + all.set(ids.iter().copied()); + let mut first = Selection::default(); + first.set([ids[0]]); + // Before, the selected frames' layouts replaced the edited one's single kept layout; with only + // the edited frame selected, it stayed. + let cases = [("200 selected frames, one edited", &all, None, true), ("5-frame story, Select All", &first, Some(story), false)]; + for (name, sel, story, evicted) in cases { + let c = cx(&d, sel, &p); + let mut tool = TypeTool::new("areaType"); + tool.start_editing(ids[0], 0); + if let Some(s) = &story { + tool.set_option("selectAll", &json!({ "story": s.iter().map(|id| id.0).collect::>() })); + } + let expected = tool.overlays(&c); + tool.frames.lock().unwrap().clear(); + if evicted { + *tool.cache.lock().unwrap() = None; + } + let (_, before) = counted(|| tool.overlays(&c)); + let (_, after) = counted(|| tool.overlays(&c)); + println!("{name}: {before} layouts per call before, {after} after"); + let calls = 20; + let (mut base, mut kept) = (Vec::new(), Vec::new()); + for _ in 0..7 { + let start = Instant::now(); + for _ in 0..calls { + // Before: the other frames were laid out on every call. + tool.frames.lock().unwrap().clear(); + if evicted { + *tool.cache.lock().unwrap() = None; + } + assert_eq!(tool.overlays(&c), expected); + } + base.push(start.elapsed().as_secs_f64() * 1000.0 / f64::from(calls)); + let start = Instant::now(); + for _ in 0..calls { + assert_eq!(tool.overlays(&c), expected); + } + kept.push(start.elapsed().as_secs_f64() * 1000.0 / f64::from(calls)); + } + let median = |v: &mut Vec| { + v.sort_by(f64::total_cmp); + v[v.len() / 2] + }; + println!("{name}: base runs {base:.3?} ms per call, kept runs {kept:.3?} ms per call"); + println!("{name}: median base {:.3} ms, kept {:.3} ms per call", median(&mut base), median(&mut kept)); + } } /// Type on a path has its in port just before its start bracket and its out port just past its diff --git a/crates/tools/src/text/tool.rs b/crates/tools/src/text/tool.rs index e18754f0ca..2945777610 100644 --- a/crates/tools/src/text/tool.rs +++ b/crates/tools/src/text/tool.rs @@ -472,6 +472,7 @@ impl Tool for TypeTool { } fn deactivate(&mut self, cx: &ToolContext) -> Vec { self.prev_tool = None; + self.frames.get_mut().unwrap_or_else(|e| e.into_inner()).clear(); self.finish(cx) } /// Editing ends when a command takes the text out of the selection (Deselect, another object @@ -609,6 +610,25 @@ impl Tool for TypeTool { _ => {} } } + /// The calls [`Self::set_option`] takes: `commitTyping`, `endTyping`, `selectAll` and + /// `stopEditing` take any value, the others the shapes they read. + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + let index = |a: &str, b: &str| v.get(a).or_else(|| v.get(b)).and_then(Value::as_u64).is_some(); + let ok = match key { + "textSelection" => index("editing", "id") && index("anchor", "start") && index("caret", "end"), + "select" => index("start", "start") && index("end", "end"), + "prevTool" | "previousTool" => return crate::option_check::string_or_null(key, v), + "copy" => serde_json::from_value::>(v.clone()).is_ok(), + "commitTyping" | "endTyping" | "selectAll" | "stopEditing" => true, + _ => return Err(crate::option_check::unknown(key)), + }; + let shape = match key { + "textSelection" => "{editing, anchor, caret} with whole numbers", + "select" => "{start, end} with whole numbers", + _ => "a list of text runs", + }; + if ok { Ok(()) } else { Err(format!("`{key}` must be {shape}")) } + } fn overlays(&self, cx: &ToolContext) -> Vec { let mut o = self.snap.guides().to_vec(); if let (Some((_, s)), Some(d)) = (self.press, self.drag) { @@ -633,13 +653,17 @@ impl Tool for TypeTool { o.push(Overlay::Measure { p: d, text: cx.size_label(size.width, size.height) }); } } + // The other frames this call draws keep their layouts for the next call; the rest are dropped. + let fonts = vectorcraft_text::layout_inputs(); + let mut now = self.frames.lock().unwrap_or_else(|e| e.into_inner()); + let mut was = std::mem::take(&mut *now); // The ports of selected area type and type on a path, as many as show ([`PORTS_MAX`]), the // edited one's included. let shown = ports_shown(cx.doc, &cx.selection.objects); if shown { for id in cx.selection.objects.iter().filter(|id| Some(**id) != self.editing) { if let Some(t) = ported(cx.doc, *id) { - let lay = self.layout(t); + let lay = Self::frame_layout(&mut now, &mut was, fonts, *id, t); ports(cx, *id, t, lay.overflow, &mut o); } } @@ -688,7 +712,7 @@ impl Tool for TypeTool { if self.preedit.is_none() { for f in self.story_others(cx) { let Some(other) = Self::text(cx, f) else { continue }; - let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), other); + let lay = Self::frame_layout(&mut now, &mut was, fonts, f, other); for q in vectorcraft_text::selection_quads(&lay, 0, edit::runs_len(&other.runs)) { o.push(Overlay::Highlight { quad: q.map(|p| other.xf * p), color: [60, 120, 255, 90] }); } diff --git a/crates/tools/src/xform/artboard.rs b/crates/tools/src/xform/artboard.rs index 5af642c44b..e8cac59c88 100644 --- a/crates/tools/src/xform/artboard.rs +++ b/crates/tools/src/xform/artboard.rs @@ -726,6 +726,18 @@ impl Tool for ArtboardTool { } } + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "active" if value.as_u64().is_some() => Ok(()), + "active" => Err("`active` must be an artboard index: a whole number from 0".into()), + "selected" if value.as_array().is_some_and(|a| !a.is_empty() && a.iter().all(|i| i.as_u64().is_some())) => Ok(()), + "selected" => Err("`selected` must be a list of artboard indexes, the active one first".into()), + "moveArt" | "scaleArt" | "suppressFitClick" => c::boolean(key, value), + _ => Err(c::unknown(key)), + } + } + /// A drag is moving or resizing artboards (Artboard Options › Update While Dragging reads it). fn transforming(&self) -> bool { matches!(self.drag, Some(Drag::Move { began: true, .. } | Drag::Resize { began: true, .. })) diff --git a/crates/tools/src/xform/eyedropper.rs b/crates/tools/src/xform/eyedropper.rs index eb1b8b3895..7b91731691 100644 --- a/crates/tools/src/xform/eyedropper.rs +++ b/crates/tools/src/xform/eyedropper.rs @@ -593,6 +593,16 @@ impl Tool for EyedropperTool { } } + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "stop" => c::string_or_null(key, value), + "brushKeyColor" => c::boolean(key, value), + "textSelection" => self.text_selection.check_option(key, value), + _ => Err(c::unknown(key)), + } + } + /// Drop the range when its text is removed or no longer selected. fn after_command(&mut self, cx: &ToolContext) -> Vec { self.text_selection.after_command(cx) diff --git a/crates/tools/src/xform/free.rs b/crates/tools/src/xform/free.rs index 1583584940..6b7f213469 100644 --- a/crates/tools/src/xform/free.rs +++ b/crates/tools/src/xform/free.rs @@ -237,7 +237,15 @@ impl FreeTransformTool { self.measure = cx.transform_tools_guides.then(|| (p, cx.size_label(nr.width(), nr.height()))); bx.conjugate(a) } - Op::Shear(h) => bx.conjugate(shear_for_side(bx.rect, h, local, m.alt)), + Op::Shear(h) => { + let a = shear_for_side(bx.rect, h, local, m.alt); + // The shear's slope, read from the matrix the preview applies, labeled with the + // angle the Shear tool shows for the same slant. + let [_, vertical, horizontal, ..] = a.as_coeffs(); + let k = if matches!(h, Handle::Top | Handle::Bottom) { horizontal } else { vertical }; + self.measure = cx.transform_tools_guides.then(|| (p, format!("{:.1}°", 0.0 - k.atan().to_degrees()))); + bx.conjugate(a) + } Op::Rotate => { let (a, deg) = rotate_for_drag(bx.center(), d.start, p, shift); self.measure = cx.transform_tools_guides.then(|| (p, format!("{:.1}°", -deg))); @@ -379,6 +387,15 @@ impl Tool for FreeTransformTool { } } + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "mode" => c::one_of(key, value, &["free", "perspective", "distort", "freeDistort"]), + "constrain" => c::boolean(key, value), + _ => Err(c::unknown(key)), + } + } + fn deactivate(&mut self, _cx: &ToolContext) -> Vec { self.quad = None; self.guides.clear(); @@ -723,4 +740,63 @@ mod tests { t.pointer(&cx(false), &ev(PointerKind::Drag, 220.0, 230.0)); assert!(t.overlays(&cx(false)).iter().all(|o| !matches!(o, Overlay::Measure { .. }))); } + + /// The label a drag shows next to the pointer, and where. + fn shown_measure(t: &FreeTransformTool, cx: &ToolContext) -> Option<(Point, String)> { + t.overlays(cx).into_iter().find_map(|o| if let Overlay::Measure { p, text } = o { Some((p, text)) } else { None }) + } + + /// With Smart Guides' Transform Tools on, a Cmd side-handle shear shows its angle next to the + /// pointer, with the Shear tool's sign: the top side moved right and the right side moved down + /// by 20 pt on the 100 pt square slant 11.3° either way. Alt shears about the center. + #[test] + fn shear_drag_shows_its_angle_with_transform_tools_guides() { + let (d, id) = doc_with_rect(); + let mut s = Selection::default(); + s.add(id); + let p = paint(); + let cx = |on: bool| ToolContext { transform_tools_guides: on, ..cx(&d, &s, &p) }; + let cmd = Mods { cmd: true, ..Default::default() }; + let shear = |c: &ToolContext, from: (f64, f64), to: (f64, f64), m: Mods| { + let mut t = FreeTransformTool::default(); + t.pointer(c, &ev(PointerKind::Down, from.0, from.1).with_mods(m)); + let a = t.pointer(c, &ev(PointerKind::Drag, to.0, to.1).with_mods(m)); + assert_eq!(a[0], Action::Begin("Shear".into())); + let shown = shown_measure(&t, c); + assert_eq!(t.pointer(c, &ev(PointerKind::Up, to.0, to.1).with_mods(m)), vec![Action::Commit]); + assert_eq!(shown_measure(&t, c), None, "the label goes with the drag"); + shown + }; + let on = cx(true); + let off = Vec2::new(on.tol(12.0), on.tol(12.0)); + assert_eq!(shear(&on, (150.0, 100.0), (170.0, 100.0), cmd), Some((Point::new(170.0, 100.0) + off, "11.3°".into()))); + assert_eq!(shear(&on, (200.0, 150.0), (200.0, 170.0), cmd), Some((Point::new(200.0, 170.0) + off, "-11.3°".into()))); + // About the center the lever is half as long: atan(20 / 50). + let alt = Mods { alt: true, ..cmd }; + assert_eq!(shear(&on, (150.0, 100.0), (170.0, 100.0), alt).map(|m| m.1), Some("21.8°".into())); + // A drag straight away from the side, at right angles to it, shears nothing. + assert_eq!(shear(&on, (150.0, 100.0), (150.0, 90.0), cmd).map(|m| m.1), Some("0.0°".into())); + assert_eq!(shear(&cx(false), (150.0, 100.0), (170.0, 100.0), cmd), None); + } + + /// A handle drag that turns into a shear, and back into a scale, labels only what it does now. + #[test] + fn a_handle_drag_that_changes_operation_relabels_it() { + let (d, id) = doc_with_rect(); + let mut s = Selection::default(); + s.add(id); + let p = paint(); + let cx = ToolContext { transform_tools_guides: true, ..cx(&d, &s, &p) }; + let cmd = Mods { cmd: true, ..Default::default() }; + let mut t = FreeTransformTool::default(); + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 100.0)); + t.pointer(&cx, &ev(PointerKind::Drag, 150.0, 90.0)); + let size = cx.size_label(100.0, 110.0); + assert_eq!(shown_measure(&t, &cx).map(|m| m.1), Some(size.clone())); + let a = t.pointer(&cx, &ev(PointerKind::Drag, 170.0, 100.0).with_mods(cmd)); + assert_eq!(a[..2], [Action::Cancel, Action::Begin("Shear".into())]); + assert_eq!(shown_measure(&t, &cx).map(|m| m.1), Some("11.3°".into())); + t.pointer(&cx, &ev(PointerKind::Drag, 150.0, 90.0)); + assert_eq!(shown_measure(&t, &cx).map(|m| m.1), Some(size)); + } } diff --git a/crates/tools/src/xform/transform.rs b/crates/tools/src/xform/transform.rs index 16a1b93a8a..339984e9a1 100644 --- a/crates/tools/src/xform/transform.rs +++ b/crates/tools/src/xform/transform.rs @@ -432,6 +432,15 @@ impl Tool for TransformTool { } } + /// `origin` is `[x, y]`, or null to clear it. + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + if key != "origin" { + return Err(crate::option_check::unknown(key)); + } + let point = value.as_array().is_some_and(|a| a.len() == 2 && a.iter().all(|n| n.as_f64().is_some_and(f64::is_finite))); + if point || value.is_null() { Ok(()) } else { Err("`origin` must be [x, y] with finite numbers, or null".into()) } + } + fn deactivate(&mut self, _cx: &ToolContext) -> Vec { if self.end_drag().is_some_and(|d| d.began) { vec![Action::Cancel] } else { vec![] } } diff --git a/crates/ui-egui/src/addons.rs b/crates/ui-egui/src/addons.rs index ec1207ad46..b22f6cb939 100644 --- a/crates/ui-egui/src/addons.rs +++ b/crates/ui-egui/src/addons.rs @@ -16,6 +16,7 @@ pub mod polygonal_lasso; pub mod select; pub mod shapes; pub mod typetools; +pub mod units; use crate::menus::Item; @@ -38,6 +39,7 @@ pub fn plugin_menu() -> Vec { Item::Sub("Selection Tools", select::menu()), Item::Sub("Smart Pen", pen::menu()), Item::Sub("Type Tools", typetools::menu()), + Item::Sub("Unit Converter", units::menu()), Item::Sep, ] } diff --git a/crates/ui-egui/src/addons/packaging.rs b/crates/ui-egui/src/addons/packaging.rs index 5b37b52abf..3f4d2e4551 100644 --- a/crates/ui-egui/src/addons/packaging.rs +++ b/crates/ui-egui/src/addons/packaging.rs @@ -4,7 +4,8 @@ //! paths that role (`addon.packaging.setRole`). Its menu's Role Swatches… picks the swatch that //! carries a role (`addon.packaging.setRoleSwatch`). Its Check button, like the Check Fold Lines menu //! item, checks the fold lines (`addon.packaging.check`) and lists the issues found under it, each -//! with a Select button; each document's list is kept until that document changes. +//! with a Select button; each document's list is kept until that document changes. Its Fold Preview +//! button, like the Fold Preview menu item, shows the blank folded in 3D ([`preview`], `ui.foldPreview`). use std::collections::HashMap; use std::sync::{Arc, Weak}; @@ -26,6 +27,8 @@ pub const SET_ROLE: &str = "addon.packaging.setRole"; pub const SET_ROLE_SWATCH: &str = "addon.packaging.setRoleSwatch"; /// The command that checks the fold lines. pub const CHECK: &str = "addon.packaging.check"; +/// The command that shows the Fold Preview window. +pub const PREVIEW: &str = "ui.foldPreview"; /// The roles by name, as `addon.packaging.setRole` and Role Swatches… take them. pub const ROLES: &[(&str, &str)] = &[("Cut Line", "cut"), ("Crease Line", "crease"), ("Partial Cut Line", "partialCut"), ("Perforation Line", "perforation")]; @@ -47,6 +50,8 @@ pub fn menu() -> Vec { make("Make Perforation Line", "perforation"), Item::Sep, Item::Cmd("Check Fold Lines", CHECK, Value::Null), + Item::Sep, + Item::Cmd("Fold Preview", PREVIEW, json!({})), ] } @@ -160,6 +165,11 @@ fn show_check(app: &mut VectorcraftApp, ui: &mut Ui) { if widgets::flat_button(ui, tl!("Check"), width).clicked() { run_check(app, ui.ctx(), json!({})); } + if widgets::flat_button(ui, tl!("Fold Preview"), width).clicked() + && let Err(e) = app.run(PREVIEW, json!({})) + { + app.status(e); + } let Some(checked) = last_check(app, ui.ctx()) else { return }; ui.add_space(4.0); dim_label(ui, &crate::i18n::msg(&checked.summary())); @@ -285,5 +295,7 @@ pub fn panel_menu(app: &mut VectorcraftApp, ui: &mut Ui) { } } +pub mod preview; + #[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/addons/packaging/preview.rs b/crates/ui-egui/src/addons/packaging/preview.rs new file mode 100644 index 0000000000..97a8ebd988 --- /dev/null +++ b/crates/ui-egui/src/addons/packaging/preview.rs @@ -0,0 +1,705 @@ +//! The Fold Preview window: the document's blank folded into its 3D shape +//! ([`vectorcraft_three_d::fold::fold`]), with the printed art on the outside of each panel and the +//! board's inside color on the back, drawn by [`vectorcraft_three_d::fold::raster::render`]. +//! +//! The window folds the blank that the document's shown fold lines make, about its largest panel +//! or the panel the user double-clicked. Its print is a raster of the document with the fold lines +//! and the layers that do not print left out ([`vectorcraft_engine::cmd::print_hidden`]), rendered +//! once per document revision, off the UI thread on native builds ([`crate::thumb_worker`]), and +//! sampled through each panel's projective map when the fold, the view or the print changes. Dragging turns the view, a Shift-drag +//! keeps to one axis, a middle-drag or a Space-drag moves it, the wheel zooms, a double-click on a +//! panel makes it the base, and the arrow keys turn the view by 5° when it has the keyboard focus. +//! The settings live in `UiState::fold_preview` (`ui.inspect`); `ui.foldPreview` sets them. + +use std::sync::Arc; + +use egui::{Color32, Rect, Sense, Ui, vec2}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use vectorcraft_geom::{Point, Rect as DRect}; +use vectorcraft_three_d::fold::raster::{self, Camera, Image, MAX_PIXELS, MAX_SIDE, Print}; +use vectorcraft_three_d::fold::{Blank, Folded, fold, pick}; + +use crate::VectorcraftApp; +use crate::thumb_worker::{Settle, ThumbWorker}; +use crate::widgets::{self, dim_label}; + +/// The window's id (`window.panel {panel: "foldPreview"}`). +pub const ID: &str = "foldPreview"; + +/// The view presets: label, id, the turn about x (the top toward the viewer) and about y (the +/// right side toward the viewer), in degrees. +pub const VIEWS: [(&str, &str, f64, f64); 7] = [ + ("Front", "front", 0.0, 0.0), + ("Back", "back", 0.0, 180.0), + ("Left", "left", 0.0, -90.0), + ("Right", "right", 0.0, 90.0), + ("Top", "top", 90.0, 0.0), + ("Bottom", "bottom", -90.0, 0.0), + ("Three-Quarter", "threeQuarter", 25.0, 35.0), +]; + +/// The tolerance the window folds with (points), as Check Fold Lines' default. +const TOLERANCE: f64 = 0.1; +/// The share of the view's shorter side the folded blank fills at a zoom of 1. +const FIT: f64 = 0.45; +/// The print raster's longest side, in pixels, and the fewest pixels it gives a point. +const PRINT_SIDE: f64 = 2048.0; +/// Degrees the view turns for each point dragged, and for each arrow key press. +const DRAG_TURN: f64 = 0.5; +const KEY_TURN: f64 = 5.0; + +/// The window's settings (kept with the UI state). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct Settings { + /// How far the blank is folded: 0 flat, 1 every hinge at its angle. + pub amount: f64, + /// The view's turn, in degrees (see [`VIEWS`]). + pub rotate_x: f64, + pub rotate_y: f64, + /// The zoom: 1 fits the folded blank in the view. + pub zoom: f64, + /// How far the view is moved, in points. + pub pan: [f64; 2], + /// The field of view in degrees; 0 for none. + pub perspective: f64, + /// The board's inside color: `#rrggbb`, the name of a swatch, or empty for white. + pub inside: String, + /// Draw the fold lines on the print. + pub show_fold_lines: bool, + /// The base panel: the one under this point (document coordinates); the largest when `None`. + pub base: Option<[f64; 2]>, +} + +impl Default for Settings { + fn default() -> Self { + let (_, _, rotate_x, rotate_y) = VIEWS[6]; + Self { + amount: 1.0, + rotate_x, + rotate_y, + zoom: 1.0, + pan: [0.0; 2], + perspective: 0.0, + inside: String::new(), + show_fold_lines: false, + base: None, + } + } +} + +impl Settings { + /// The view preset these settings show, if any. + fn view(&self) -> Option<&'static (&'static str, &'static str, f64, f64)> { + VIEWS.iter().find(|v| (v.2 - self.rotate_x).abs() < 1e-9 && (v.3 - self.rotate_y).abs() < 1e-9) + } + + /// These settings with every value in the range `ui.foldPreview` allows: saved UI state is read + /// as it was stored. A value that is not a number takes its default. + fn clamped(mut self) -> Self { + let within = |v: f64, lo: f64, hi: f64, or: f64| if v.is_finite() { v.clamp(lo, hi) } else { or }; + let turn = |v: f64| if (-180.0..=180.0).contains(&v) { v } else { wrapped(v) }; + let fresh = Settings::default(); + self.amount = within(self.amount, 0.0, 1.0, fresh.amount); + self.zoom = within(self.zoom, 0.1, 8.0, fresh.zoom); + self.perspective = within(self.perspective, 0.0, 160.0, fresh.perspective); + (self.rotate_x, self.rotate_y) = (turn(self.rotate_x), turn(self.rotate_y)); + self.pan = self.pan.map(|v| if v.is_finite() { v } else { 0.0 }); + self.base = self.base.filter(|b| b.iter().all(|v| v.is_finite())); + self + } +} + +/// `angle` (degrees) brought into -180 to 180. +fn wrapped(angle: f64) -> f64 { + let a = (angle + 180.0).rem_euclid(360.0) - 180.0; + if a.is_finite() { a } else { 0.0 } +} + +/// What the print raster shows: the document, its revision, whether the fold lines are drawn, and +/// the region and size. +#[derive(Clone, Copy, Debug, PartialEq)] +struct PrintKey { + uid: u64, + revision: u64, + fold_lines: bool, + region: [u64; 4], + width: u32, + height: u32, +} + +/// The last frame drawn: its size in pixels and how long the fold and the drawing took (ms). +#[derive(Clone, Copy, Debug, Default)] +struct Frame { + width: u32, + height: u32, + fold_ms: f64, + draw_ms: f64, +} + +/// A document's blanks and whether its fold lines have an error, by (uid, revision). +type Blanks = ((u64, u64), Arc>, bool); + +/// What a fold folds: the document (uid, revision), the blank, the base panel and the amount's bits. +type FoldKey = (u64, u64, usize, usize, u64); + +/// What the last image shows: the fold, the camera, the inside color and the print. +#[derive(Clone, Copy, Debug, PartialEq)] +struct DrawKey { + fold: FoldKey, + camera: Camera, + inside: [u8; 4], + print: Option, +} + +#[derive(Default)] +struct Cache { + blanks: Option, + /// The last fold, what it folds and how long it took (ms). + folded: Option<(FoldKey, Arc, f64)>, + /// What the texture shows. + drawn: Option, + /// Folds worked out and images rendered (tests count them). + folds: u64, + renders: u64, + /// The print shown and what it shows. + print: Option<(PrintKey, Arc)>, + /// Renders the print off the UI thread (None: on this thread). + worker: Option>, + worker_started: bool, + pending: Option, + settle: Settle, + tex: Option, + /// The last frame's image, for double-click picking, and the screen rect it filled. + image: Option<(Image, Rect)>, + frame: Option, + /// Prints rendered (tests count them). + prints: u64, +} + +thread_local! { + static CACHE: crate::graphics::TexCache = crate::graphics::TexCache::default(); + static RENDERER: std::cell::RefCell = std::cell::RefCell::new(vectorcraft_render::Renderer::new()); +} + +/// The board's inside color (straight RGBA) for `inside`: white when it is empty, a swatch of `d` +/// with a plain color, or else `#rrggbb`; `None` for anything else. +fn inside_color(d: &vectorcraft_engine::doc::Document, inside: &str) -> Option<[u8; 4]> { + if inside.is_empty() { + return Some([255; 4]); + } + match d.swatch(inside).map(|s| &s.paint) { + Some(vectorcraft_color::Paint::Solid { color, .. }) => Some(color.to_rgba8(1.0)), + _ if inside.starts_with('#') => vectorcraft_color::Color::from_hex(inside).map(|c| c.to_rgba8(1.0)), + _ => None, + } +} + +/// The document rect a print of `blank` covers: its panels' bounds, with a point to spare. +fn print_region(blank: &Blank) -> Option { + let r = blank.panels.iter().filter_map(|p| p.outline.bounds()).reduce(|a, b| a.union(b))?; + let r = r.inflate(1.0, 1.0); + (r.width() > 0.0 && r.height() > 0.0 && r.is_finite()).then_some(r) +} + +/// The pixel size of the print of `region`: its longest side [`PRINT_SIDE`]. +fn print_size(region: DRect) -> (u32, u32, f64) { + let scale = PRINT_SIDE / region.width().max(region.height()); + let side = |len: f64| ((len * scale).ceil() as u32).clamp(1, MAX_SIDE); + (side(region.width()), side(region.height()), scale) +} + +impl Cache { + /// The blanks of document `uid` at `revision`, worked out again only when it changed. + fn blanks(&mut self, uid: u64, revision: u64, d: &vectorcraft_engine::doc::Document) -> (Arc>, bool) { + if let Some((key, blanks, errors)) = &self.blanks + && *key == (uid, revision) + { + return (blanks.clone(), *errors); + } + let (blanks, issues) = vectorcraft_engine::cmd::fold_source(d); + let errors = issues.iter().any(|i| i.code.is_error()); + let blanks = Arc::new(blanks); + self.blanks = Some(((uid, revision), blanks.clone(), errors)); + (blanks, errors) + } + + /// `blank` folded about `panel` by `amount` (what `key` names), worked out again only when the + /// key changed, and how long that took (ms). + fn fold(&mut self, key: FoldKey, blank: &Blank, panel: usize, amount: f64) -> Option<(Arc, f64)> { + if let Some((k, f, ms)) = &self.folded + && *k == key + { + return Some((f.clone(), *ms)); + } + let t0 = crate::now_ms(); + let f = Arc::new(fold(blank, Some(panel), amount, TOLERANCE)?); + let ms = crate::now_ms() - t0; + self.folded = Some((key, f.clone(), ms)); + self.folds += 1; + Some((f, ms)) + } + + /// Bring the print up to `key`: on the worker when there is one, else here, and not before the + /// document has settled unless there is no print of it yet. + fn update_print(&mut self, ctx: &egui::Context, doc: &Arc, key: PrintKey, region: DRect, scale: f64) { + if !self.worker_started { + self.worker_started = true; + self.worker = ThumbWorker::spawn(ctx, "fold-preview"); + } + let done = match self.worker.as_ref().map(ThumbWorker::poll) { + Some(Some(done)) => done, + Some(None) => { + (self.worker, self.pending) = (None, None); + vec![] + } + None => vec![], + }; + for d in done { + if self.pending == Some(d.key) { + self.pending = None; + } + if let Some(img) = d.img { + self.keep_print(d.key, img); + } + } + let shown = self.print.as_ref().map(|(k, _)| *k); + if shown == Some(key) || self.pending == Some(key) { + return; + } + let have = shown.is_some_and(|k| k.uid == key.uid); + if have && !self.settle.settled(ctx, key.uid, key.revision, ctx.input(|i| i.time)) { + return; + } + let opts = vectorcraft_render::RenderOptions { + skip_templates: true, + image_mips: true, + hidden: vectorcraft_engine::cmd::print_hidden(doc, key.fold_lines), + ..Default::default() + }; + if let Some(w) = &self.worker { + let (doc, opts) = (doc.clone(), opts.clone()); + if w.submit((), key, Box::new(move |r| Some(r.render_region_with(&doc, region, scale, &opts)))) { + self.pending = Some(key); + return; + } + self.worker = None; + } + let img = RENDERER.with(|r| r.borrow_mut().render_region_with(doc, region, scale, &opts)); + self.keep_print(key, img); + } + + /// The print to draw for `want`: the one shown when it is of the same document, blank region and + /// Show Fold Lines setting (an older revision while the new one renders), else none. + fn print_for(&self, want: &PrintKey) -> Option<(PrintKey, Arc)> { + let same = |k: &PrintKey| (k.uid, k.fold_lines, k.region) == (want.uid, want.fold_lines, want.region); + self.print.as_ref().filter(|(k, _)| same(k)).map(|(k, p)| (*k, p.clone())) + } + + fn keep_print(&mut self, key: PrintKey, img: vectorcraft_render::Rendered) { + let region = + DRect::new(f64::from_bits(key.region[0]), f64::from_bits(key.region[1]), f64::from_bits(key.region[2]), f64::from_bits(key.region[3])); + if let Some(print) = Print::new(region, img.width, img.height, img.pixels) { + self.print = Some((key, Arc::new(print))); + self.prints += 1; + } + } +} + +/// `ui.foldPreview {amount?, view?, rotateX?, rotateY?, zoom?, perspective?, inside?, +/// showFoldLines?, base?}`: set the window's settings, show it, and answer with them and the last +/// frame's size and times. A value of the wrong kind or out of range is an error, and nothing is +/// set. +pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result { + let mut set = app.ui.fold_preview.clone(); + let number = |key: &str, lo: f64, hi: f64| -> Result, String> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(v) => match v.as_f64() { + Some(n) if (lo..=hi).contains(&n) => Ok(Some(n)), + _ => Err(format!("`{key}` must be a number from {lo} to {hi}")), + }, + } + }; + if let Some(a) = number("amount", 0.0, 1.0)? { + set.amount = a; + } + match p.get("view") { + None | Some(Value::Null) => {} + Some(v) => { + let (_, _, x, y) = v + .as_str() + .and_then(|v| VIEWS.iter().find(|view| view.1 == v)) + .ok_or_else(|| format!("`view` must be one of {}", VIEWS.iter().map(|v| v.1).collect::>().join(", ")))?; + (set.rotate_x, set.rotate_y) = (*x, *y); + } + } + if let Some(x) = number("rotateX", -180.0, 180.0)? { + set.rotate_x = x; + } + if let Some(y) = number("rotateY", -180.0, 180.0)? { + set.rotate_y = y; + } + if let Some(z) = number("zoom", 0.1, 8.0)? { + set.zoom = z; + } + if let Some(v) = number("perspective", 0.0, 160.0)? { + set.perspective = v; + } + match p.get("inside") { + None | Some(Value::Null) => {} + Some(v) => { + let inside = v.as_str().filter(|inside| { + inside.is_empty() + || app.session.active().and_then(|st| inside_color(&st.doc, inside)).is_some() + || (inside.starts_with('#') && vectorcraft_color::Color::from_hex(inside).is_some()) + }); + let Some(inside) = inside else { + return Err(format!("`inside` must be #rrggbb, the name of a swatch with a plain color, or empty for white, not {v}")); + }; + set.inside = inside.to_string(); + } + } + match p.get("showFoldLines") { + None | Some(Value::Null) => {} + Some(v) => set.show_fold_lines = v.as_bool().ok_or("`showFoldLines` must be true or false")?, + } + match p.get("base") { + None => {} + Some(Value::Null) => set.base = None, + Some(v) => { + let a = v.as_array().filter(|a| a.len() == 2); + let xy: Option> = a.map(|a| a.iter().filter_map(Value::as_f64).filter(|n| n.is_finite()).collect()); + let Some(&[x, y]) = xy.as_deref() else { return Err("`base` must be a point: [x, y], or null".into()) }; + let blanks = app.session.active().map(|st| vectorcraft_engine::cmd::fold_source(&st.doc).0).unwrap_or_default(); + if pick(&blanks, Some(Point::new(x, y))).is_none() { + return Err("`base` is in no panel".into()); + } + set.base = Some([x, y]); + } + } + if p.get("view").is_some_and(|v| !v.is_null()) || p.get("zoom").is_some_and(|v| !v.is_null()) { + set.pan = [0.0; 2]; + } + app.ui.fold_preview = set; + crate::panel_docking::reveal_panel(app, ID)?; + if let Some(ctx) = &app.ui_ctx { + ctx.request_repaint(); + } + Ok(state(app)) +} + +/// The window's settings and the last frame's size and times. +fn state(app: &VectorcraftApp) -> Value { + let frame = CACHE.with(|c| c.borrow().frame); + let mut out = serde_json::to_value(&app.ui.fold_preview).unwrap_or_default(); + if let Some(o) = out.as_object_mut() { + o.insert( + "frame".into(), + frame.map_or(Value::Null, |f| json!({"width": f.width, "height": f.height, "foldMs": f.fold_ms, "drawMs": f.draw_ms})), + ); + } + out +} + +/// The toolbar: the view presets, Perspective, Inside, Show Fold Lines and Reset. +fn toolbar(app: &VectorcraftApp, ui: &mut Ui, set: &mut Settings) { + ui.horizontal_wrapped(|ui| { + let labels: Vec<&str> = VIEWS.iter().map(|v| v.0).collect(); + let current = set.view().map_or("", |v| v.0); + if let Some(i) = widgets::dropdown_named(ui, "fold-preview-view", Some(tl!("View")), current, &labels, 120.0) + && let Some(&(_, _, x, y)) = VIEWS.get(i) + { + (set.rotate_x, set.rotate_y, set.pan) = (x, y, [0.0; 2]); + } + let swatches: Vec = app.session.active().map_or_else(Vec::new, |st| { + st.doc.swatches.iter().filter(|s| matches!(s.paint, vectorcraft_color::Paint::Solid { .. })).map(|s| s.name.clone()).collect() + }); + let mut names: Vec<&str> = vec![tl!("White")]; + names.extend(swatches.iter().map(String::as_str)); + let shown = if set.inside.is_empty() { tl!("White") } else { set.inside.as_str() }; + ui.label(tl!("Inside")); + if let Some(i) = widgets::dropdown_names_named(ui, "fold-preview-inside", Some(tl!("Inside")), shown, &names, 110.0) { + set.inside = swatches.get(i.wrapping_sub(1)).cloned().unwrap_or_default(); + } + if widgets::check(ui, tl!("Show Fold Lines"), set.show_fold_lines, true) { + set.show_fold_lines = !set.show_fold_lines; + } + if widgets::flat_button_fit(ui, tl!("Reset"), 48.0).clicked() { + let fresh = Settings::default(); + (set.rotate_x, set.rotate_y, set.zoom, set.pan, set.perspective) = (fresh.rotate_x, fresh.rotate_y, 1.0, [0.0; 2], 0.0); + } + }); + ui.horizontal(|ui| { + ui.label(tl!("Perspective")); + widgets::slider(ui, egui::Slider::new(&mut set.perspective, 0.0..=160.0).suffix("°").fixed_decimals(0)); + }); +} + +/// The Fold and Zoom sliders. +fn sliders(ui: &mut Ui, set: &mut Settings) { + ui.horizontal(|ui| { + ui.label(tl!("Fold")); + let mut percent = set.amount * 100.0; + if widgets::slider(ui, egui::Slider::new(&mut percent, 0.0..=100.0).suffix("%").fixed_decimals(0)).changed() { + set.amount = (percent / 100.0).clamp(0.0, 1.0); + } + }); + ui.horizontal(|ui| { + ui.label(tl!("Zoom")); + let mut percent = set.zoom * 100.0; + if widgets::slider(ui, egui::Slider::new(&mut percent, 10.0..=800.0).suffix("%").fixed_decimals(0).logarithmic(true)).changed() { + set.zoom = (percent / 100.0).clamp(0.1, 8.0); + } + }); +} + +/// Turns, moves and zooms the view with the pointer, the wheel and the arrow keys, and picks the +/// base panel of `blank` (the blank `key` folds) on a double-click. +fn interact(ui: &Ui, response: &egui::Response, set: &mut Settings, blank: Option<(&Blank, FoldKey)>) { + if response.clicked() || response.drag_started() { + response.request_focus(); + } + let (shift, space) = ui.input(|i| (i.modifiers.shift, i.key_down(egui::Key::Space))); + let delta = response.drag_delta(); + if delta != egui::Vec2::ZERO { + if response.dragged_by(egui::PointerButton::Middle) || (space && response.dragged_by(egui::PointerButton::Primary)) { + set.pan[0] += f64::from(delta.x); + set.pan[1] += f64::from(delta.y); + } else if response.dragged_by(egui::PointerButton::Primary) { + let (mut dx, mut dy) = (f64::from(delta.x), f64::from(delta.y)); + if shift { + if dx.abs() >= dy.abs() { + dy = 0.0; + } else { + dx = 0.0; + } + } + set.rotate_y = wrapped(set.rotate_y + dx * DRAG_TURN); + set.rotate_x = wrapped(set.rotate_x + dy * DRAG_TURN); + } + } + if response.hovered() { + let scroll = f64::from(ui.input(|i| i.smooth_scroll_delta.y + (i.zoom_delta() - 1.0) * 200.0)); + if scroll != 0.0 { + set.zoom = (set.zoom * (scroll * 0.002).exp()).clamp(0.1, 8.0); + } + } + if response.has_focus() { + // The view keeps the arrow keys, so they turn it rather than move the focus on. + ui.memory_mut(|m| { + m.set_focus_lock_filter(response.id, egui::EventFilter { horizontal_arrows: true, vertical_arrows: true, ..Default::default() }) + }); + let presses = |key| ui.input_mut(|i| i.count_and_consume_key(egui::Modifiers::NONE, key)) as f64 * KEY_TURN; + let (left, right, up, down) = + (presses(egui::Key::ArrowLeft), presses(egui::Key::ArrowRight), presses(egui::Key::ArrowUp), presses(egui::Key::ArrowDown)); + if left + right + up + down > 0.0 { + set.rotate_y = wrapped(set.rotate_y + right - left); + set.rotate_x = wrapped(set.rotate_x + down - up); + } + } + if response.double_clicked() + && let Some(pos) = response.interact_pointer_pos() + && let Some((blank, key)) = blank + { + // The image on screen is the last one drawn; its panel numbers are used only while it shows + // the same blank of the same document revision. + let picked = CACHE.with(|c| { + let c = c.borrow(); + let shown = c.drawn.map(|d| (d.fold.0, d.fold.1, d.fold.2)); + if shown != Some((key.0, key.1, key.2)) { + return None; + } + let (img, rect) = c.image.as_ref()?; + let x = (pos.x - rect.left()) / rect.width() * img.width as f32; + let y = (pos.y - rect.top()) / rect.height() * img.height as f32; + img.panel_at(x.max(0.0) as u32, y.max(0.0) as u32) + }); + if let Some(p) = picked.and_then(|i| blank.panels.get(i)).and_then(|p| p.point_inside()) { + set.base = Some([p.x, p.y]); + } + } +} + +/// The status line under the view, in English (shown translated). +fn status(blanks: usize, folded: Option<(&Blank, &Folded)>, errors: bool) -> Vec { + let Some((blank, f)) = folded else { + return vec!["Check the fold lines first.".into()]; + }; + let mut out = vec![crate::i18n::fmt( + "Panels: {panels}, hinges: {hinges}", + &[("panels", &blank.panels.len().to_string()), ("hinges", &blank.hinges.len().to_string())], + )]; + if errors { + out.push("Check the fold lines first.".into()); + } + if blanks > 1 { + out.push(crate::i18n::fmt("Other blanks not shown: {count}", &[("count", &(blanks - 1).to_string())])); + } + if let Some(gap) = f.hinges.iter().filter(|h| !h.closes).map(|h| h.gap).reduce(f64::max) { + out.push(crate::i18n::fmt("A joint does not close by {gap} pt.", &[("gap", &format!("{gap:.1}"))])); + } + if !f.collisions.is_empty() { + out.push("Two panels pass through each other.".into()); + } + out +} + +pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { + let Some(st) = app.session.active() else { + crate::panels::empty_state(ui, "box", tl!("No document"), tl!("Open a document to preview its folded shape.")); + return; + }; + let (uid, revision, doc) = (st.uid, st.revision, st.doc.clone()); + let mut set = app.ui.fold_preview.clone().clamped(); + toolbar(app, ui, &mut set); + let (blanks, errors) = CACHE.with(|c| c.borrow_mut().blanks(uid, revision, &doc)); + let base_point = set.base.map(|[x, y]| Point::new(x, y)); + let picked = pick(&blanks, base_point).or_else(|| pick(&blanks, None)); + let folded = picked.and_then(|(b, panel)| { + let blank = blanks.get(b)?; + let key = (uid, revision, b, panel, set.amount.to_bits()); + let (f, ms) = CACHE.with(|c| c.borrow_mut().fold(key, blank, panel, set.amount))?; + Some((blank, f, key, ms)) + }); + + let bottom = ui.spacing().interact_size.y * 3.0 + 12.0; + let size = vec2(ui.available_width().max(64.0), (ui.available_height() - bottom).max(64.0)); + let (rect, response) = ui.allocate_exact_size(size, Sense::click_and_drag()); + let view_name = set.view().map_or("", |v| v.0); + response.widget_info(|| { + let mut info = egui::WidgetInfo::labeled(egui::Role::Image, true, tl!("Fold Preview")); + info.current_text_value = Some(crate::i18n::t(view_name).to_string()); + info + }); + interact(ui, &response, &mut set, folded.as_ref().map(|(b, _, key, _)| (*b, *key))); + let t = crate::theme::Tokens::get(ui.ctx()); + ui.painter().rect_filled(rect, 2.0, t.pasteboard); + if let Some((blank, f, key, fold_ms)) = &folded { + draw(ui, rect, &doc, *key, blank, f, &set, *fold_ms); + } + if response.has_focus() { + ui.painter().rect_stroke(rect, 2.0, egui::Stroke::new(1.0, t.accent), egui::StrokeKind::Inside); + } + for line in status(blanks.len(), folded.as_ref().map(|(b, f, ..)| (*b, &**f)), errors) { + dim_label(ui, &crate::i18n::msg(&line)); + } + sliders(ui, &mut set); + if set != app.ui.fold_preview { + app.ui.fold_preview = set; + } +} + +/// Draws `blank` folded as `f` (the fold `key` names) into `rect`, with the print of `doc`. The image +/// is rendered again only when the fold, the view, the inside color or the print changed. +#[allow(clippy::too_many_arguments)] +fn draw(ui: &Ui, rect: Rect, doc: &Arc, key: FoldKey, blank: &Blank, f: &Folded, set: &Settings, fold_ms: f64) { + // Pixels per point of the view, lowered when the window has more pixels than the view may have + // in all or along either side, so the image keeps the window's proportions. + let (w, h) = (f64::from(rect.width()), f64::from(rect.height())); + let mut ppp = f64::from(ui.ctx().pixels_per_point()); + let area = w * h * ppp * ppp; + if area > f64::from(MAX_PIXELS) { + ppp *= (f64::from(MAX_PIXELS) / area).sqrt(); + } + ppp = ppp.min(f64::from(MAX_SIDE) / w.max(h).max(1.0)); + let width = ((w * ppp).floor() as u32).clamp(1, MAX_SIDE); + let height = ((h * ppp).floor() as u32).clamp(1, MAX_SIDE); + let Some((lo, hi)) = raster::bounds(blank, f) else { return }; + let center = [(lo[0] + hi[0]) / 2.0, (lo[1] + hi[1]) / 2.0, (lo[2] + hi[2]) / 2.0]; + let radius = ((hi[0] - lo[0]).powi(2) + (hi[1] - lo[1]).powi(2) + (hi[2] - lo[2]).powi(2)).sqrt() / 2.0; + let mut fit = FIT * f64::from(width.min(height)) / radius.max(1e-6); + if set.perspective > 0.0 { + // The eye at two radii from the middle or farther, so at a zoom of 1 the whole blank is in + // front of it. + let focal = f64::from(width.min(height)) / 2.0 / (set.perspective.to_radians() / 2.0).tan(); + fit = fit.min(focal / (2.0 * radius.max(1e-6))); + } + let camera = Camera { + width, + height, + rotate_x: set.rotate_x, + rotate_y: set.rotate_y, + scale: fit * set.zoom, + pan: [set.pan[0] * ppp, set.pan[1] * ppp], + perspective: set.perspective, + center, + }; + let inside = inside_color(doc, &set.inside).unwrap_or([255; 4]); + // While the print of a new revision renders, the last one of the same blank and setting is + // drawn; a print of another document, blank or Show Fold Lines setting is not. + let print = CACHE.with(|c| { + let mut c = c.borrow_mut(); + let region = print_region(blank)?; + let (pw, ph, scale) = print_size(region); + let pkey = PrintKey { + uid: key.0, + revision: key.1, + fold_lines: set.show_fold_lines, + region: [region.x0.to_bits(), region.y0.to_bits(), region.x1.to_bits(), region.y1.to_bits()], + width: pw, + height: ph, + }; + c.update_print(ui.ctx(), doc, pkey, region, scale); + c.print_for(&pkey) + }); + let draw_key = DrawKey { fold: key, camera, inside, print: print.as_ref().map(|(k, _)| *k) }; + let kept = CACHE.with(|c| { + let mut c = c.borrow_mut(); + let Some(tex) = c.tex.as_ref().filter(|_| c.drawn == Some(draw_key)).map(|t| t.id()) else { return false }; + ui.painter().image(tex, rect, Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), Color32::WHITE); + if let Some((_, at)) = &mut c.image { + *at = rect; + } + true + }); + if kept { + return; + } + let t0 = crate::now_ms(); + let scene = raster::Scene { blank, folded: f, print: print.as_ref().map(|(_, p)| &**p), inside, outside: [255; 4], camera }; + let Some(img) = raster::render(&scene) else { return }; + let draw_ms = crate::now_ms() - t0; + let color = egui::ColorImage::from_rgba_premultiplied([img.width as usize, img.height as usize], &img.pixels); + CACHE.with(|c| { + let mut c = c.borrow_mut(); + c.drawn = Some(draw_key); + c.renders += 1; + match &mut c.tex { + Some(tex) => tex.set(color, egui::TextureOptions::LINEAR), + None => c.tex = Some(ui.ctx().load_texture("fold-preview", color, egui::TextureOptions::LINEAR)), + } + if let Some(tex) = &c.tex { + let uv = Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)); + ui.painter().image(tex.id(), rect, uv, Color32::WHITE); + } + c.frame = Some(Frame { width: img.width, height: img.height, fold_ms, draw_ms }); + c.image = Some((img, rect)); + }); +} + +#[cfg(test)] +pub(crate) fn prints_rendered() -> u64 { + CACHE.with(|c| c.borrow().prints) +} + +#[cfg(test)] +pub(crate) fn last_image() -> Option { + CACHE.with(|c| c.borrow().image.as_ref().map(|(i, _)| i.clone())) +} + +/// The folds worked out and the images rendered so far. +#[cfg(test)] +pub(crate) fn work_done() -> (u64, u64) { + CACHE.with(|c| (c.borrow().folds, c.borrow().renders)) +} + +/// The screen rect the last image filled. +#[cfg(test)] +pub(crate) fn last_rect() -> Option { + CACHE.with(|c| c.borrow().image.as_ref().map(|(_, r)| *r)) +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/addons/packaging/preview/tests.rs b/crates/ui-egui/src/addons/packaging/preview/tests.rs new file mode 100644 index 0000000000..c3c69c3f31 --- /dev/null +++ b/crates/ui-egui/src/addons/packaging/preview/tests.rs @@ -0,0 +1,505 @@ +use serde_json::{Value, json}; +use vectorcraft_engine::Session; + +use std::sync::Arc; + +use egui::{Event, Modifiers, PointerButton, Pos2, vec2}; + +use super::{Cache, ID, PrintKey, Settings, inside_color, last_image, last_rect, prints_rendered, show, status, work_done}; +use crate::{VectorcraftApp, menus}; + +/// An app with a tray blank (a 100 pt base at x 140 to 240, y 140 to 240, and a 40 pt wall on each +/// side) and a red square printed on the base, nothing selected → (app, the red square's id). +fn app() -> (VectorcraftApp, u64) { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let path = |app: &mut VectorcraftApp, d: &str| app.run("path.create", json!({ "d": d })).unwrap()["id"].as_u64().unwrap(); + let outline = path(&mut app, "M140 100 L240 100 L240 140 L280 140 L280 240 L240 240 L240 280 L140 280 L140 240 L100 240 L100 140 L140 140 Z"); + let creases = [ + path(&mut app, "M140 140 L240 140"), + path(&mut app, "M240 140 L240 240"), + path(&mut app, "M240 240 L140 240"), + path(&mut app, "M140 240 L140 140"), + ]; + app.run("addon.packaging.setRole", json!({ "role": "cut", "ids": [outline] })).unwrap(); + app.run("addon.packaging.setRole", json!({ "role": "crease", "ids": creases })).unwrap(); + let red = app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 180, "height": 180})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({ "ids": [red] })).unwrap(); + app.run("paint.setFill", json!({ "color": "#ff0000" })).unwrap(); + app.run("paint.setStroke", json!({ "none": true })).unwrap(); + app.run("object.arrange.sendToBack", json!({})).unwrap(); + app.run("select.none", json!({})).unwrap(); + (app, red) +} + +/// Draws the window in a 520 × 440 frame, twice (egui lays out on the first). +fn frame(app: &mut VectorcraftApp) { + frame_at(app, 1.0); +} + +/// [`frame`] at `zoom` pixels per point. +fn frame_at(app: &mut VectorcraftApp, zoom: f32) { + crate::i18n::set_current(crate::i18n::Lang::EN); + let ctx = egui::Context::default(); + ctx.set_pixels_per_point(zoom); + crate::theme::install_fonts(&ctx); + for time in [0.0, 1.0] { + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(520.0, 440.0)); + let input = egui::RawInput { time: Some(time), screen_rect: Some(screen), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| show(app, ui)); + out.textures_delta.clear(); + } +} + +fn color_at(img: &vectorcraft_three_d::fold::raster::Image, x: u32, y: u32) -> [u8; 4] { + let i = (y * img.width + x) as usize * 4; + [img.pixels[i], img.pixels[i + 1], img.pixels[i + 2], img.pixels[i + 3]] +} + +/// The color at the middle of the window's last image. +fn middle(img: &vectorcraft_three_d::fold::raster::Image) -> [u8; 4] { + color_at(img, img.width / 2, img.height / 2) +} + +#[test] +fn the_menu_item_and_the_panel_button_show_the_window_and_a_second_run_keeps_it() { + let (mut app, _) = app(); + let entries = menus::menu_entries(&app); + let item = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Packaging Tools"] && e.label == "Fold Preview").expect("listed"); + assert_eq!((item.command.as_deref(), &item.params), (Some("ui.foldPreview"), &json!({}))); + assert!(!crate::panel_docking::showing(&app.ui, ID)); + menus::invoke(&mut app, "ui.foldPreview", json!({})); + assert!(crate::panel_docking::visible(&app.ui, ID), "the window opens"); + menus::invoke(&mut app, "ui.foldPreview", json!({})); + assert!(crate::panel_docking::visible(&app.ui, ID), "a second run leaves it open"); + let text = crate::tests_labels::painted_text(&mut app, super::super::show); + assert!(text.contains("Fold Preview"), "the Fold Lines panel has the button: {text}"); +} + +#[test] +fn ui_fold_preview_sets_the_window_and_refuses_bad_values() { + let (mut app, _) = app(); + let r = app + .run( + "ui.foldPreview", + json!({"amount": 0.5, "view": "top", "zoom": 2, "perspective": 40, "inside": "#00ff00", "showFoldLines": true, "base": [120, 190]}), + ) + .unwrap(); + let want = Settings { + amount: 0.5, + rotate_x: 90.0, + rotate_y: 0.0, + zoom: 2.0, + pan: [0.0; 2], + perspective: 40.0, + inside: "#00ff00".into(), + show_fold_lines: true, + base: Some([120.0, 190.0]), + }; + assert_eq!(app.ui.fold_preview, want); + assert_eq!(r["rotateX"], 90.0, "{r}"); + assert!(r.get("frame").is_some(), "{r}"); + app.run("ui.foldPreview", json!({"rotateX": -30, "rotateY": 170, "base": null})).unwrap(); + assert_eq!((app.ui.fold_preview.rotate_x, app.ui.fold_preview.rotate_y, app.ui.fold_preview.base), (-30.0, 170.0, None)); + let kept = app.ui.fold_preview.clone(); + for (p, want) in [ + (json!({"amount": 2}), "`amount` must be a number from 0 to 1"), + (json!({"amount": "half"}), "`amount` must be a number from 0 to 1"), + (json!({"view": "sideways"}), "`view` must be one of"), + (json!({"rotateX": 200}), "`rotateX` must be a number from -180 to 180"), + (json!({"zoom": 0}), "`zoom` must be a number from 0.1 to 8"), + (json!({"perspective": 170}), "`perspective` must be a number from 0 to 160"), + (json!({"inside": "no such swatch"}), "`inside` must be #rrggbb"), + (json!({"inside": 7}), "`inside` must be #rrggbb"), + (json!({"showFoldLines": "yes"}), "`showFoldLines` must be true or false"), + (json!({"base": [1, "2"]}), "`base` must be a point"), + (json!({"base": [5, 5]}), "`base` is in no panel"), + (json!({"amount": 0.2, "zoom": 99}), "`zoom` must be a number"), + ] { + let e = app.run("ui.foldPreview", p.clone()).unwrap_err().to_string(); + assert!(e.contains(want), "{p}: {e}"); + assert_eq!(app.ui.fold_preview, kept, "{p} sets nothing"); + } + // A swatch with a plain color names the inside. + app.run("ui.foldPreview", json!({"inside": "White"})).unwrap(); + assert_eq!(app.ui.fold_preview.inside, "White"); + // So does one whose name starts with #, and a swatch's name comes before a #rrggbb that reads the same. + app.run("swatch.new", json!({"name": "#brand", "color": "#0000ff"})).unwrap(); + app.run("swatch.new", json!({"name": "#00ff00", "color": "#0000ff"})).unwrap(); + app.run("ui.foldPreview", json!({"inside": "#brand"})).unwrap(); + assert_eq!(app.ui.fold_preview.inside, "#brand"); + let doc = &app.session.active().expect("a document").doc; + assert_eq!(inside_color(doc, "#brand"), Some([0, 0, 255, 255])); + assert_eq!(inside_color(doc, "#00ff00"), Some([0, 0, 255, 255])); + assert_eq!(inside_color(doc, "#ff0000"), Some([255, 0, 0, 255])); + // White, the default, stays white beside a swatch named #ffffff. + app.run("swatch.new", json!({"name": "#ffffff", "color": "#0000ff"})).unwrap(); + let doc = &app.session.active().expect("a document").doc; + assert_eq!(inside_color(doc, &Settings::default().inside), Some([255; 4])); + assert_eq!(inside_color(doc, "#ffffff"), Some([0, 0, 255, 255])); + app.run("ui.foldPreview", json!({"inside": ""})).unwrap(); + assert_eq!(app.ui.fold_preview.inside, ""); +} + +#[test] +fn the_window_draws_the_print_on_the_folded_panels_and_the_inside_on_their_backs() { + let (mut app, _) = app(); + // Flat, from the front: the base's print, red, fills the middle. + app.run("ui.foldPreview", json!({"amount": 0, "view": "front"})).unwrap(); + let before = prints_rendered(); + frame(&mut app); + assert!(prints_rendered() > before, "the print is rendered on this thread without a worker"); + let img = last_image().expect("a frame"); + let [r, g, b, a] = middle(&img); + assert!(r > 150 && g < 40 && b < 40 && a == 255, "red print: {:?}", [r, g, b, a]); + let state = app.run("ui.foldPreview", json!({})).unwrap(); + assert_eq!((state["frame"]["width"].as_u64(), state["frame"]["height"].as_u64()), (Some(u64::from(img.width)), Some(u64::from(img.height)))); + // From the back, the base's inside shows in the inside color. + app.run("ui.foldPreview", json!({"view": "back", "inside": "#00ff00"})).unwrap(); + frame(&mut app); + let [r, g, b, _] = middle(&last_image().expect("a frame")); + assert!(r < 40 && g > 150 && b < 40, "green inside: {:?}", [r, g, b]); + // Folded and seen from the front, the walls stand edge on: the base fills the same place. + app.run("ui.foldPreview", json!({"amount": 1, "view": "front"})).unwrap(); + frame(&mut app); + let img = last_image().expect("a frame"); + let [r, ..] = middle(&img); + assert!(r > 150, "the base still shows its print: {:?}", middle(&img)); + // The same print is not rendered again while the document does not change. + let prints = prints_rendered(); + frame(&mut app); + assert_eq!(prints_rendered(), prints); +} + +#[test] +fn a_wide_perspective_still_fits_the_whole_folded_blank_in_the_view() { + let (mut app, _) = app(); + // Without perspective, the base and the two walls behind it that face the viewer show. + let mut flat = None; + for perspective in [0, 60, 160] { + app.run("ui.foldPreview", json!({"amount": 1, "view": "threeQuarter", "zoom": 1, "perspective": perspective})).unwrap(); + frame(&mut app); + let img = last_image().expect("a frame"); + let mut shown: Vec = + (0..img.height).flat_map(|y| (0..img.width).map(move |x| (x, y))).filter_map(|(x, y)| img.panel_at(x, y)).collect(); + shown.sort_unstable(); + shown.dedup(); + let flat = flat.get_or_insert_with(|| shown.clone()); + assert_eq!(flat.len(), 3); + assert_eq!(&shown, flat, "{perspective}°: the same panels show"); + let edge = (0..img.width).flat_map(|x| [(x, 0), (x, img.height - 1)]).chain((0..img.height).flat_map(|y| [(0, y), (img.width - 1, y)])); + assert!(edge.into_iter().all(|(x, y)| img.panel_at(x, y).is_none()), "{perspective}°: nothing reaches the edge of the view"); + } +} + +#[test] +fn a_window_with_more_pixels_than_the_view_may_have_is_drawn_smaller() { + let (mut app, _) = app(); + app.run("ui.foldPreview", json!({"amount": 0, "view": "front"})).unwrap(); + frame_at(&mut app, 8.0); + let img = last_image().expect("a frame"); + assert!(u64::from(img.width) * u64::from(img.height) <= u64::from(vectorcraft_three_d::fold::raster::MAX_PIXELS), "{}×{}", img.width, img.height); + assert!(img.width > 1000, "still sharper than one pixel a point: {}", img.width); + let [r, ..] = middle(&img); + assert!(r > 150, "the base's print shows: {:?}", middle(&img)); +} + +#[test] +fn the_print_leaves_out_the_fold_lines_unless_they_are_shown() { + let (mut app, red) = app(); + // Without the red square, the base's middle shows the board with no art; with a crease drawn + // across the middle and the fold lines shown, the crease's color shows there. + app.run("select.set", json!({ "ids": [red] })).unwrap(); + app.run("edit.clear", json!({})).unwrap(); + let mid = app.run("path.create", json!({ "d": "M140 190 L240 190" })).unwrap()["id"].as_u64().unwrap(); + app.run("addon.packaging.setRole", json!({ "role": "crease", "ids": [mid] })).unwrap(); + app.run("select.set", json!({ "ids": [mid] })).unwrap(); + app.run("stroke.set", json!({ "weight": 20 })).unwrap(); + app.run("select.none", json!({})).unwrap(); + app.run("ui.foldPreview", json!({"amount": 0, "view": "front", "zoom": 1})).unwrap(); + frame(&mut app); + let plain = middle(&last_image().expect("a frame")); + app.run("ui.foldPreview", json!({"showFoldLines": true})).unwrap(); + frame(&mut app); + let lined = middle(&last_image().expect("a frame")); + assert_ne!(plain, lined, "the crease shows only with Show Fold Lines on"); + assert!(plain[0] > 200 && plain[1] > 200 && plain[2] > 200, "the board is white where the print has no art: {plain:?}"); +} + +#[test] +fn the_window_says_when_there_is_nothing_to_fold() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let text = crate::tests_labels::painted_text(&mut app, show); + assert!(text.contains("Check the fold lines first."), "{text}"); + let mut none = VectorcraftApp::new(Session::new(), Default::default()); + let text = crate::tests_labels::painted_text(&mut none, show); + assert!(text.contains("Open a document to preview its folded shape."), "{text}"); +} + +#[test] +fn the_settings_are_kept_with_the_ui_state() { + let (mut app, _) = app(); + app.run("ui.foldPreview", json!({"amount": 0.25, "view": "left"})).unwrap(); + let saved: Value = serde_json::to_value(&app.ui).unwrap(); + assert_eq!(saved["fold_preview"]["amount"], 0.25, "{}", saved["fold_preview"]); + let back: crate::state::UiState = serde_json::from_value(saved).unwrap(); + assert_eq!(back.fold_preview, app.ui.fold_preview); +} + +#[test] +fn saved_settings_out_of_range_are_brought_into_range() { + let (mut app, _) = app(); + app.ui.fold_preview = Settings { + amount: 3.0, + rotate_x: 200.0, + rotate_y: 180.0, + zoom: 0.0, + pan: [f64::NAN, 4.0], + perspective: -5.0, + base: Some([f64::INFINITY, 0.0]), + ..Settings::default() + }; + frame(&mut app); + let set = &app.ui.fold_preview; + assert_eq!( + (set.amount, set.rotate_x, set.rotate_y, set.zoom, set.pan, set.perspective, set.base), + (1.0, -160.0, 180.0, 0.1, [0.0, 4.0], 0.0, None) + ); + let text = crate::tests_labels::painted_text(&mut app, show); + assert!(!text.contains("Check the fold lines first."), "the blank folds: {text}"); + assert!(last_image().is_some(), "and is drawn"); +} + +/// A window kept open over frames, as the app draws it. +struct View { + ctx: egui::Context, + time: f64, +} + +impl View { + fn new(app: &mut VectorcraftApp) -> Self { + crate::i18n::set_current(crate::i18n::Lang::EN); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut v = View { ctx, time: 0.0 }; + v.idle(app); + v + } + + fn step(&mut self, app: &mut VectorcraftApp, events: Vec, modifiers: Modifiers) { + self.time += 0.05; + let screen = egui::Rect::from_min_size(Pos2::ZERO, vec2(520.0, 440.0)); + let events = std::iter::once(Event::ModifiersChanged(modifiers)).chain(events).collect(); + let input = egui::RawInput { time: Some(self.time), screen_rect: Some(screen), events, ..Default::default() }; + let mut out = self.ctx.run_ui(input, |ui| show(app, ui)); + out.textures_delta.clear(); + } + + fn idle(&mut self, app: &mut VectorcraftApp) { + for _ in 0..3 { + self.step(app, vec![], Modifiers::NONE); + } + } + + /// Presses `button` at `at`, drags by `by` in four steps and lets go, holding `modifiers`. + fn drag(&mut self, app: &mut VectorcraftApp, at: Pos2, by: egui::Vec2, button: PointerButton, modifiers: Modifiers) { + let press = |pos, pressed| Event::PointerButton { pos, button, pressed, modifiers }; + self.step(app, vec![Event::PointerMoved(at)], modifiers); + self.step(app, vec![press(at, true)], modifiers); + for k in 1..=4 { + self.step(app, vec![Event::PointerMoved(at + by * (k as f32 / 4.0))], modifiers); + } + self.step(app, vec![press(at + by, false)], modifiers); + self.idle(app); + } + + fn click(&mut self, app: &mut VectorcraftApp, at: Pos2) { + let press = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + self.step(app, vec![Event::PointerMoved(at)], Modifiers::NONE); + self.step(app, vec![press(true)], Modifiers::NONE); + self.step(app, vec![press(false)], Modifiers::NONE); + } + + fn key(&mut self, app: &mut VectorcraftApp, key: egui::Key) { + let press = Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }; + self.step(app, vec![press], Modifiers::NONE); + self.step(app, vec![], Modifiers::NONE); + } +} + +/// The app showing the tray flat from the front, in a [`View`], and the middle of the view. +fn front_view() -> (VectorcraftApp, View, Pos2) { + let (mut app, _) = app(); + app.run("ui.foldPreview", json!({"amount": 0, "view": "front"})).unwrap(); + let view = View::new(&mut app); + let at = last_rect().expect("the view is drawn").center(); + (app, view, at) +} + +#[test] +fn a_drag_turns_the_view_and_a_shift_drag_keeps_to_one_axis() { + let (mut app, mut view, at) = front_view(); + view.drag(&mut app, at, vec2(40.0, 20.0), PointerButton::Primary, Modifiers::NONE); + let set = app.ui.fold_preview.clone(); + assert!(set.rotate_y > 5.0 && set.rotate_y <= 20.0 + 1e-9, "{set:?}"); + assert!(set.rotate_x > 2.0 && set.rotate_x <= 10.0 + 1e-9, "{set:?}"); + app.run("ui.foldPreview", json!({"view": "front"})).unwrap(); + view.drag(&mut app, at, vec2(40.0, 20.0), PointerButton::Primary, Modifiers::SHIFT); + let set = app.ui.fold_preview.clone(); + assert!(set.rotate_y > 5.0 && set.rotate_x == 0.0, "only the larger move turns the view: {set:?}"); +} + +#[test] +fn a_middle_drag_moves_the_view_and_the_wheel_zooms_it() { + let (mut app, mut view, at) = front_view(); + view.drag(&mut app, at, vec2(30.0, -10.0), PointerButton::Middle, Modifiers::NONE); + let set = app.ui.fold_preview.clone(); + assert!(set.pan[0] > 0.0 && set.pan[1] < 0.0, "{set:?}"); + assert_eq!((set.rotate_x, set.rotate_y), (0.0, 0.0), "the view does not turn"); + let wheel = Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: vec2(0.0, 60.0), + phase: egui::TouchPhase::Move, + modifiers: Modifiers::NONE, + source: egui::MouseWheelSource::Unknown, + }; + view.step(&mut app, vec![Event::PointerMoved(at), wheel], Modifiers::NONE); + for _ in 0..20 { + view.step(&mut app, vec![], Modifiers::NONE); + } + assert!(app.ui.fold_preview.zoom > 1.05, "{:?}", app.ui.fold_preview); +} + +#[test] +fn the_arrow_keys_turn_the_focused_view_and_keep_the_focus() { + let (mut app, mut view, at) = front_view(); + view.click(&mut app, at); + view.idle(&mut app); + // Up first: the toolbar is above the view, where the focus would go if the view let it. + view.key(&mut app, egui::Key::ArrowUp); + view.key(&mut app, egui::Key::ArrowRight); + view.key(&mut app, egui::Key::ArrowRight); + let set = &app.ui.fold_preview; + assert_eq!((set.rotate_x, set.rotate_y), (-5.0, 10.0), "every press turns the view by 5°"); + // A focused view seen from the back stays there until a key turns it. + app.run("ui.foldPreview", json!({"view": "back"})).unwrap(); + view.idle(&mut app); + assert_eq!(app.ui.fold_preview.rotate_y, 180.0); +} + +#[test] +fn a_double_click_on_a_panel_makes_it_the_base() { + let (mut app, mut view, at) = front_view(); + // The left wall is the base; the middle of the view shows the tray's base panel. + app.run("ui.foldPreview", json!({"base": [120, 190]})).unwrap(); + view.idle(&mut app); + view.click(&mut app, at); + view.click(&mut app, at); + let [x, y] = app.ui.fold_preview.base.expect("a base"); + assert!((140.0..240.0).contains(&x) && (140.0..240.0).contains(&y), "the base panel is picked: {x}, {y}"); +} + +#[test] +fn a_double_click_as_the_document_changes_picks_nothing_from_the_old_image() { + let (mut app, mut view, at) = front_view(); + app.run("ui.foldPreview", json!({"base": [120, 190]})).unwrap(); + view.idle(&mut app); + view.click(&mut app, at); + let press = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + view.step(&mut app, vec![press(true)], Modifiers::NONE); + // The document changes between the image on screen and the release that ends the double-click. + app.run("shape.rectangle", json!({"x": 350, "y": 350, "width": 10, "height": 10})).unwrap(); + view.step(&mut app, vec![press(false)], Modifiers::NONE); + assert_eq!(app.ui.fold_preview.base, Some([120.0, 190.0]), "the base is kept"); +} + +#[test] +fn the_view_is_folded_and_drawn_again_only_when_something_changes() { + let (mut app, mut view, _) = front_view(); + let (folds, renders) = work_done(); + view.idle(&mut app); + assert_eq!(work_done(), (folds, renders), "nothing changed: no fold and no render"); + app.run("ui.foldPreview", json!({"rotateY": 10})).unwrap(); + view.idle(&mut app); + assert_eq!(work_done(), (folds, renders + 1), "a turn renders once and does not fold again"); + app.run("ui.foldPreview", json!({"amount": 0.5})).unwrap(); + view.idle(&mut app); + assert_eq!(work_done(), (folds + 1, renders + 2), "a new amount folds and renders once"); +} + +#[test] +fn a_short_wide_window_keeps_its_proportions() { + let (mut app, _) = app(); + app.run("ui.foldPreview", json!({"amount": 0, "view": "front"})).unwrap(); + crate::i18n::set_current(crate::i18n::Lang::EN); + let ctx = egui::Context::default(); + ctx.set_pixels_per_point(2.0); + crate::theme::install_fonts(&ctx); + for time in [0.0, 1.0] { + let screen = egui::Rect::from_min_size(Pos2::ZERO, vec2(2200.0, 260.0)); + let input = egui::RawInput { time: Some(time), screen_rect: Some(screen), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| show(&mut app, ui)); + out.textures_delta.clear(); + } + let (img, rect) = (last_image().expect("a frame"), last_rect().expect("a rect")); + let (image, window) = (f64::from(img.width) / f64::from(img.height), f64::from(rect.width() / rect.height())); + assert!(img.width <= vectorcraft_three_d::fold::raster::MAX_SIDE, "{}", img.width); + assert!((image - window).abs() / window < 0.02, "image {image}, window {window}"); +} + +#[test] +fn a_print_of_another_blank_or_setting_is_not_drawn_while_the_new_one_renders() { + let key = PrintKey { uid: 1, revision: 5, fold_lines: false, region: [0, 0, 10, 10], width: 1, height: 1 }; + let region = vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0); + let print = vectorcraft_three_d::fold::raster::Print::new(region, 1, 1, vec![255; 4]).expect("a print"); + let cache = Cache { print: Some((key, Arc::new(print))), ..Default::default() }; + assert!(cache.print_for(&PrintKey { revision: 6, ..key }).is_some(), "a newer revision of the same blank keeps the last print"); + for other in [PrintKey { uid: 2, ..key }, PrintKey { fold_lines: true, ..key }, PrintKey { region: [0, 0, 20, 10], ..key }] { + assert!(cache.print_for(&other).is_none(), "{other:?}"); + } +} + +#[test] +fn the_status_line_reports_open_joints_crossing_panels_and_other_blanks() { + use vectorcraft_three_d::fold::{Blank, Folded, FoldedHinge}; + let hinge = |tree, closes, gap| FoldedHinge { a: 0, b: 1, angle: 90.0, tree, closes, gap }; + let f = Folded { + base: 0, + panels: vec![], + order: vec![], + hinges: vec![hinge(true, true, 0.0), hinge(false, false, 12.34), hinge(false, false, 3.0), hinge(false, true, 0.05)], + collisions: vec![(0, 1)], + }; + let lines = status(3, Some((&Blank::default(), &f)), true); + assert_eq!( + lines, + [ + "Panels: 0, hinges: 0", + "Check the fold lines first.", + "Other blanks not shown: 2", + "A joint does not close by 12.3 pt.", + "Two panels pass through each other." + ] + ); + let f = Folded { hinges: vec![hinge(false, true, 0.05)], collisions: vec![], ..f }; + assert_eq!(status(1, Some((&Blank::default(), &f)), false), ["Panels: 0, hinges: 0"]); +} + +#[test] +fn the_window_says_when_folded_panels_pass_through_each_other() { + // A strip: a 120 pt lid, a 30 pt wall, the 100 pt base and a 60 pt wall, all 50 pt deep. Folded + // about the base, the lid crosses the taller wall. + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let path = |app: &mut VectorcraftApp, d: &str| app.run("path.create", json!({ "d": d })).unwrap()["id"].as_u64().unwrap(); + let outline = path(&mut app, "M0 0 L310 0 L310 50 L0 50 Z"); + let creases = [path(&mut app, "M120 0 L120 50"), path(&mut app, "M150 0 L150 50"), path(&mut app, "M250 0 L250 50")]; + app.run("addon.packaging.setRole", json!({ "role": "cut", "ids": [outline] })).unwrap(); + app.run("addon.packaging.setRole", json!({ "role": "crease", "ids": creases })).unwrap(); + app.run("select.none", json!({})).unwrap(); + app.run("ui.foldPreview", json!({"base": [200, 25], "amount": 1})).unwrap(); + let text = crate::tests_labels::painted_text(&mut app, show); + assert!(text.contains("Two panels pass through each other."), "{text}"); + assert!(!text.contains("A joint does not close"), "{text}"); +} diff --git a/crates/ui-egui/src/addons/pathtools.rs b/crates/ui-egui/src/addons/pathtools.rs index 011af4b171..8a1666b260 100644 --- a/crates/ui-egui/src/addons/pathtools.rs +++ b/crates/ui-egui/src/addons/pathtools.rs @@ -1,11 +1,12 @@ //! Path Precision Tools in the interface: its submenu (Object › Plug-ins › Path Precision Tools), //! which selects its tools, opens its panels and runs Split / Add Points at Crossings, Set Corners… ([`set_corners`]), Divide into -//! Dashes ([`dashes`]), Expand Dashes into Paths, Convert to Parametric Shape and Tangent Circle… ([`tangent_circle`]); the Anchor Inspector panel (the selected +//! Dashes ([`dashes`]), Expand Dashes into Paths, Smooth Bridge ([`bridge`]), Convert to Parametric Shape and Tangent Circle… ([`tangent_circle`]); the Anchor Inspector panel (the selected //! anchor's position and handles as numbers, the add-on's anchor edits, the Corner Tool's values, //! [`corner`], and the Shared Edge Merge Tool's, [`shared_edge`]); the Parametric Shape panel //! ([`shape`]); and its tools' options dialog (a double-click on the tool). Everything acts through `addon.pathtools.*` and //! `tool.setOption`. +pub mod bridge; pub mod corner; pub mod dashes; pub mod set_corners; @@ -74,6 +75,7 @@ pub fn menu() -> Vec { Item::Cmd("Split at Crossings", "addon.pathtools.crossings", json!({ "cut": true })), Item::Cmd("Divide into Dashes…", dashes::COMMAND, Value::Null), Item::Cmd("Expand Dashes into Paths", "addon.pathtools.expandDashes", json!({})), + Item::Cmd("Smooth Bridge…", bridge::COMMAND, Value::Null), Item::Cmd("Convert to Parametric Shape", "addon.pathtools.shape.convert", json!({})), Item::Cmd("Tangent Circle…", tangent_circle::COMMAND, Value::Null), Item::Cmd("Common Tangents…", COMMON_TANGENTS, json!({ "tangents": "all", "centerline": false })), @@ -246,12 +248,15 @@ fn body(_app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { false } -/// OK: set the tool's options. +/// OK: set the tool's options. When the tool refuses one of them, nothing is set and the dialog +/// stays open. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let tool = d.str("__tool"); let values: Map = d.fields.iter().filter(|(k, _)| !k.starts_with("__")).map(|(k, v)| (k.clone(), v.clone())).collect(); let r = app.run("tool.setOption", json!({ "tool": tool, "values": values })); - app.ui.dialog = None; + if r.is_ok() { + app.ui.dialog = None; + } r } diff --git a/crates/ui-egui/src/addons/pathtools/bridge.rs b/crates/ui-egui/src/addons/pathtools/bridge.rs new file mode 100644 index 0000000000..4b9926d616 --- /dev/null +++ b/crates/ui-egui/src/addons/pathtools/bridge.rs @@ -0,0 +1,92 @@ +//! Smooth Bridge in the interface: its dialog (the arcs' radius as a percentage of the smaller +//! circle's radius, Keep Originals), which previews on the canvas and runs `addon.pathtools.bridge` +//! on OK. + +use egui::Ui; +use serde_json::{Value, json}; + +use crate::VectorcraftApp; +use crate::dialogs::{DialogSpec, form}; +use crate::state::Dialog; +use crate::widgets; + +/// The command, and its dialog's kind. +pub const COMMAND: &str = "addon.pathtools.bridge"; +pub const KIND: &str = "smoothBridge"; +/// The radius the command takes (%), and its default. +const RADII: std::ops::RangeInclusive = 1.0..=1000.0; +const RADIUS: f64 = 100.0; +const LABEL_W: f32 = 60.0; +const FIELD_W: f32 = 90.0; + +/// The dialog's fields to start with: the command's defaults. +pub(crate) fn fields() -> Value { + json!({ "radius": RADIUS, "keepOriginals": false }) +} + +pub(crate) const SPEC: DialogSpec = + DialogSpec { heading: |_| tl!("Smooth Bridge").to_string(), body, confirm, preview: true, min_width: 280.0, ..DialogSpec::FORM }; + +/// The command's parameters from the dialog's fields. +fn params(d: &Dialog) -> Value { + json!({ "radius": d.f64("radius", RADIUS), "keepOriginals": d.bool("keepOriginals") }) +} + +fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { + widgets::label_row(ui, tl!("Radius:"), LABEL_W, |ui| { + if let Some(v) = widgets::range_field(ui, ("dlg-num", "radius"), d.f64("radius", RADIUS), RADII, "%", 0, FIELD_W) { + d.fields.insert("radius".into(), json!(v)); + } + }); + form::check(ui, d, "keepOriginals", tl!("Keep Originals")); + form::preview(app, ui, d, "Smooth Bridge", COMMAND, params(d)); + false +} + +/// OK: run the command (keep its preview) and close. +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + form::commit_preview(app, COMMAND, params(d)) +} + +#[cfg(test)] +mod tests { + use serde_json::json; + use vectorcraft_engine::Session; + + use crate::tests_labels::painted_text; + use crate::{VectorcraftApp, menus}; + + fn circle(app: &mut VectorcraftApp, x: f64, r: f64) -> u64 { + app.run("shape.ellipse", json!({"x": x - r, "y": 100.0 - r, "width": 2.0 * r, "height": 2.0 * r})).unwrap()["id"].as_u64().unwrap() + } + + #[test] + fn smooth_bridge_opens_its_dialog_previews_and_runs_on_ok() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let (a, b) = (circle(&mut app, 100.0, 20.0), circle(&mut app, 160.0, 20.0)); + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + let entries = menus::menu_entries(&app); + let item = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Path Precision Tools"] && e.label == "Smooth Bridge…").unwrap(); + let (cmd, p) = menus::click_target(&item.label, item.command.as_deref().unwrap(), &item.params); + menus::invoke(&mut app, &cmd, p); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(super::KIND)); + let shown = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + for s in ["Smooth Bridge", "Radius:", "Keep Originals", "Preview"] { + assert!(shown.contains(s), "{s} in {shown}"); + } + let count = |app: &VectorcraftApp| app.session.doc().unwrap().doc.layers[0].children().unwrap().len(); + app.ui.dialog.as_mut().unwrap().fields.insert("preview".into(), json!(true)); + painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + assert_eq!(count(&app), 1, "previewed: one outline in place of the circles"); + crate::dialogs::cancel(&mut app); + assert_eq!(count(&app), 2, "rolled back"); + menus::invoke(&mut app, &cmd, serde_json::Value::Null); + let n = app.session.doc().unwrap().history.undo.len(); + app.ui.dialog.as_mut().unwrap().fields.insert("keepOriginals".into(), json!(true)); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.doc().unwrap().history.undo.len(), n + 1); + assert_eq!(count(&app), 3, "the circles and the outline above them"); + } +} diff --git a/crates/ui-egui/src/addons/units.rs b/crates/ui-egui/src/addons/units.rs new file mode 100644 index 0000000000..8822b70167 --- /dev/null +++ b/crates/ui-egui/src/addons/units.rs @@ -0,0 +1,199 @@ +//! Unit Converter in the interface: its submenu (Object › Plug-ins › Unit Converter), which opens +//! the panel, and the panel. The panel shows one length in every unit of +//! [`Unit::EAST_ASIAN`], one number field each. A value typed in any field (units and arithmetic, +//! as every number field reads them) updates the others as it is typed; text that does not read +//! leaves them as they were. From Selection reads the selection's width and height +//! (`addon.units.selectionSize`), and Width or Height picks which of the two the fields show; the +//! size read is dropped when the document, its selection or the bounds measure changes. Apply gives the selection that +//! width or height through `object.setBounds` as the Transform panel's W or H field does (its +//! reference point, Constrain Width and Height Proportions and Transform Object Only, Pattern +//! Only or Both), as one undo step. Each field's copy button puts its value on the clipboard, with +//! its unit when Copy with Units is on. + +use egui::Ui; +use serde_json::json; +use vectorcraft_doc::{Unit, finite_in_every_unit}; + +use crate::VectorcraftApp; +use crate::menus::Item; +use crate::panels::transform; +use crate::panels::{pstate, set_pstate}; +use crate::widgets; + +/// The panel's id (`window.panel {panel: "unitConverter"}`). +pub const ID: &str = "unitConverter"; +/// The command that measures the selection. +pub const SELECTION_SIZE: &str = "addon.units.selectionSize"; + +/// Where the panel keeps its length and choices (panel state). +const STATE: &str = "unit-converter"; +/// A row (label, field, copy button and two gaps) is 214 pt wide, inside the 240 pt body of the +/// default 260 pt floating panel with room for its scroll bar. +const LABEL_W: f32 = 90.0; +const FIELD_W: f32 = 90.0; + +/// Object › Plug-ins › Unit Converter. +pub fn menu() -> Vec { + vec![Item::Cmd("Unit Converter Panel", "window.panel", json!({ "panel": ID }))] +} + +/// The selection's side the fields show and Apply sets. +#[derive(Clone, Copy, Default, Debug, PartialEq)] +pub(crate) enum Side { + #[default] + Width, + Height, +} + +impl Side { + /// `object.setBounds`'s param for this side. + fn key(self) -> &'static str { + match self { + Side::Width => "width", + Side::Height => "height", + } + } +} + +/// The panel's length and choices. +#[derive(Clone, Default, Debug, PartialEq)] +pub(crate) struct Converter { + /// The length (points), none until one is typed or read from the selection. + pub points: Option, + /// The selection's width and height (points) From Selection last read. + pub size: Option<(f64, f64)>, + /// The active document's uid and revision, and the bounds measure (Use Preview Bounds, + /// glyph bounds), when [`Converter::size`] was read. + pub read_at: Option, + /// Which of them the fields show, and the side Apply sets. + pub side: Side, + /// Copy puts the unit after the number. + pub with_units: bool, +} + +impl Converter { + /// Show `side`: the fields take that side of the size From Selection read, if any. + pub fn pick(&mut self, side: Side) { + self.side = side; + if let Some((w, h)) = self.size { + self.points = Some(if side == Side::Width { w } else { h }); + } + } + + /// A length typed in a field: after From Selection it replaces the side shown, so picking the + /// other side and back keeps it. + pub fn set(&mut self, pt: f64) { + self.points = Some(pt); + if let Some((w, h)) = &mut self.size { + *(if self.side == Side::Width { w } else { h }) = pt; + } + } + + /// Drop the size From Selection read when the active document is no longer the one it was + /// read from or is measured another way (`now`: its uid and revision, which a change to the + /// selection also moves, and the bounds measure). The length the fields show stays. + pub fn follow(&mut self, now: Option) { + if self.size.is_some() && self.read_at != now { + self.size = None; + self.read_at = None; + } + } + + /// What the copy button of the field in `unit` puts on the clipboard. + pub fn copied(&self, unit: Unit) -> Option { + self.points.map(|pt| if self.with_units { unit.format(pt) } else { unit.number(pt) }) + } +} + +/// A document's uid and revision, and the bounds measure. +pub(crate) type ReadAt = (u64, u64, vectorcraft_effects::preview::Measure); + +/// The active document's uid and revision, and the bounds measure. +pub(crate) fn document_now(app: &VectorcraftApp) -> Option { + app.session.active().map(|st| (st.uid, st.revision, app.session.bounds_measure())) +} + +/// From Selection: read the selection's width and height into `st`, and show the side picked. +pub(crate) fn from_selection(app: &mut VectorcraftApp, st: &mut Converter) -> Result<(), String> { + let r = app.run(SELECTION_SIZE, json!({}))?; + if let (Some(w), Some(h)) = (r["width"]["points"].as_f64(), r["height"]["points"].as_f64()) { + st.size = Some((w, h)); + st.read_at = document_now(app); + st.pick(st.side); + } + Ok(()) +} + +/// Apply: give the selection the length as its width or height, as the Transform panel's W or H +/// field does: from its reference point (a symbol instance's registration point with Use +/// Registration Point for Symbol on), with the other side following under Constrain Width and +/// Height Proportions, and with the panel menu's Transform Object Only, Pattern Only or Both. +/// Without a length it does nothing. +pub(crate) fn apply(app: &mut VectorcraftApp, ui: &Ui, st: &Converter) -> Result<(), String> { + let Some(pt) = st.points else { return Ok(()) }; + let reference = app.selection_box().map_or_else(|| transform::reference_index(ui), |b| transform::panel_reference(app, ui, &b).index); + let params = json!({ st.side.key(): pt, "reference": reference, "proportional": transform::proportional(app, ui) }); + let params = transform::with_pattern_switches(app, params); + app.run("object.setBounds", params)?; + Ok(()) +} + +pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { + let mut st: Converter = pstate(ui.ctx(), STATE); + st.follow(document_now(app)); + // A number typed without a unit is in its row's unit, so 2 in the Picas row is 2 picas, also + // with Preferences › Units › Numbers Without Units Are Points on; other panels' fields keep it. + let bare_points = widgets::typed_unit(ui.ctx(), Unit::Picas) == Unit::Points; + widgets::set_bare_numbers_are_points(ui.ctx(), false); + for unit in Unit::EAST_ASIAN { + widgets::label_row(ui, unit.label(), LABEL_W, |ui| { + // A length too large to show in one of the units (near the largest number, in Q and + // Ha) leaves the others as they were, as text that does not read does. + if let Some(pt) = widgets::num_field_live(ui, ("unit-converter", unit.key()), st.points, unit, FIELD_W) + && finite_in_every_unit(pt) + { + st.set(pt); + } + // The button's name and tip carry the row's unit ("Copy Millimeters"). + let tip = format!("{} {}", tl!("Copy"), tl!(unit.label())); + let copy = widgets::icon_button_enabled(ui, "copy", &tip, false, st.points.is_some(), 22.0); + if copy.clicked() + && let Some(text) = st.copied(unit) + { + ui.ctx().copy_text(text); + } + }); + } + widgets::set_bare_numbers_are_points(ui.ctx(), bare_points); + if widgets::check(ui, "Copy with Units", st.with_units, true) { + st.with_units = !st.with_units; + } + ui.add_space(6.0); + widgets::subheader(ui, tl!("Selection")); + let selected = app.session.active().is_some_and(|d| !d.selection.is_empty()); + ui.horizontal(|ui| { + for (side, label) in [(Side::Width, "Width"), (Side::Height, "Height")] { + if widgets::radio(ui, label, st.side == side, true) { + st.pick(side); + } + } + }); + ui.horizontal(|ui| { + let read = ui.add_enabled_ui(selected, |ui| widgets::flat_button(ui, tl!("From Selection"), 110.0)).inner; + if read.clicked() + && let Err(e) = from_selection(app, &mut st) + { + app.status(e); + } + let set = ui.add_enabled_ui(selected && st.points.is_some(), |ui| widgets::flat_button(ui, tl!("Apply"), 70.0)).inner; + if set.clicked() + && let Err(e) = apply(app, ui, &st) + { + app.status(e); + } + }); + set_pstate(ui.ctx(), STATE, st); +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/addons/units/tests.rs b/crates/ui-egui/src/addons/units/tests.rs new file mode 100644 index 0000000000..3959157032 --- /dev/null +++ b/crates/ui-egui/src/addons/units/tests.rs @@ -0,0 +1,329 @@ +//! Unit Converter's submenu and panel: one field per unit, typing in one updates the others and +//! text that does not read leaves them alone, From Selection reads the selection's size, Apply +//! sets the side picked as one undo step and adds none when nothing changes, and Copy writes the +//! value with or without its unit. + +use egui::{Event, Key, Modifiers, Pos2, Rect, vec2}; +use serde_json::json; +use vectorcraft_doc::Unit; +use vectorcraft_engine::Session; + +use super::{Converter, ID, STATE, Side, apply, document_now, from_selection, show}; +use crate::panels::{pstate, set_pstate}; +use crate::tests_labels::{painted_text, shapes_text}; +use crate::{VectorcraftApp, menus}; + +/// An app with a selected 72 × 36 pt rectangle. +fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 72, "height": 36})).unwrap(); + app +} + +fn near(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-6 +} + +fn undo_steps(app: &VectorcraftApp) -> usize { + app.session.active().unwrap().history.undo.len() +} + +/// The selection's width and height. +fn size(app: &mut VectorcraftApp) -> (f64, f64) { + let r = app.run("addon.units.selectionSize", json!({})).unwrap(); + (r["width"]["points"].as_f64().unwrap(), r["height"]["points"].as_f64().unwrap()) +} + +#[test] +fn the_submenu_opens_the_panel() { + let mut app = app(); + let entries = menus::menu_entries(&app); + let item = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Unit Converter"] && e.label == "Unit Converter Panel").expect("listed"); + menus::invoke(&mut app, "window.panel", item.params.clone()); + assert!(crate::panel_docking::showing(&app.ui, ID), "the panel opens"); +} + +#[test] +fn the_panel_has_a_field_for_every_unit_and_its_buttons() { + let mut app = app(); + let text = painted_text(&mut app, |app, ui| { + set_pstate(ui.ctx(), STATE, Converter { points: Some(720.0 / 25.4), ..Converter::default() }); + show(app, ui); + }); + for u in Unit::EAST_ASIAN { + assert!(text.lines().any(|l| l == u.label()), "{} in {text}", u.label()); + } + for s in ["10 mm", "1 cm", "0.3937 in", "28.346 pt", "40 Q", "40 H"] { + assert!(text.lines().any(|l| l == s), "{s} in {text}"); + } + for s in ["Copy with Units", "Selection", "Width", "Height", "From Selection", "Apply"] { + assert!(text.lines().any(|l| l == s), "{s} in {text}"); + } +} + +#[test] +fn typing_in_a_field_updates_the_others_and_text_that_does_not_read_leaves_them() { + let mut app = app(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut time = 0.0; + let mut frame = |app: &mut VectorcraftApp, events: Vec| { + time += 0.05; + let screen_rect = Some(Rect::from_min_size(Pos2::ZERO, vec2(400.0, 800.0))); + let mut out = ctx.run_ui(egui::RawInput { events, time: Some(time), screen_rect, focused: true, ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + (pstate::(&ctx, STATE), shapes_text(&out)) + }; + let tab = Event::Key { key: Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }; + frame(&mut app, vec![]); + frame(&mut app, vec![]); + // Tab reaches the first field, Points, which selects its text so typing replaces it. + frame(&mut app, vec![tab]); + frame(&mut app, vec![]); + let (st, _) = frame(&mut app, vec![Event::Text("1in/2".into())]); + assert!(st.points.is_some_and(|pt| near(pt, 36.0)), "{st:?}"); + let (st, text) = frame(&mut app, vec![]); + assert!(near(st.points.unwrap(), 36.0)); + for s in ["0.5 in", "3 p", "12.7 mm", "1.27 cm"] { + assert!(text.lines().any(|l| l == s), "{s} in {text}"); + } + // Text that does not read keeps the length the other fields show. + let (st, text) = frame(&mut app, vec![Event::Text("x".into())]); + assert!(near(st.points.unwrap(), 36.0), "{st:?}"); + assert!(text.lines().any(|l| l == "12.7 mm"), "{text}"); + // So does a length too large to show in Q and Ha. + let select_all = Event::Key { key: Key::A, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::COMMAND }; + frame(&mut app, vec![select_all]); + // 1.7e308 pt: finite in points. + let (st, _) = frame(&mut app, vec![Event::Text(format!("17{}", "0".repeat(307)))]); + assert!(near(st.points.unwrap(), 36.0), "{st:?}"); +} + +#[test] +fn a_number_typed_without_a_unit_in_the_picas_row_is_in_picas() { + let mut app = app(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + // Numbers Without Units Are Points is on (its default), and stays on for other fields. + crate::widgets::set_bare_numbers_are_points(&ctx, true); + let mut time = 0.0; + let mut frame = |app: &mut VectorcraftApp, events: Vec| { + time += 0.05; + let screen_rect = Some(Rect::from_min_size(Pos2::ZERO, vec2(400.0, 800.0))); + let mut out = ctx.run_ui(egui::RawInput { events, time: Some(time), screen_rect, focused: true, ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + pstate::(&ctx, STATE) + }; + let tab = Event::Key { key: Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }; + frame(&mut app, vec![]); + frame(&mut app, vec![]); + // Tab reaches the Points field, then the Picas field (the copy buttons are off with no length). + for _ in 0..2 { + frame(&mut app, vec![tab.clone()]); + frame(&mut app, vec![]); + } + let st = frame(&mut app, vec![Event::Text("2".into())]); + assert!(st.points.is_some_and(|pt| near(pt, 24.0)), "{st:?}"); + assert_eq!(crate::widgets::typed_unit(&ctx, Unit::Picas), Unit::Points, "other fields still read points"); +} + +#[test] +fn picking_a_side_shows_that_side_of_the_size_read() { + let mut st = Converter { size: Some((72.0, 36.0)), ..Converter::default() }; + st.pick(Side::Height); + assert_eq!((st.side, st.points), (Side::Height, Some(36.0))); + st.pick(Side::Width); + assert_eq!(st.points, Some(72.0)); + // A length typed after From Selection replaces the side shown, and picking the other side and + // back keeps it. + st.set(100.0); + st.pick(Side::Height); + assert_eq!(st.points, Some(36.0)); + st.pick(Side::Width); + assert_eq!((st.points, st.size), (Some(100.0), Some((100.0, 36.0)))); + // Before From Selection a side keeps the length typed. + let mut st = Converter::default(); + st.set(5.0); + st.pick(Side::Height); + assert_eq!((st.points, st.size), (Some(5.0), None)); +} + +#[test] +fn copy_writes_the_value_with_or_without_its_unit() { + let mut st = Converter { points: Some(72.0), ..Converter::default() }; + assert_eq!(st.copied(Unit::Inches).as_deref(), Some("1")); + st.with_units = true; + assert_eq!(st.copied(Unit::Inches).as_deref(), Some("1 in")); + assert_eq!(st.copied(Unit::Millimeters), Some(Unit::Millimeters.format(72.0))); + assert_eq!(Converter::default().copied(Unit::Points), None, "nothing to copy before a length"); +} + +/// Apply `st` in a frame whose shared reference point (the Transform panel's) is `reference`. +fn apply_at(app: &mut VectorcraftApp, st: &Converter, reference: usize) { + try_apply_at(app, st, reference).unwrap(); +} + +/// [`apply_at`], with its result. +fn try_apply_at(app: &mut VectorcraftApp, st: &Converter, reference: usize) -> Result<(), String> { + let ctx = egui::Context::default(); + ctx.data_mut(|d| d.insert_temp(egui::Id::unique("refpt"), reference)); + let mut result = Ok(()); + ctx.run_ui(Default::default(), |ui| result = apply(app, ui, st)).textures_delta.clear(); + result +} + +/// The selection's bounding box. +fn bounds(app: &mut VectorcraftApp) -> vectorcraft_geom::Rect { + app.selection_box().unwrap().rect +} + +#[test] +fn from_selection_reads_the_size_and_apply_sets_the_side_picked() { + let mut app = app(); + let mut st = Converter::default(); + from_selection(&mut app, &mut st).unwrap(); + assert_eq!((st.size, st.points), (Some((72.0, 36.0)), Some(72.0))); + st.pick(Side::Height); + assert_eq!(st.points, Some(36.0)); + // Apply: 1 in high, from the centre, as one undo step. + let steps = undo_steps(&app); + st.points = Some(72.0); + apply_at(&mut app, &st, 4); + let (w, h) = size(&mut app); + assert!(near(w, 72.0) && near(h, 72.0), "{w} × {h}"); + assert_eq!(undo_steps(&app), steps + 1); + // The same length again changes nothing and adds no step. + apply_at(&mut app, &st, 4); + assert_eq!(undo_steps(&app), steps + 1); + // Without a length Apply does nothing. + apply_at(&mut app, &Converter::default(), 4); + assert_eq!(undo_steps(&app), steps + 1); + // Width, kept at the left edge (reference 3). + let x0 = bounds(&mut app).x0; + let st = Converter { points: Some(144.0), side: Side::Width, ..Converter::default() }; + apply_at(&mut app, &st, 3); + let b = bounds(&mut app); + assert!(near(b.width(), 144.0) && near(b.x0, x0), "{b:?}"); + assert_eq!(undo_steps(&app), steps + 2); +} + +/// Apply follows the Transform panel's W and H fields: Constrain Width and Height Proportions +/// scales the other side too, and Transform Pattern Only leaves the object's size alone. +#[test] +fn apply_follows_the_transform_panels_proportions_and_pattern_choice() { + let mut app = app(); + app.run("prefs.set", json!({"key": "constrainProportions", "value": true})).unwrap(); + apply_at(&mut app, &Converter { points: Some(144.0), side: Side::Width, ..Converter::default() }, 4); + let (w, h) = size(&mut app); + assert!(near(w, 144.0) && near(h, 72.0), "{w} × {h}"); + app.run("prefs.set", json!({"key": "constrainProportions", "value": false})).unwrap(); + app.run("prefs.set", json!({"key": "transformPanelPatterns", "value": "pattern"})).unwrap(); + // The object has no pattern to transform: whether the command reports that or not, the + // object keeps its size. + let _ = try_apply_at(&mut app, &Converter { points: Some(10.0), side: Side::Width, ..Converter::default() }, 4); + let (w, h) = size(&mut app); + assert!(near(w, 144.0) && near(h, 72.0), "the object keeps its size: {w} × {h}"); + app.run("prefs.set", json!({"key": "transformPanelPatterns", "value": "both"})).unwrap(); + apply_at(&mut app, &Converter { points: Some(10.0), side: Side::Width, ..Converter::default() }, 4); + assert!(near(size(&mut app).0, 10.0)); +} + +/// With Use Registration Point for Symbol on and one symbol instance selected, Apply keeps the +/// symbol's registration point (here its top-left corner) in place, as the Transform panel does, +/// instead of the shared reference point (the centre). +#[test] +fn apply_keeps_a_symbol_instances_registration_point() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("shape.rectangle", json!({"x": 100, "y": 50, "width": 80, "height": 40})).unwrap(); + let id = app.run("symbol.new", json!({"name": "Corner", "registration": 0})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + app.run("prefs.set", json!({"key": "useRegistrationPointForSymbol", "value": true})).unwrap(); + apply_at(&mut app, &Converter { points: Some(160.0), side: Side::Width, ..Converter::default() }, 4); + assert_eq!(bounds(&mut app), vectorcraft_geom::Rect::new(100.0, 50.0, 260.0, 90.0)); +} + +/// The size From Selection read belongs to the selection it was read from: after the selection +/// changes, picking a side keeps the length shown instead of showing the old object's side, and +/// Apply sets that length. +#[test] +fn a_size_read_from_another_selection_is_dropped() { + let mut app = app(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let frame = |app: &mut VectorcraftApp| { + ctx.run_ui(Default::default(), |ui| show(app, ui)).textures_delta.clear(); + pstate::(&ctx, STATE) + }; + let mut st = Converter::default(); + from_selection(&mut app, &mut st).unwrap(); + set_pstate(&ctx, STATE, st); + // Drawing the panel again with nothing changed keeps it. + assert_eq!(frame(&mut app).size, Some((72.0, 36.0))); + // Another object selected. + app.run("shape.rectangle", json!({"x": 200, "y": 100, "width": 20, "height": 50})).unwrap(); + let mut st = frame(&mut app); + assert_eq!((st.size, st.points), (None, Some(72.0)), "{st:?}"); + st.pick(Side::Height); + assert_eq!(st.points, Some(72.0), "not the first object's height"); + apply_at(&mut app, &st, 4); + let (w, h) = size(&mut app); + assert!(near(w, 20.0) && near(h, 72.0), "{w} × {h}"); + // So does a change to the document. + let mut st = Converter::default(); + from_selection(&mut app, &mut st).unwrap(); + app.run("object.rotate", json!({"angle": 30})).unwrap(); + st.follow(document_now(&app)); + assert_eq!(st.size, None); + // And a change to how the selection is measured (Use Preview Bounds), which leaves the + // document as it is. + let mut st = Converter::default(); + from_selection(&mut app, &mut st).unwrap(); + st.follow(document_now(&app)); + assert!(st.size.is_some()); + app.run("prefs.set", json!({"key": "usePreviewBounds", "value": true})).unwrap(); + st.follow(document_now(&app)); + assert_eq!(st.size, None); +} + +/// Each row's copy button reads as copying that row's unit, so a screen reader tells the twelve +/// apart, and the fields are named by their rows. +#[test] +fn each_copy_button_and_field_is_named_with_its_unit() { + let mut app = app(); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + set_pstate(&ctx, STATE, Converter { points: Some(72.0), ..Converter::default() }); + ctx.run_ui(Default::default(), |ui| show(&mut app, ui)).textures_delta.clear(); + let mut out = ctx.run_ui(Default::default(), |ui| show(&mut app, ui)); + out.textures_delta.clear(); + let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; + // A label node carries its text as its value. + let label_of = |id: egui::accesskit::NodeId| nodes.iter().find(|(n, _)| *n == id).and_then(|(_, n)| n.label().or(n.value())).map(str::to_string); + let buttons: Vec = + nodes.iter().filter(|(_, n)| n.role() == egui::accesskit::Role::Button).filter_map(|(_, n)| n.label().map(str::to_string)).collect(); + for u in Unit::EAST_ASIAN { + let name = format!("Copy {}", u.label()); + assert_eq!(buttons.iter().filter(|b| **b == name).count(), 1, "{name} in {buttons:?}"); + // The row fits the 240 pt body of the default 260 pt floating panel, with 10 pt left for + // its scroll bar. + let button = nodes.iter().find(|(_, n)| n.label() == Some(name.as_str())).and_then(|(_, n)| n.bounds()).unwrap(); + assert!(button.x1 <= 230.0, "{name} ends at {}", button.x1); + // The field of the row is labeled by the row's label. + let field = nodes + .iter() + .find(|(_, n)| n.role() != egui::accesskit::Role::Button && n.labelled_by().iter().any(|l| label_of(*l).as_deref() == Some(u.label()))); + assert!(field.is_some(), "a field labeled {}", u.label()); + } +} + +#[test] +fn from_selection_with_nothing_selected_reports_it_and_keeps_the_length() { + let mut app = app(); + app.run("select.none", json!({})).unwrap(); + let mut st = Converter { points: Some(10.0), ..Converter::default() }; + assert!(from_selection(&mut app, &mut st).is_err()); + assert_eq!((st.points, st.size), (Some(10.0), None)); +} diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index e3d2a13d64..a05dcedb38 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -82,6 +82,7 @@ impl VectorcraftApp { slices: None, print_tiling: None, live_paint_gaps: None, + find_font: None, hidden_chars: Default::default(), spelling: Default::default(), selection_marks: Default::default(), @@ -89,7 +90,9 @@ impl VectorcraftApp { selection_box: None, selection_bounds: None, content_bounds: None, + three_d_exportable: None, pixel_aligned: None, + symbol_instances: None, plugin_keys: Default::default(), placed_keys: Default::default(), cursors: Default::default(), @@ -182,6 +185,8 @@ impl VectorcraftApp { automation_roots: None, synthetic_frame: false, pending_plugin_install: None, + script_picked: Vec::new(), + script_picked_left_out: false, pen_end: Default::default(), host_iteration: 0, #[cfg(test)] @@ -354,8 +359,13 @@ impl VectorcraftApp { // A panel's, a dialog's or the text input's commit journaled in the frame before. crate::panels::actions::after_journaled_edit(self); crate::scripts_menu::poll(self, ctx); - if self.session.script_running() && !self.session.script_waiting() && self.session.script_dialog().is_none() { - // A script in `$.sleep` goes on when its time is up; until then the app can idle. + if self.session.script_running() + && !self.session.script_waiting() + && self.session.script_dialog().is_none() + && self.session.script_picker().is_none() + { + // A script in `$.sleep` goes on when its time is up; until then the app can idle. A + // script at a file dialog goes on when the dialog answers, and `picks::poll` looks for that. match self.session.script_sleep_left() { Some(left) => ctx.request_repaint_after(left), None => ctx.request_repaint(), @@ -576,6 +586,7 @@ impl VectorcraftApp { self.ime_caret_rect = None; scrub::begin_frame(self, &ctx); font_menu::end_stale_preview(self, &ctx); + font_menu::apply_preview_size(self, &ctx); tools_float::track(self, &ctx); // A selection move released over a panel ends before any panel sees the release (#2826). canvas::release_over_panel(self, &ctx); @@ -602,10 +613,6 @@ impl VectorcraftApp { if self.ui.toolbar && self.ui.screen_mode < 3 { tools_float::set_window_dock_zone(&ctx, ui.available_rect_before_wrap()); } - if !self.ui.tools_beside_canvas { - // A canvas-edge target left from before the setting was turned off docks nothing. - tools_float::clear_canvas_dock_zone(&ctx); - } // Beside the canvas, docked Tools draws inside the canvas panel (`toolbar::show_beside_canvas`). // So does Tools docked on the right, left of the panels. if self.ui.toolbar && self.ui.screen_mode < 3 && ((!self.ui.tools_beside_canvas && !self.ui.toolbar_right) || self.ui.toolbar_pos.is_some()) { @@ -628,6 +635,8 @@ impl VectorcraftApp { plugin_runs::show(self, &ctx); trace_runs::show(self, &ctx); opening::show(self, &ctx); + // After every window this pass may open, and before the palette's field takes the keyboard. + panel_docking::close_overlays_for_modal(self, &ctx); palette::show(self, &ctx); // After every panel had its chance to draw in this pass. crate::panels::three_d::end_stale_drag(self, &ctx); diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 6c31668533..701c0f5ffc 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -252,9 +252,7 @@ impl VectorcraftApp { { self.last_pathfinder = Some(op.to_string()); } - if r.is_ok() && matches!(id, "edit.copy" | "edit.cut" | "artboard.copy" | "artboard.cut") { - self.publish_clipboard(); - } + let copied = r.is_ok() && self.publish_copy(id); self.sync_views(); self.refresh_replace_font_warning(false); // File › Revert replaces the document in its tab, keeps the tab's view and starts the tool afresh. @@ -262,16 +260,13 @@ impl VectorcraftApp { match &r { Err(e) => self.ui.status = e.clone(), Ok(v) => { - // Image Trace's notes (a large image traces more slowly, or was scaled down). - if id.starts_with("imageTrace.make") - && let Some(w) = v["warnings"].as_array().and_then(|w| w.first()).and_then(Value::as_str) - { - self.ui.status = w.to_string(); + if matches!(id, "imageTrace.make" | "imageTrace.makeAndExpand") { + self.show_trace_notes(v); } // A renamed spot color swatch stays the Color Guide's base; a deleted one ends the link. panels::color_guide::after_command(self, id, ¶ms, v, spot_base); if id == "file.new" { - self.ui.status.clear(); + self.status(""); // New Document's Pixel preview mode (Overprint Preview is the engine's). if v["previewMode"] == "pixel" { self.ui.view.pixel_preview = true; @@ -280,7 +275,7 @@ impl VectorcraftApp { // Choosing a data set, or stepping to one, clears the status bar. The reply's `warning` // below then shows when no object is bound to a variable the data set has a value for. if matches!(id, "dataset.select" | "dataset.next" | "dataset.prev") { - self.ui.status.clear(); + self.status(""); } // A font applied with Character's font menu or Find Font's Change becomes the newest recent font. // Find Font's Change records the family the text now carries (any name of it is stored as its @@ -312,9 +307,42 @@ impl VectorcraftApp { } } } + // The message the Copy or Cut leaves is the one its clipboard formats' notes may replace. + if copied { + self.clipboard_publishing.ran_with_status(&self.ui); + } r } + /// After a Copy or Cut `id` that ran: offer what it copied to other apps + /// ([`Self::publish_clipboard`]) → whether `id` is one. + fn publish_copy(&mut self, id: &str) -> bool { + let copy = matches!(id, "edit.copy" | "edit.cut" | "artboard.copy" | "artboard.cut"); + if copy { + self.publish_clipboard(matches!(id, "edit.cut" | "artboard.cut")); + } + copy + } + + /// Image Trace's notes in `reply` (a large image traces more slowly, or was scaled down): the + /// first of them and how many there are, with the rest for the message's hover. A trace that + /// made no paths shows its first note as it is. Without notes, the message an earlier trace's + /// notes left is cleared while nothing has set the status since, and any other message stays. + fn show_trace_notes(&mut self, reply: &Value) { + let notes = io::notes_of(reply); + let left = self.trace_runs.notes_status.take(); + let Some(first) = notes.first() else { + io::clear_notes_left(self, left); + return; + }; + let status = match reply["paths"].as_u64() { + Some(0) => first.clone(), + _ => crate::trace_runs::traced_with_notes(notes.len(), first), + }; + io::show_with_notes(self, status, notes); + self.trace_runs.notes_status = Some((self.ui.status.clone(), self.ui.status_sets)); + } + fn set_command_warning(&mut self, id: &str, warning: &str) { self.ui.status = warning.to_string(); if id != "text.replaceFont" { @@ -484,4 +512,30 @@ impl VectorcraftApp { self.ui.status = s.into(); self.ui.status_sets = self.ui.status_sets.wrapping_add(1); } + + /// Begin the interaction a dialog or a panel previews on. Typing in progress is kept as its own + /// undo step first, and the warning of the preview that keeping it applied shows in the status + /// bar, as it does when a tool's drag begins. On an error no interaction begins, so the caller + /// runs no preview. + pub(crate) fn begin_interaction(&mut self, label: &str) -> Result<(), String> { + let warnings = self.session.begin_interaction_warned(label).map_err(|e| e.to_string())?; + self.show_warnings(warnings); + Ok(()) + } + + /// Keep typing in progress as one undo step and end the Type tool's typing session, with the + /// typing that Real-time Drawing off left unapplied applied first; its warning shows in the + /// status bar. + pub(crate) fn keep_typing(&mut self) -> Result<(), String> { + let warnings = self.session.keep_typing().map_err(|e| e.to_string())?; + self.show_warnings(warnings); + Ok(()) + } + + /// Each warning in the status bar in turn, as the tool's status requests show; the last stays. + fn show_warnings(&mut self, warnings: Vec) { + for w in warnings { + self.status(w); + } + } } diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index 6dc036fcf2..be5ff73c54 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -42,6 +42,10 @@ pub struct CanvasCache { pub print_tiling: Option, /// The gap lines View → Show Live Paint Gaps draws for (document uid, revision). pub live_paint_gaps: Option, + /// Type → Find Font's list of the document's fonts and whether the document misses one, for a + /// version of the document's content and of the available fonts: the dialog reads them every + /// frame. + pub find_font: Option, /// The marks Type → Show Hidden Characters drew on each text object in the last frame. A frame /// that does not draw them drops them ([`canvas::show`]). pub hidden_chars: canvas::HiddenChars, @@ -61,9 +65,15 @@ pub struct CanvasCache { pub selection_bounds: Option<((u64, u64), Option)>, /// [`VectorcraftApp::content_bounds`] for (document uid, revision). pub content_bounds: Option<((u64, u64), Option)>, + /// Whether the 3D and Materials panel's Export 3D Object button is available (a selected + /// object has a 3D effect that `assets.add3D` exports) for (document uid, revision). + pub three_d_exportable: Option<((u64, u64), bool)>, /// The Transform panel's Align to Pixel Grid state (on, off or mixed, and whether every /// selected object can be aligned) for (document uid, revision). pub pixel_aligned: Option<((u64, u64), Option)>, + /// The symbol instances in the selection and its groups, for (document uid, revision): the + /// Properties and Symbols panels read them every frame. + pub symbol_instances: Option<((u64, u64), SymbolInstances)>, /// [`CacheKey::plugins`] by document uid, with the plug-in revision /// ([`vectorcraft_render::effects::plugin_revision`]) it was last checked at. pub plugin_keys: std::collections::HashMap, @@ -111,10 +121,48 @@ pub type SliceCache = ((u64, u64), std::sync::Arc>); +/// [`CanvasCache::find_font`]: the document's fonts as `text.fonts` lists them, and whether +/// [`vectorcraft_engine::cmd::fontfiles::missing_fonts`] finds any (`None` until it is asked). +#[derive(Clone, Debug)] +pub struct FindFontCache { + /// The document and the content and fonts the answers were worked out from. + pub key: FontsKey, + pub fonts: std::sync::Arc>, + pub missing: Option, +} + +/// A document's uid, a version of its content (compared by identity) and the font database's +/// generation ([`vectorcraft_text::FontDb::generation`]). The weak reference keeps the version's +/// allocation, so a later version is never placed at the same address while the key is kept. +#[derive(Clone, Debug)] +pub struct FontsKey { + pub uid: u64, + pub doc: std::sync::Weak, + pub generation: u64, +} + +impl PartialEq for FontsKey { + fn eq(&self, other: &Self) -> bool { + self.uid == other.uid && self.generation == other.generation && std::sync::Weak::ptr_eq(&self.doc, &other.doc) + } +} + /// [`CanvasCache::pixel_aligned`]: the selected objects' Align to Pixel Grid, on or off when they /// agree and `None` when they differ, with whether every one can be aligned. pub type PixelAligned = (Option, bool); +/// [`CanvasCache::symbol_instances`]: the symbol instances in the selection and its groups. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct SymbolInstances { + /// Each instance's id, in the order the selection's subtrees list them. + pub ids: Vec, + /// One of them has appearance changes of its own (`symbol_overrides`). + pub changed: bool, + /// One of them has a scale, rotation or shear that Reset Transformation would change; measured + /// on the first read. + pub transformed: Option, +} + /// [`CanvasCache::print_tiling`]: the print tiling of (document uid, revision). pub type PrintTilingCache = ((u64, u64), std::sync::Arc>); diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 70c8834c2d..ef7ef0ba78 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -64,14 +64,14 @@ pub use overlays::SharedPaths; #[cfg(test)] use overlays::selected_anchor; use overlays::{HandleLook, blend_widgets_overlay, draw_inside_overlay, draw_overlays, hover_highlight, ime_geometry, selection_overlay}; -pub use panes::Panes; +pub use panes::{Layout as TileLayout, Panes}; pub(crate) use panes::{consolidate, note_drop, noted_cursor, pane, release_on_noted, tile, tiled_area}; pub(crate) use raster::{KeptFrame, color_image, color_image_owned, render_job}; use raster::{changed_pixels, frame_ppp, pixel_region, upload}; pub use selection_marks::SelectionMarks; -#[cfg(test)] -pub(crate) use task_bar::chip_paints; use task_bar::task_bar; +#[cfg(test)] +pub(crate) use task_bar::{chip_paints, images_with_other_art}; pub(crate) use task_bar::{has_colors, task_bar_rect, task_bar_shows_fonts, task_bar_shows_type}; #[cfg(test)] use tool_overlays::{DIAL_RADIUS, HiddenMarks}; @@ -175,7 +175,7 @@ enum Drag { }, /// A Selection tool move over a panel or toolbar: the art waits where it last moved on the /// canvas, and the panels get it ([`widgets::PanelDrag::Art`]) if it is released there. Back - /// on the canvas the move goes on, as in Illustrator (#2826). + /// on the canvas the move goes on (#2826). Art, /// Fingers making a touch gesture ([`crate::touch`]): the first one's press does nothing. Gesture, @@ -832,7 +832,7 @@ fn frame_options( // Type › Highlight Substituted Fonts: pink behind text in a substitute font. highlight_substituted_fonts: app.session.prefs.highlight_substituted_fonts, // General › Anti-aliased Artwork: off, edges are hard on screen (raster effects and - // pattern tiles stay smooth), as in Illustrator. + // pattern tiles stay smooth). anti_alias: if app.session.prefs.anti_aliased_artwork { vectorcraft_render::AntiAlias::Art } else { vectorcraft_render::AntiAlias::None }, progressive_placed: true, trace_views: true, diff --git a/crates/ui-egui/src/canvas/context.rs b/crates/ui-egui/src/canvas/context.rs index d8cd85d13a..9cdec919b5 100644 --- a/crates/ui-egui/src/canvas/context.rs +++ b/crates/ui-egui/src/canvas/context.rs @@ -75,10 +75,11 @@ pub(super) fn panel_drop(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respons } return; } - // A symbol from the Symbols panel: an instance centred where it is dropped, on art or not. - if let widgets::PanelDrag::Symbol(name) = &*d { + // A symbol from the Symbols panel: an instance centred where it is dropped, on art or not. A + // symbol of another document is added to this one first. + if let widgets::PanelDrag::Symbol { document, name } = &*d { let at = xf.to_doc(pos); - if let Err(e) = app.run("symbol.place", json!({"name": name, "x": at.x, "y": at.y})) { + if let Err(e) = app.run("symbol.placeFromDocument", json!({"sourceDocument": document, "name": name, "x": at.x, "y": at.y})) { app.status(e); } return; @@ -155,7 +156,7 @@ pub(super) fn panel_drop(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respons // Art dragged back onto the canvas: its move was already dropped. (A symbol was placed // above.) widgets::PanelDrag::Art(_) - | widgets::PanelDrag::Symbol(_) + | widgets::PanelDrag::Symbol { .. } | widgets::PanelDrag::LibrarySymbol { .. } | widgets::PanelDrag::LibraryGraphic { .. } => return, // A Libraries panel style or group only moves within that panel. diff --git a/crates/ui-egui/src/canvas/drag.rs b/crates/ui-egui/src/canvas/drag.rs index 68f06c70cc..bdda812306 100644 --- a/crates/ui-egui/src/canvas/drag.rs +++ b/crates/ui-egui/src/canvas/drag.rs @@ -317,7 +317,7 @@ pub(super) fn drag_art_out(app: &VectorcraftApp, ui: &Ui, resp: &egui::Response, // The art the drag started with: the release rolls the move back to it, and an Alt-copy's // copies, selected while it previews, go with that. let ids = it.selection.objects.clone(); - egui::DragAndDrop::set_payload(ui.ctx(), widgets::PanelDrag::Art(ids)); + widgets::drag_art(ui.ctx(), st.uid, ids); true } @@ -423,6 +423,7 @@ pub fn apply_requests(app: &mut VectorcraftApp, r: vectorcraft_engine::Result crate::dialogs::open_tool_dialog(app, &kind, p), + vectorcraft_engine::UiRequest::Panel(panel) => activate_panel(app, &panel), vectorcraft_engine::UiRequest::SwitchTool(t) => app.select_tool(&t), vectorcraft_engine::UiRequest::Status(msg) => app.status(msg), vectorcraft_engine::UiRequest::Place(p) => crate::place::place_from_cursor(app, &p), @@ -442,3 +443,11 @@ pub fn apply_requests(app: &mut VectorcraftApp, r: vectorcraft_engine::Result app.status(e.to_string()), } } + +/// Show and select `panel` where it is (`window.panel.activate`): a panel already on show stays on +/// show, and a dock hidden by Tab shows again. +fn activate_panel(app: &mut VectorcraftApp, panel: &str) { + if let Err(e) = app.run("window.panel.activate", serde_json::json!({ "panel": panel })) { + app.status(e); + } +} diff --git a/crates/ui-egui/src/canvas/grid.rs b/crates/ui-egui/src/canvas/grid.rs index 84adb0d861..001b2e31f7 100644 --- a/crates/ui-egui/src/canvas/grid.rs +++ b/crates/ui-egui/src/canvas/grid.rs @@ -432,7 +432,7 @@ pub(super) fn rulers(ui: &Ui, full: egui::Rect, xf: &Xf, hover: Option, s let sy = left.top() + d; clip_left.line_segment([pos2(left.right() - len, sy), pos2(left.right(), sy)], Stroke::new(1.0, t.ruler_tick)); if let Some(text) = label { - // Vertical labels read top-to-bottom, one digit per line like Illustrator. + // Vertical labels read top-to-bottom, one digit per line. let top = sy + 2.0; if top < filled_to { return; diff --git a/crates/ui-egui/src/canvas/home.rs b/crates/ui-egui/src/canvas/home.rs index bffab8f06c..c103c4b7ea 100644 --- a/crates/ui-egui/src/canvas/home.rs +++ b/crates/ui-egui/src/canvas/home.rs @@ -25,7 +25,7 @@ pub(super) fn home(app: &mut VectorcraftApp, ui: &mut Ui, rect: egui::Rect) { /// The Home screen's column: welcome, New / Open, Recent Files, Learn, presets and community links. fn home_content(app: &mut VectorcraftApp, ui: &mut Ui) { let t = Tokens::get(ui.ctx()); - // The welcome and the New / Open buttons sit centred, as PhotoCraft's Home screen does (#4684). + // The welcome and the New / Open buttons sit centred (#4684). ui.vertical_centered(|ui| { ui.label(egui::RichText::new(tl!("Welcome to VectorCraft")).font(theme::semibold(26.0)).color(t.text)); ui.add_space(4.0); diff --git a/crates/ui-egui/src/canvas/panes.rs b/crates/ui-egui/src/canvas/panes.rs index e6e16ad271..6b1d8ac3f2 100644 --- a/crates/ui-egui/src/canvas/panes.rs +++ b/crates/ui-egui/src/canvas/panes.rs @@ -1,5 +1,6 @@ //! Window › Arrange › Tile: every open document in a pane of its own, edge to edge in the document -//! area. The current document's pane is the canvas ([`super::show`]). Each other pane draws its +//! area, in a grid, side by side or stacked; the 2-up to 6-up layouts show that many and leave the +//! rest under their tabs ([`Layout`]). The current document's pane is the canvas ([`super::show`]). Each other pane draws its //! document from a render of its own, with its artboards, guides and selected objects, and a press //! in it makes its document the current one. A Selection drag released in it drops the dragged //! artwork into its document ([`crate::document_drag::drop_on_pane`]). Each view Window › New @@ -39,6 +40,9 @@ pub struct Panes { pending: HashMap, /// The panes the last frame drew, as (window, pane rect). pub(crate) last: Vec<(Win, egui::Rect)>, + /// The slots of `last`'s windows, in the same order: which windows they were, as document + /// indices shift when a document closes. + last_slots: Vec>, /// By slot: the size of the view's area its view was last fitted to in a pane, and the zoom and /// center the fit gave. fits: HashMap, @@ -50,6 +54,7 @@ impl Panes { self.shown.clear(); self.pending.clear(); self.last.clear(); + self.last_slots.clear(); self.fits.clear(); } @@ -162,37 +167,123 @@ fn render_pane( img } -/// The grid of `n` panes in `area`, filled row by row: as many columns as the square root of `n` -/// rounded up, and as many rows as those columns need. The panes meet edge to edge and cover -/// `area`; the spare cells of the last row stay empty. -pub(crate) fn cells(n: usize, area: egui::Rect) -> Vec { - if n == 0 { - return vec![]; +/// How Tile lays out the panes (`window.arrange.tile`'s `layout`). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Layout { + /// A grid: as many columns as the square root of the number of panes rounded up. + #[default] + Grid, + /// Side by side in one row, each pane as tall as the document area. + Vertical, + /// Stacked in one column, each pane as wide as the document area. + Horizontal, + /// At most this many panes (2, 3, 4 or 6); the other windows stay under their tabs. + Up(usize), +} + +impl Layout { + /// Each layout with its name in `layout`, in the order the menus list them. + pub(crate) const ALL: [(&'static str, Layout); 7] = [ + ("grid", Layout::Grid), + ("vertical", Layout::Vertical), + ("horizontal", Layout::Horizontal), + ("2up", Layout::Up(2)), + ("3up", Layout::Up(3)), + ("4up", Layout::Up(4)), + ("6up", Layout::Up(6)), + ]; + + /// The layout's name in `layout`. + pub(crate) fn name(self) -> &'static str { + Self::ALL.iter().find(|(_, l)| *l == self).map_or("grid", |(n, _)| n) } + + /// The layout `p`'s `layout` names, the grid without one. Any other value is an error. + pub(crate) fn from_params(p: &serde_json::Value) -> Result { + let key = "layout"; + match p.get(key) { + None => Ok(Layout::Grid), + Some(v) => v + .as_str() + .and_then(|s| Self::ALL.iter().find(|(n, _)| *n == s)) + .map(|(_, l)| *l) + .ok_or_else(|| format!("`{key}` must be one of {}", Self::ALL.map(|(n, _)| n).join(", "))), + } + } + + /// How many of `n` windows the layout gives a pane. + fn panes(self, n: usize) -> usize { + match self { + Layout::Up(k) => n.min(k), + _ => n, + } + } + + /// How many columns the layout puts `n` panes in. + fn columns(self, n: usize) -> usize { + match self { + Layout::Grid => grid_columns(n), + Layout::Vertical => n, + Layout::Horizontal => 1, + Layout::Up(k) if k <= 3 => n, + Layout::Up(k) => grid_columns(k).min(n), + } + } +} + +/// The square root of `n` rounded up. +fn grid_columns(n: usize) -> usize { let mut cols = 1; while cols * cols < n { cols += 1; } + cols +} + +/// The `n` panes `layout` places in `area`, filled row by row, in as many rows as its columns +/// need (the grid: as many columns as the square root of `n` rounded up). The panes meet edge to +/// edge and cover `area`; the spare cells of the last row stay empty. +pub(crate) fn layout_cells(layout: Layout, n: usize, area: egui::Rect) -> Vec { + if n == 0 { + return vec![]; + } + let cols = layout.columns(n).clamp(1, n); let rows = n.div_ceil(cols); let x = |c: usize| if c == cols { area.right() } else { area.left() + area.width() * c as f32 / cols as f32 }; let y = |r: usize| if r == rows { area.bottom() } else { area.top() + area.height() * r as f32 / rows as f32 }; (0..n).map(|i| egui::Rect::from_min_max(pos2(x(i % cols), y(i / cols)), pos2(x(i % cols + 1), y(i / cols + 1)))).collect() } -/// `window.arrange.tile`: every open document, and each further view of one, in a pane of its own, -/// each fitted to its pane. With fewer than two windows open (when the menu item is grayed out) it -/// leaves the view and `tiled` as they are. The windows floating come back under the tabs for it. -pub(crate) fn tile(app: &mut VectorcraftApp) -> Result { +/// The windows of `docked` (in tab order) that `layout` gives a pane: all of them, or as many of +/// the first ones as it shows, with the current window `active` in the last pane when it is not +/// among them. +pub(crate) fn shown_windows(layout: Layout, docked: &[Win], active: Option) -> Vec { + let k = layout.panes(docked.len()); + let mut shown = docked[..k].to_vec(); + if let (Some(a), Some(last)) = (active.filter(|a| !shown.contains(a) && docked.contains(a)), shown.last_mut()) { + *last = a; + } + shown +} + +/// `window.arrange.tile`: every open document, and each further view of one, in a pane of its own +/// as `layout` places them (the grid without one), each fitted to its pane. With fewer than two +/// windows open (when the menu item is grayed out) it leaves the view, `tiled` and the layout as +/// they are. The windows floating come back under the tabs for it. A `layout` that is not one of +/// [`Layout::ALL`]'s names is an error. +pub(crate) fn tile(app: &mut VectorcraftApp, p: &serde_json::Value) -> Result { + let layout = Layout::from_params(p)?; app.sync_views(); let n = crate::doc_windows::windows(app).len(); if n < 2 { - return Ok(json!({"tiled": app.ui.tiled, "panes": n})); + return Ok(json!({"tiled": app.ui.tiled, "panes": n, "layout": app.ui.tile_layout.name()})); } crate::doc_windows::dock_all(app); app.ui.tiled = true; + app.ui.tile_layout = layout; app.ui.home = None; crate::doc_windows::unfit_all(app); - Ok(json!({"tiled": app.ui.tiled, "panes": n})) + Ok(json!({"tiled": app.ui.tiled, "panes": layout.panes(n), "layout": layout.name()})) } /// `window.arrange.consolidateAllWindows`: one document at a time again, under its tab, the @@ -220,27 +311,43 @@ pub(crate) fn tiled_area(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { app.canvas.panes.clear(); } app.canvas.panes.last.clear(); + app.canvas.panes.last_slots.clear(); return false; } // The current window's pane is the canvas, unless it is a floating one. let active = crate::doc_windows::current(app).filter(|a| docked.contains(a)); + // The 2-up to 6-up layouts leave the windows past their panes under the tabs. + let layout = app.ui.tile_layout; + let shown = shown_windows(layout, &docked, active); app.sync_views(); - let live: Vec = crate::doc_windows::windows(app).into_iter().filter_map(|w| slot(app, w)).collect(); + // The renders of the panes and the floating windows stay; a window under its tab has none. + let live: Vec = + crate::doc_windows::windows(app).into_iter().filter(|w| shown.contains(w) || !docked.contains(w)).filter_map(|w| slot(app, w)).collect(); app.canvas.panes.shown.retain(|s, _| live.contains(s)); app.canvas.panes.pending.retain(|s, _| live.contains(s)); app.canvas.panes.fits.retain(|s, _| live.contains(s)); - // A window opened, closed, floated or docked changes the grid, and so does coming back to the - // panes from one window: each window fits its new pane. - if app.canvas.panes.last.iter().map(|(w, _)| *w).ne(docked.iter().copied()) { - for w in &docked { - if let Some(v) = crate::doc_windows::view_mut(app, *w) { - v.fitted = false; - } + // A window that moved to another pane fits it, and so does a window whose pane changed place or + // size because a window opened, closed, floated or docked, or because the panes came back from + // one window. A window that keeps its pane keeps its zoom and scroll, as when a tab brings its + // window into the last pane of a 2-up to 6-up layout, or when 6-Up loses its sixth document. + // Windows are compared by their slots, since a closed document shifts the indices of the + // documents after it, and panes by their place in the layout. + let before = std::mem::take(&mut app.canvas.panes.last_slots); + let now: Vec> = shown.iter().map(|w| slot(app, *w)).collect(); + let unit = egui::Rect::from_min_size(pos2(0.0, 0.0), vec2(1.0, 1.0)); + let (cells_before, cells_now) = (layout_cells(layout, before.len(), unit), layout_cells(layout, now.len(), unit)); + for (i, (w, s)) in shown.iter().zip(&now).enumerate() { + if s.is_some() && before.get(i) == Some(s) && cells_before.get(i) == cells_now.get(i) { + continue; + } + if let Some(v) = crate::doc_windows::view_mut(app, *w) { + v.fitted = false; } } + app.canvas.panes.last_slots = now; let t = Tokens::get(ui.ctx()); let ppp = ui.ctx().pixels_per_point(); - let cells: Vec<(Win, egui::Rect)> = docked.iter().copied().zip(cells(n, ui.available_rect_before_wrap())).collect(); + let cells: Vec<(Win, egui::Rect)> = shown.iter().copied().zip(layout_cells(layout, shown.len(), ui.available_rect_before_wrap())).collect(); let areas: Vec<(Win, egui::Rect)> = cells.iter().map(|(w, cell)| (*w, view_rects(app, *cell, ppp).1)).collect(); let unfitted = refit_resized(app, &areas); let mut activate = None; diff --git a/crates/ui-egui/src/canvas/panes/tests.rs b/crates/ui-egui/src/canvas/panes/tests.rs index 03c0ce7bed..6c7a8cf755 100644 --- a/crates/ui-egui/src/canvas/panes/tests.rs +++ b/crates/ui-egui/src/canvas/panes/tests.rs @@ -43,6 +43,11 @@ fn button(pos: Pos2, pressed: bool) -> egui::Event { egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() } } +/// Tile's grid of `n` panes in `area`. +fn cells(n: usize, area: egui::Rect) -> Vec { + layout_cells(Layout::Grid, n, area) +} + /// The documents' indices in the panes the last frame drew, and the panes. fn panes(app: &VectorcraftApp) -> (Vec, Vec) { app.canvas.panes.last.iter().map(|(w, r)| (w.0, *r)).unzip() @@ -84,6 +89,336 @@ fn cells_tile_the_area_edge_to_edge() { } } +/// The distinct left and top edges of `c`: how many columns and rows its panes take. +fn columns_and_rows(c: &[egui::Rect]) -> (usize, usize) { + let lefts: BTreeSet = c.iter().map(|r| r.left().to_bits()).collect(); + let tops: BTreeSet = c.iter().map(|r| r.top().to_bits()).collect(); + (lefts.len(), tops.len()) +} + +#[test] +fn each_tile_layout_places_its_panes_edge_to_edge() { + let area = egui::Rect::from_min_size(pos2(10.0, 35.0), vec2(1001.0, 703.0)); + let cases = [ + (Layout::Vertical, 3, (3, 1)), + (Layout::Vertical, 7, (7, 1)), + (Layout::Horizontal, 3, (1, 3)), + (Layout::Up(2), 2, (2, 1)), + (Layout::Up(3), 3, (3, 1)), + (Layout::Up(3), 2, (2, 1)), + (Layout::Up(4), 4, (2, 2)), + (Layout::Up(4), 3, (2, 2)), + (Layout::Up(6), 6, (3, 2)), + (Layout::Up(6), 4, (3, 2)), + (Layout::Up(6), 2, (2, 1)), + ]; + for (layout, n, shape) in cases { + let c = layout_cells(layout, n, area); + assert_eq!(c.len(), n); + assert_eq!(columns_and_rows(&c), shape, "{layout:?} with {n} panes: columns and rows"); + assert_eq!(c[0].min, area.min, "{layout:?}: the first pane starts at the corner"); + let right = c.iter().map(|r| r.right()).fold(f32::MIN, f32::max); + let bottom = c.iter().map(|r| r.bottom()).fold(f32::MIN, f32::max); + assert_eq!((right, bottom), (area.right(), area.bottom()), "{layout:?} with {n} panes reaches the far edges"); + for (i, r) in c.iter().enumerate() { + assert!(r.width() > 0.0 && r.height() > 0.0 && area.contains_rect(*r), "{layout:?}: {r:?}"); + for o in &c[i + 1..] { + assert!(r.intersect(*o).area() <= 0.0, "{layout:?} panes overlap: {r:?} {o:?}"); + } + } + } + assert!(layout_cells(Layout::Up(2), 0, area).is_empty()); +} + +#[test] +fn tile_layouts_line_the_documents_up_side_by_side_or_stacked() { + let mut app = app_with(3); + let ctx = egui::Context::default(); + let reply = app.run("window.arrange.tile", json!({"layout": "vertical"})).unwrap(); + assert_eq!(reply, json!({"tiled": true, "panes": 3, "layout": "vertical"})); + frame(&mut app, &ctx, vec![]); + let (docs, rects) = panes(&app); + assert_eq!(docs, [0, 1, 2]); + assert!(rects.windows(2).all(|p| p[0].top() == p[1].top() && p[0].height() == p[1].height() && p[0].right() == p[1].left()), "{rects:?}"); + let reply = app.run("window.arrange.tile", json!({"layout": "horizontal"})).unwrap(); + assert_eq!(reply, json!({"tiled": true, "panes": 3, "layout": "horizontal"})); + frame(&mut app, &ctx, vec![]); + let (docs, rects) = panes(&app); + assert_eq!(docs, [0, 1, 2]); + assert!(rects.windows(2).all(|p| p[0].left() == p[1].left() && p[0].width() == p[1].width() && p[0].bottom() == p[1].top()), "{rects:?}"); + // Each document fits its new pane. + let artboard = Rect::new(0.0, 0.0, 400.0, 300.0); + let canvas = app.canvas_rect.unwrap(); + for (i, r) in docs.iter().zip(&rects) { + let shown = if *i == 2 { canvas } else { view_rects(&app, *r, ctx.pixels_per_point()).1 }; + let v = app.views[*i]; + assert!(v.fitted && (v.zoom - fit_zoom(shown, artboard, 0.0, 1.0)).abs() < 1e-9, "document {i} fits its pane: {v:?}"); + } + assert_eq!(crate::control::inspect(&app, &ctx)["tileLayout"], json!("horizontal")); + assert_eq!(app.run("window.arrange.tile", json!({})).unwrap()["layout"], json!("grid"), "Tile without a layout is the grid"); +} + +#[test] +fn n_up_shows_that_many_documents_and_keeps_the_rest_under_their_tabs() { + let mut app = app_with(5); + let ctx = egui::Context::default(); + assert_eq!(app.run("window.arrange.tile", json!({"layout": "2up"})).unwrap(), json!({"tiled": true, "panes": 2, "layout": "2up"})); + frame(&mut app, &ctx, vec![]); + assert_eq!(panes(&app).0, [0, 4], "the current document takes the last pane"); + app.run("document.activate", json!({"index": 1})).unwrap(); + frame(&mut app, &ctx, vec![]); + assert_eq!(panes(&app).0, [0, 1], "the first documents in tab order"); + let second = (app.session.documents()[1].uid, 1); + app.run("document.activate", json!({"index": 0})).unwrap(); + frame(&mut app, &ctx, vec![]); + assert!(app.canvas.panes.shown.contains_key(&second), "the second document is rendered for its pane"); + app.run("document.activate", json!({"index": 3})).unwrap(); + frame(&mut app, &ctx, vec![]); + let (docs, rects) = panes(&app); + assert_eq!(docs, [0, 3], "a document chosen under its tab comes into the last pane"); + assert!(!app.canvas.panes.shown.contains_key(&second), "a document under its tab keeps no render"); + let artboard = Rect::new(0.0, 0.0, 400.0, 300.0); + let shown = view_rects(&app, rects[0], ctx.pixels_per_point()).1; + assert!((app.views[0].zoom - fit_zoom(shown, artboard, 0.0, 1.0)).abs() < 1e-9); + assert!(app.canvas_rect.is_some_and(|c| rects[1].contains_rect(c)), "the current document's pane is the canvas"); + // A document brought into the last pane leaves the first pane's zoom as it is. + app.views[0].zoom *= 2.0; + let zoomed = app.views[0].zoom; + app.run("document.activate", json!({"index": 2})).unwrap(); + frame(&mut app, &ctx, vec![]); + assert_eq!(panes(&app).0, [0, 2]); + assert_eq!(app.views[0].zoom, zoomed, "the document that stayed in its pane keeps its zoom"); + let last = app.canvas_rect.unwrap(); + assert!((app.views[2].zoom - fit_zoom(last, artboard, 0.0, 1.0)).abs() < 1e-9, "the document brought in fits its pane"); + assert_eq!(app.run("window.arrange.tile", json!({"layout": "4up"})).unwrap()["panes"], json!(4)); + frame(&mut app, &ctx, vec![]); + let (docs, rects) = panes(&app); + assert_eq!((docs, columns_and_rows(&rects)), (vec![0, 1, 2, 3], (2, 2))); + assert_eq!(app.run("window.arrange.tile", json!({"layout": "6up"})).unwrap()["panes"], json!(5), "6-Up with five documents shows them all"); + frame(&mut app, &ctx, vec![]); + let (docs, rects) = panes(&app); + assert_eq!((docs, columns_and_rows(&rects)), (vec![0, 1, 2, 3, 4], (3, 2))); + assert_eq!(app.run("window.arrange.tile", json!({"layout": "3up"})).unwrap()["panes"], json!(3)); + frame(&mut app, &ctx, vec![]); + let (docs, rects) = panes(&app); + assert_eq!((docs, columns_and_rows(&rects)), (vec![0, 1, 2], (3, 1))); + app.run("document.activate", json!({"index": 4})).unwrap(); + frame(&mut app, &ctx, vec![]); + assert_eq!(panes(&app).0, [0, 1, 4]); +} + +/// A document closed before the panes shifts the indices of the ones after it: the document that +/// moves into another pane fits it. +#[test] +fn closing_a_document_in_an_n_up_layout_fits_the_documents_that_change_panes() { + let mut app = app_with(4); + let ctx = egui::Context::default(); + app.run("document.activate", json!({"index": 1})).unwrap(); + app.run("window.arrange.tile", json!({"layout": "2up"})).unwrap(); + frame(&mut app, &ctx, vec![]); + app.run("document.activate", json!({"index": 3})).unwrap(); + frame(&mut app, &ctx, vec![]); + assert_eq!(panes(&app).0, [0, 3]); + let moving = app.session.documents()[1].uid; + // The second document's view, under its tab, is zoomed away from its fit. + app.views[1].zoom *= 3.0; + app.run("file.close", json!({"index": 0})).unwrap(); + frame(&mut app, &ctx, vec![]); + let (docs, rects) = panes(&app); + assert_eq!(docs, [0, 2], "the former second document is first now, the current one stays last"); + assert_eq!(app.session.documents()[0].uid, moving); + let area = view_rects(&app, rects[0], ctx.pixels_per_point()).1; + let v = app.views[0]; + assert!(v.fitted && (v.zoom - fit_zoom(area, Rect::new(0.0, 0.0, 400.0, 300.0), 0.0, 1.0)).abs() < 1e-9, "it fits its new pane: {v:?}"); +} + +/// 6-Up keeps its three columns and two rows with five documents: closing the sixth leaves the +/// others in their panes with the zoom they had. Side by side, closing one widens every pane, and +/// each document fits its new pane. +#[test] +fn closing_a_document_keeps_the_zoom_of_the_documents_whose_panes_stay() { + let mut app = app_with(6); + let ctx = egui::Context::default(); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("window.arrange.tile", json!({"layout": "6up"})).unwrap(); + frame(&mut app, &ctx, vec![]); + assert_eq!(panes(&app).0, [0, 1, 2, 3, 4, 5]); + app.views[1].zoom *= 2.0; + let zoomed = app.views[1].zoom; + app.run("file.close", json!({"index": 5})).unwrap(); + frame(&mut app, &ctx, vec![]); + let (docs, rects) = panes(&app); + assert_eq!((docs, columns_and_rows(&rects)), (vec![0, 1, 2, 3, 4], (3, 2))); + assert_eq!(app.views[1].zoom, zoomed, "the document that kept its pane keeps its zoom"); + + let mut app = app_with(3); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("window.arrange.tile", json!({"layout": "vertical"})).unwrap(); + frame(&mut app, &ctx, vec![]); + app.views[1].zoom *= 2.0; + app.run("file.close", json!({"index": 2})).unwrap(); + frame(&mut app, &ctx, vec![]); + let (docs, rects) = panes(&app); + assert_eq!(docs, [0, 1]); + let area = view_rects(&app, rects[1], ctx.pixels_per_point()).1; + let v = app.views[1]; + assert!(v.fitted && (v.zoom - fit_zoom(area, Rect::new(0.0, 0.0, 400.0, 300.0), 0.0, 1.0)).abs() < 1e-9, "it fits its wider pane: {v:?}"); +} + +#[test] +fn tile_refuses_a_layout_it_does_not_have() { + let mut app = app_with(3); + for bad in [json!("5up"), json!("Vertical"), json!(3), json!(null), json!({})] { + let err = app.run("window.arrange.tile", json!({"layout": bad})).unwrap_err(); + assert_eq!(err, "`layout` must be one of grid, vertical, horizontal, 2up, 3up, 4up, 6up", "{bad}"); + assert!(!app.ui.tiled && app.ui.tile_layout == Layout::Grid, "{bad}: the view stays as it is"); + } + app.run("window.arrange.tile", json!({"layout": "vertical"})).unwrap(); + assert!(app.run("window.arrange.tile", json!({"layout": "diagonal"})).is_err()); + assert_eq!(app.ui.tile_layout, Layout::Vertical, "a refused layout leaves the tiled one"); + // With one document the layout is still checked, and nothing changes. + let mut one = app_with(1); + assert!(one.run("window.arrange.tile", json!({"layout": "7up"})).is_err()); + assert_eq!(one.run("window.arrange.tile", json!({"layout": "2up"})).unwrap(), json!({"tiled": false, "panes": 1, "layout": "grid"})); +} + +#[test] +fn the_tile_items_check_the_layout_the_panes_show() { + let mut app = app_with(3); + let checked = |app: &VectorcraftApp, layout: Option<&str>| { + let p = layout.map_or(serde_json::Value::Null, |l| json!({"layout": l})); + crate::menus::checked(app, "window.arrange.tile", &p) + }; + assert_eq!(checked(&app, None), Some(false), "not tiled"); + app.run("window.arrange.tile", json!({"layout": "4up"})).unwrap(); + assert_eq!(checked(&app, Some("4up")), Some(true)); + assert_eq!(checked(&app, None), Some(false)); + assert_eq!(checked(&app, Some("2up")), Some(false)); + app.run("window.arrange.tile", json!({})).unwrap(); + assert_eq!(checked(&app, None), Some(true), "Tile is the grid"); + app.run("window.arrange.consolidateAllWindows", json!({})).unwrap(); + assert_eq!(checked(&app, None), Some(false)); + // Window › Arrange lists every layout, after Cascade and before Float in Window. + let window = crate::menus::menu_tree().into_iter().find(|(t, _)| *t == "Window").map(|(_, items)| items).unwrap(); + let arrange = window + .into_iter() + .find_map(|i| match i { + crate::menus::Item::Sub("Arrange", items) => Some(items), + _ => None, + }) + .unwrap(); + let labels: Vec<&str> = arrange + .iter() + .filter_map(|i| match i { + crate::menus::Item::Cmd(l, ..) => Some(*l), + _ => None, + }) + .collect(); + assert_eq!( + labels, + [ + "Cascade", + "Tile", + "Tile All Vertically", + "Tile All Horizontally", + "2-Up Layout", + "3-Up Layout", + "4-Up Layout", + "6-Up Layout", + "Float in Window", + "Float All in Windows", + "Consolidate All Windows" + ] + ); + // Each item's params run, as the menu sends them. + for item in &arrange { + if let crate::menus::Item::Cmd(_, "window.arrange.tile", p) = item { + let p = if p.is_null() { json!({}) } else { p.clone() }; + assert!(app.run("window.arrange.tile", p.clone()).is_ok(), "{p}"); + } + } +} + +/// One frame of the application bar with screen-reader nodes on → the nodes. +fn app_bar_frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> Vec { + app_bar_frame_in(app, ctx, events, 1400.0) +} + +/// [`app_bar_frame`] on a window `width` points wide. +fn app_bar_frame_in(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec, width: f32) -> Vec { + let screen = egui::Rect::from_min_size(Pos2::ZERO, vec2(width, 800.0)); + let mut out = ctx.run_ui(egui::RawInput { events, screen_rect: Some(screen), ..Default::default() }, |ui| crate::chrome::app_bar(app, ui)); + out.textures_delta.clear(); + out.platform_output.accesskit_update.map(|u| u.nodes.into_iter().map(|(_, n)| n).collect()).unwrap_or_default() +} + +/// The center of the application bar's node whose label, without its leading spaces, is `name` +/// (or starts with it and a shortcut in parentheses). +fn app_bar_node(nodes: &[egui::accesskit::Node], name: &str) -> Option { + let named = |l: &str| l.trim_start().strip_prefix(name).is_some_and(|rest| rest.is_empty() || rest.trim_start().starts_with('(')); + let b = nodes.iter().find(|n| n.label().is_some_and(named))?.bounds()?; + Some(pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32)) +} + +/// Click the application bar's node labeled `name`. +fn click_app_bar(app: &mut VectorcraftApp, ctx: &egui::Context, name: &str) { + let at = app_bar_node(&app_bar_frame(app, ctx, vec![]), name).unwrap_or_else(|| panic!("{name} is drawn")); + app_bar_frame(app, ctx, vec![egui::Event::PointerMoved(at), button(at, true)]); + app_bar_frame(app, ctx, vec![button(at, false)]); +} + +#[test] +fn the_arrange_documents_button_tiles_and_consolidates() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = app_with(3); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + app_bar_frame(&mut app, &ctx, vec![]); + let nodes = app_bar_frame(&mut app, &ctx, vec![]); + let (arrange, search) = (app_bar_node(&nodes, "Arrange Documents"), app_bar_node(&nodes, "Search commands")); + let (arrange, search) = (arrange.expect("the application bar has Arrange Documents"), search.expect("the search shows")); + assert!(arrange.x > search.x && (arrange.y - search.y).abs() < 1.0, "right of the search: {arrange:?}, {search:?}"); + click_app_bar(&mut app, &ctx, "Arrange Documents"); + let menu = app_bar_frame(&mut app, &ctx, vec![]); + for item in [ + "Consolidate All Windows", + "Tile", + "Tile All Vertically", + "Tile All Horizontally", + "2-Up Layout", + "3-Up Layout", + "4-Up Layout", + "6-Up Layout", + ] { + assert!(app_bar_node(&menu, item).is_some(), "the menu lists {item}"); + } + click_app_bar(&mut app, &ctx, "Tile All Vertically"); + assert!(app.ui.tiled && app.ui.tile_layout == Layout::Vertical, "{}", app.ui.status); + click_app_bar(&mut app, &ctx, "Arrange Documents"); + click_app_bar(&mut app, &ctx, "Consolidate All Windows"); + assert!(!app.ui.tiled); +} + +/// As the application bar narrows, Arrange Documents goes before the search. +#[test] +fn a_narrow_application_bar_keeps_search_before_arrange_documents() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = app_with(3); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + let mut search_alone = false; + for width in (200..=1400).rev().step_by(4) { + app_bar_frame_in(&mut app, &ctx, vec![], width as f32); + let nodes = app_bar_frame_in(&mut app, &ctx, vec![], width as f32); + let (arrange, search) = (app_bar_node(&nodes, "Arrange Documents").is_some(), app_bar_node(&nodes, "Search commands").is_some()); + assert!(search || !arrange, "{width} pt: Arrange Documents shows without the search"); + search_alone |= search && !arrange; + } + assert!(search_alone, "some width shows the search without Arrange Documents"); +} + #[test] fn tile_shows_a_pane_for_each_document_fitted_to_it() { let mut app = app_with(3); @@ -91,7 +426,7 @@ fn tile_shows_a_pane_for_each_document_fitted_to_it() { frame(&mut app, &ctx, vec![]); assert!(panes(&app).0.is_empty(), "documents open under their tabs"); let tabbed = app.canvas_rect.unwrap(); - assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": true, "panes": 3})); + assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": true, "panes": 3, "layout": "grid"})); frame(&mut app, &ctx, vec![]); let (docs, rects) = panes(&app); assert_eq!(docs, [0, 1, 2]); @@ -454,7 +789,7 @@ fn arrange_items_follow_the_open_documents() { fn tile_with_one_document_leaves_the_next_one_under_its_tab() { let mut app = app_with(1); let ctx = egui::Context::default(); - assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": false, "panes": 1})); + assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": false, "panes": 1, "layout": "grid"})); assert!(!app.ui.tiled); assert!(!enabled(&app, "window.arrange.consolidateAllWindows")); app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); diff --git a/crates/ui-egui/src/canvas/task_bar.rs b/crates/ui-egui/src/canvas/task_bar.rs index e49fa9bfc7..c133c003f8 100644 --- a/crates/ui-egui/src/canvas/task_bar.rs +++ b/crates/ui-egui/src/canvas/task_bar.rs @@ -92,6 +92,31 @@ fn smooth_tool_on_paths(app: &VectorcraftApp, ctx: &egui::Context) -> bool { found } +/// Whether the selection holds images together with other objects, for which the bar offers Make +/// Clipping Mask: at least one selected object is an image and at least one is not (a selected id +/// with no object counts as not an image). The walk stops once it has seen both. The answer is kept +/// in `ctx` for the document's revision, as [`smooth_tool_on_paths`] keeps its own. +pub(crate) fn images_with_other_art(st: &vectorcraft_engine::DocState, ctx: &egui::Context) -> bool { + let id = task_bar_id().with("mixed"); + let key = (st.uid, st.revision); + if let Some((k, found)) = ctx.data(|d| d.get_temp::<((u64, u64), bool)>(id)) + && k == key + { + return found; + } + let (mut image, mut other) = (false, false); + let found = st.selection.objects.iter().any(|id| { + if st.doc.node(*id).is_some_and(|o| matches!(o.kind, NodeKind::Image(_))) { + image = true; + } else { + other = true; + } + image && other + }); + ctx.data_mut(|d| d.insert_temp(id, (key, found))); + found +} + /// Whether the bar shows its blank canvas actions, Draw (Pencil) and Place Image: a selection tool is /// in use and the active document has no artwork, only layers and guides. fn blank_canvas(app: &VectorcraftApp) -> bool { @@ -192,10 +217,7 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { _ => None, }); // Images and vector art selected together: a clipping mask is the likely next step. - let mixed = n > 1 && { - let images = st.selection.objects.iter().filter_map(|id| st.doc.node(*id)).filter(|o| matches!(o.kind, NodeKind::Image(_))).count(); - images > 0 && images < n - }; + let mixed = n > 1 && images_with_other_art(st, ui.ctx()); // An Image Trace object: the group the engine names "Image Trace", its source image first. let is_trace = is_group && first.as_ref().is_some_and(|f| { diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 34d0777c51..cea61e42bb 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -1647,6 +1647,37 @@ fn switch_selection_and_drawing_modes_command() { } } +/// Select Last Selection Tool: the Selection tool before any selection tool is chosen, then the +/// one of Selection, Direct Selection and Group Selection chosen last; Magic Wand and Lasso don't +/// count. Running it again keeps that tool, and it changes no art, selection or undo history. +#[test] +fn select_last_selection_tool_command() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let id = app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap()["id"].clone(); + app.session.execute("select.set", &json!({"ids": [id]})).unwrap(); + let last = |app: &mut VectorcraftApp| app.run("tool.selectLastSelection", json!({})).unwrap(); + let state = |app: &VectorcraftApp| { + let st = app.session.active().unwrap(); + (st.doc.clone(), st.selection.clone(), st.history.undo.len()) + }; + app.select_tool("pen"); + let before = state(&app); + assert_eq!((last(&mut app), app.session.tool_id()), (json!({"tool": "selection"}), "selection"), "none chosen yet: Selection"); + for id in ["directSelection", "groupSelection", "selection"] { + app.select_tool(id); + app.select_tool("pen"); + assert_eq!(last(&mut app), json!({"tool": id}), "{id}"); + } + app.select_tool("directSelection"); + for other in ["magicWand", "lasso", "rectangle", "hand"] { + app.select_tool(other); + } + assert_eq!(last(&mut app), json!({"tool": "directSelection"}), "Magic Wand and Lasso are not remembered"); + assert_eq!(last(&mut app), json!({"tool": "directSelection"}), "again: the same tool, no cycling"); + assert!(state(&app) == before, "no art, selection or undo step changes"); +} + /// A Switch Selection and Drawing Modes whose tool choice fails returns the error, in both /// directions: the tool stays, the drawing tool to return to stays, and no undo step is added. #[test] @@ -6869,10 +6900,136 @@ fn hidden_char_marks(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec c.fill == blue || c.stroke.color == blue, + Shape::Text(t) => t.fallback_color == blue, + Shape::LineSegment { stroke, .. } => stroke.color == blue, + Shape::Path(p) => p.stroke.color == egui::epaint::ColorMode::Solid(blue), + _ => false, + }) .collect() } +/// Show Hidden Characters marks each tab, nonbreaking space, narrow nonbreaking space, space of +/// a set width and discretionary hyphen with a mark of its kind, a plain space with a dot, and +/// a tab's arrow spans the tab's advance to its stop. +#[test] +fn hidden_characters_mark_tabs_nonbreaking_spaces_and_discretionary_hyphens() { + use super::tool_overlays::CharMark::*; + let text = "a b\tc\u{00A0}d\u{202F}e\u{2003}f\u{2009}g\u{200A}h\u{00AD}i"; + let t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(10.0, 50.0), text, vectorcraft_doc::CharStyle::default()); + let marks = HiddenMarks::of(&t); + let kinds: Vec<_> = marks.chars.iter().map(|c| c.0).collect(); + assert_eq!(kinds, [Tab, NoBreakSpace, NarrowNoBreakSpace, FixedSpace, FixedSpace, FixedSpace, DiscretionaryHyphen]); + assert_eq!(marks.spaces.len(), 1, "only the plain space has a dot"); + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); + let tab = lay.glyphs.iter().find(|g| text[g.byte..].starts_with('\t')).unwrap(); + assert!(tab.advance > 1.0, "{}", tab.advance); + let (_, a, b) = marks.chars[0]; + let start = t.xf * vectorcraft_geom::Point::new(tab.origin.x, tab.origin.y - 3.0); + assert!((a - start).hypot() < 1e-9 && (b.x - a.x - tab.advance).abs() < 1e-9 && b.y == a.y, "{a:?} {b:?} {start:?}"); +} + +/// Show Hidden Characters marks a line that a forced line break (U+2028) ends with a bent arrow +/// and no ¶; the line a paragraph return ends gets ¶, and the story's end #. +#[test] +fn hidden_characters_mark_forced_line_breaks() { + let t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::ZERO, "ab\u{2028}cd\nef", vectorcraft_doc::CharStyle::default()); + let marks = HiddenMarks::of(&t); + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); + assert_eq!(lay.lines.len(), 3); + assert_eq!(marks.breaks.len(), 1); + let (at, along, up) = marks.breaks[0]; + let first = &lay.lines[0]; + assert_eq!(at, vectorcraft_geom::Point::new(first.x1 + 1.0, first.baseline)); + assert_eq!((along - at, up - at), (vectorcraft_geom::Vec2::new(1.0, 0.0), vectorcraft_geom::Vec2::new(0.0, -1.0))); + let ends: Vec<_> = marks.ends.iter().map(|e| (e.1, e.0.y)).collect(); + assert_eq!(ends, [("¶", lay.lines[1].baseline), ("#", lay.lines[2].baseline)]); + // A story that ends with a forced line break: the arrow, and # on the empty line after it. + let t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::ZERO, "ab\u{2028}", vectorcraft_doc::CharStyle::default()); + let marks = HiddenMarks::of(&t); + assert_eq!((marks.breaks.len(), marks.ends.iter().map(|e| e.1).collect::>()), (1, vec!["#"])); +} + +/// A discretionary hyphen gets one ¬ also where the line breaks at it and the layout draws a +/// hyphen there, which stands for no character of the text. +#[test] +fn hidden_characters_mark_a_discretionary_hyphen_at_a_break_once() { + let style = vectorcraft_doc::CharStyle::default(); + let db = vectorcraft_text::FontDb::global(); + let word = vectorcraft_text::layout(db, &vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::ZERO, "coco-", style.clone())); + let width = word.lines[0].x1 - word.lines[0].x0 + 2.0; + let mut t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::ZERO, "coco\u{00AD}co", style); + t.kind = vectorcraft_doc::text::TextKind::Area { + frame: vectorcraft_geom::PathData::from_bezpath(&vectorcraft_geom::Rect::new(0.0, 0.0, width, 400.0).to_path(0.1)), + }; + let lay = vectorcraft_text::layout(db, &t); + assert_eq!(lay.lines.len(), 2, "the line breaks at the discretionary hyphen"); + assert!(lay.glyphs.iter().any(|g| g.len == 0), "the layout draws a hyphen at the break"); + let marks = HiddenMarks::of(&t); + assert_eq!(marks.chars.iter().map(|c| c.0).collect::>(), [super::tool_overlays::CharMark::DiscretionaryHyphen]); +} + +/// In vertical type the marks follow the column: a space's dot sits beside the column, halfway +/// down the space, and ¶ goes below the column's last character. +#[test] +fn hidden_characters_follow_vertical_type() { + let mut t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::ZERO, "a b\nc", vectorcraft_doc::CharStyle::default()); + t.vertical = true; + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); + let space = lay.glyphs.iter().find(|g| g.byte == 1).unwrap(); + let marks = HiddenMarks::of(&t); + let dot = marks.spaces[0]; + assert!((dot - vectorcraft_geom::Point::new(space.origin.x + 3.0, space.origin.y + space.advance / 2.0)).hypot() < 1e-9, "{dot:?} {space:?}"); + let (at, glyph, align) = marks.ends[0]; + assert_eq!((glyph, align), ("¶", egui::Align2::CENTER_TOP)); + let b = lay.glyphs.iter().find(|g| g.byte == 2).unwrap(); + assert!(at.y > b.origin.y, "{at:?} below {:?}", b.origin); +} + +/// In a right-to-left paragraph ¶ goes at the line's left end, where the paragraph ends. +#[test] +fn hidden_characters_end_a_right_to_left_line_at_its_left() { + let t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::ZERO, "אב גד\nהו", vectorcraft_doc::CharStyle::default()); + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); + assert!(lay.lines[0].rtl); + let marks = HiddenMarks::of(&t); + let (at, glyph, align) = marks.ends[0]; + assert_eq!((glyph, align), ("¶", egui::Align2::RIGHT_BOTTOM)); + assert_eq!(at.x, lay.lines[0].x0 - 1.0); +} + +/// Type on a path has the marks over its characters and # after its last one. +#[test] +fn hidden_characters_mark_type_on_a_path() { + let mut t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::ZERO, "a b\tc", vectorcraft_doc::CharStyle::default()); + let path = vectorcraft_geom::Line::new((0.0, 100.0), (600.0, 100.0)).to_path(0.1); + t.kind = vectorcraft_doc::text::TextKind::OnPath { path: vectorcraft_geom::PathData::from_bezpath(&path), start: 0.0, end: None }; + let marks = HiddenMarks::of(&t); + assert_eq!(marks.spaces.len(), 1); + assert_eq!(marks.chars.iter().map(|c| c.0).collect::>(), [super::tool_overlays::CharMark::Tab]); + assert_eq!(marks.ends.iter().map(|e| e.1).collect::>(), ["#"]); +} + +/// The overlay draws each kind of mark: a dot, two rings, the tab's arrow, a tick, ¬, the forced +/// line break's bent arrow, ¶ and #. +#[test] +fn show_hidden_characters_draws_every_kind_of_mark() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let text = "a b\tc\u{00A0}d\u{202F}e\u{2003}f\u{00AD}g\u{2028}h\ni"; + app.session.execute("text.create", &json!({"x": 20, "y": 60, "text": text})).unwrap(); + let ctx = egui::Context::default(); + let xf = Xf { rect: egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)), zoom: 1.0, center: Point::new(200.0, 150.0), rot: 0.0 }; + let shapes = hidden_chars(&mut app, &ctx, &xf); + let count = |f: &dyn Fn(&Shape) -> bool| shapes.iter().filter(|s| f(s)).count(); + assert_eq!(count(&|s| matches!(s, Shape::Circle(c) if c.fill != Color32::TRANSPARENT)), 1, "{shapes:?}"); + assert_eq!(count(&|s| matches!(s, Shape::Circle(c) if c.fill == Color32::TRANSPARENT)), 2, "{shapes:?}"); + assert_eq!(count(&|s| matches!(s, Shape::LineSegment { .. })), 2, "the tab's shaft and the tick: {shapes:?}"); + assert_eq!(count(&|s| matches!(s, Shape::Path(_))), 3, "the tab's head and the break's arrow: {shapes:?}"); + assert_eq!(count(&|s| matches!(s, Shape::Text(_))), 3, "¬, ¶ and #: {shapes:?}"); +} + /// Show Hidden Characters puts a dot over each space of a list paragraph and none over its /// bullet, which stands for no character. #[test] @@ -6890,7 +7047,7 @@ fn hidden_characters_mark_no_space_at_a_bullet() { fn show_hidden_characters_off_releases_the_text_nodes() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); - let text = json!({"x": 20, "y": 60, "text": "one two\nthree four"}); + let text = json!({"x": 20, "y": 60, "text": "one\ttwo\u{00A0}x\nthree\u{2028}four"}); let id = vectorcraft_doc::NodeId(app.session.execute("text.create", &text).unwrap()["id"].as_u64().unwrap()); let ctx = egui::Context::default(); app.run("type.hiddenCharacters", json!({})).unwrap(); @@ -8871,6 +9028,36 @@ fn escape_while_editing_in_isolation_returns_to_selection_tool_and_keeps_isolati assert!(app.session.active().unwrap().isolation.is_none(), "2nd Escape must exit isolation mode"); } +/// One Escape leaves isolation mode from a sublayer two levels down, where Exit Isolation Mode goes +/// up one layer at a time. +#[test] +fn escape_leaves_an_isolated_sublayer_in_one_step() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let top = app.session.active().unwrap().doc.layers[0].id; + let mid = app.session.execute("layer.newSublayer", &json!({"parent": top.0})).unwrap()["id"].as_u64().unwrap(); + let deep = app.session.execute("layer.newSublayer", &json!({"parent": mid})).unwrap()["id"].as_u64().unwrap(); + app.session.execute("layer.setCurrent", &json!({"id": deep})).unwrap(); + app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 20})).unwrap(); + app.session.execute("object.isolate", &json!({"id": deep})).unwrap(); + app.select_tool("selection"); + let ctx = egui::Context::default(); + let timed = |app: &mut VectorcraftApp, time: f64, events: Vec| { + let screen = egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)); + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), time: Some(time), events, ..Default::default() }, |ui| { + crate::shortcuts::handle(app, ui.ctx()); + show(app, ui) + }); + out.textures_delta.clear(); + }; + let esc = |pressed| egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; + timed(&mut app, 0.0, vec![]); + assert_eq!(app.session.active().unwrap().isolation, Some(vectorcraft_doc::NodeId(deep))); + timed(&mut app, 1.0, vec![esc(true), esc(false)]); + timed(&mut app, 1.1, vec![]); + assert_eq!(app.session.active().unwrap().isolation, None, "one Escape leaves every level"); +} + #[test] fn a_symbol_dropped_on_the_canvas_is_placed_there() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); @@ -8883,7 +9070,8 @@ fn a_symbol_dropped_on_the_canvas_is_placed_there() { let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); // Released over empty canvas: an instance centred there. let at = xf.to_screen(Point::new(250.0, 180.0)); - egui::DragAndDrop::set_payload(&ctx, widgets::PanelDrag::Symbol(name.clone())); + let document = app.session.active().unwrap().uid; + egui::DragAndDrop::set_payload(&ctx, widgets::PanelDrag::Symbol { document, name: name.clone() }); let up = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }; frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at), up]); let st = app.session.active().unwrap(); @@ -8894,6 +9082,106 @@ fn a_symbol_dropped_on_the_canvas_is_placed_there() { assert!((c - xf.to_doc(at)).hypot() < 1e-6, "{c:?}"); } +/// A new active document with a symbol `name` made from a `w` by `h` rectangle and no art; → its +/// uid. +fn document_with_symbol(app: &mut VectorcraftApp, name: &str, w: f64, h: f64) -> u64 { + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": w, "height": h})).unwrap(); + app.session.execute("symbol.new", &json!({"name": name})).unwrap(); + app.session.execute("edit.clear", &json!({})).unwrap(); + app.session.active().unwrap().uid +} + +/// The natural size the active document records for symbol `name`. +fn symbol_size(app: &VectorcraftApp, name: &str) -> (f64, f64) { + let st = app.session.active().unwrap(); + let size = st.doc.unknown.get(vectorcraft_doc::SYMBOL_SIZES).and_then(|m| m.get(name)).cloned().unwrap(); + (size[0].as_f64().unwrap(), size[1].as_f64().unwrap()) +} + +/// A symbol dragged from one document's Symbols panel and released on the canvas after another +/// document with a different symbol of the same name became active places the dragged symbol: it +/// is added under a free name, the other document's symbol is left as it was, the source document +/// is not changed, and one Undo takes back both the symbol and the instance. +#[test] +fn a_symbol_dragged_from_another_document_places_that_documents_symbol() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let source = document_with_symbol(&mut app, "Leaf", 40.0, 20.0); + let ctx = egui::Context::default(); + // While Leaf is held, a document with a Leaf of its own becomes active. + egui::DragAndDrop::set_payload(&ctx, widgets::PanelDrag::Symbol { document: source, name: "Leaf".into() }); + document_with_symbol(&mut app, "Leaf", 10.0, 70.0); + frame(&mut app, &ctx, vec![]); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let undo = app.session.active().unwrap().history.undo.len(); + let at = xf.to_screen(Point::new(250.0, 180.0)); + let up = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }; + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at), up]); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.symbols.iter().map(|s| s.name.as_str()).collect::>(), ["Leaf", "Leaf 2"]); + assert_eq!(st.history.undo.len(), undo + 1, "added and placed as one undo step"); + let placed = st.selection.objects.first().copied().expect("the placed instance is selected"); + let n = st.doc.node(placed).unwrap(); + assert!(matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if symbol == "Leaf 2"), "{:?}", n.kind); + let b = n.geometric_bounds().unwrap(); + assert!((b.width() - 40.0).abs() < 1e-6 && (b.height() - 20.0).abs() < 1e-6, "the dragged symbol's size: {b:?}"); + assert!((b.center() - xf.to_doc(at)).hypot() < 1e-6, "{b:?}"); + assert_eq!(symbol_size(&app, "Leaf"), (10.0, 70.0), "this document's Leaf is unchanged"); + app.run("edit.undo", json!({})).unwrap(); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.symbols.iter().map(|s| s.name.as_str()).collect::>(), ["Leaf"]); + assert!(st.doc.node(placed).is_none()); + assert!(app.session.set_active(0)); + assert_eq!(app.session.active().unwrap().uid, source); + assert_eq!(app.session.active().unwrap().doc.symbols.len(), 1, "the source document is unchanged"); + assert_eq!(symbol_size(&app, "Leaf"), (40.0, 20.0)); +} + +/// A symbol dragged from a document that was closed before the release places nothing, even +/// where the active document has a symbol of the same name. +#[test] +fn a_symbol_whose_document_closed_places_nothing() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let source = document_with_symbol(&mut app, "Leaf", 40.0, 20.0); + document_with_symbol(&mut app, "Leaf", 10.0, 70.0); + app.session.execute("file.close", &json!({"index": 0})).unwrap(); + assert!(app.session.documents().iter().all(|d| d.uid != source)); + let ctx = egui::Context::default(); + egui::DragAndDrop::set_payload(&ctx, widgets::PanelDrag::Symbol { document: source, name: "Leaf".into() }); + frame(&mut app, &ctx, vec![]); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let undo = app.session.active().unwrap().history.undo.len(); + let at = xf.to_screen(Point::new(250.0, 180.0)); + let up = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }; + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at), up]); + let st = app.session.active().unwrap(); + assert_eq!(st.history.undo.len(), undo, "no edit"); + assert!(st.selection.objects.is_empty(), "nothing placed"); +} + +/// The chip at the pointer shows the dragged symbol from the document it was dragged from after +/// another document, without a symbol of that name, became active. +#[test] +fn the_pointer_chip_of_a_dragged_symbol_shows_its_own_documents_symbol() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let source = document_with_symbol(&mut app, "Leaf", 40.0, 20.0); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let ctx = egui::Context::default(); + egui::DragAndDrop::set_payload(&ctx, widgets::PanelDrag::Symbol { document: source, name: "Leaf".into() }); + let screen_rect = Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0))); + let run = |events| { + let mut out = + ctx.run_ui(egui::RawInput { screen_rect, events, ..Default::default() }, |ui| crate::panels::swatches::drag_preview(&app, ui.ctx())); + out.textures_delta.clear(); + out + }; + // The chip's area is drawn from its second frame. + run(vec![egui::Event::PointerMoved(pos2(200.0, 150.0))]); + let out = run(vec![]); + let thumbnail = out.shapes.iter().any(|c| matches!(&c.shape, Shape::Mesh(m) if m.texture_id != egui::TextureId::default())); + assert!(thumbnail, "the chip draws the source document's thumbnail of Leaf"); +} + #[test] fn a_library_symbol_dropped_on_the_canvas_is_added_and_placed_there_in_one_step() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); diff --git a/crates/ui-egui/src/canvas/tool_overlays.rs b/crates/ui-egui/src/canvas/tool_overlays.rs index bc94f19e2b..5ccf5e4b9a 100644 --- a/crates/ui-egui/src/canvas/tool_overlays.rs +++ b/crates/ui-egui/src/canvas/tool_overlays.rs @@ -2,12 +2,14 @@ use super::grid::{clip_segment, pref_color}; use super::outline::{OVERLAY_MAX_ANCHORS, c32, stroke_path}; use super::{Color32, CornerRadius, Node, NodeKind, Overlay, Point, Pos2, Rect, Shape, Stroke, StrokeKind, Tokens, VectorcraftApp, Xf, pos2, vec2}; -/// Type → Show Hidden Characters: spaces as dots, ¶ at paragraph ends, # at the end of a story. -/// The marks of each text object are kept from one frame to the next ([`HiddenChars`]). +/// Type → Show Hidden Characters: the characters that print no ink, and the ends of paragraphs, +/// lines and stories ([`HiddenMarks`]). The marks of each text object are kept from one frame to +/// the next ([`HiddenChars`]). pub(super) fn hidden_chars_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: &Xf) { let Some(st) = app.session.active() else { return }; let clip = p.clip_rect(); let color = Color32::from_rgb(0x4f, 0x9d, 0xff); + let stroke = Stroke::new(1.0, color); let font = egui::FontId::proportional(((10.0 * xf.zoom) as f32).clamp(7.0, 18.0)); let kept = &mut app.canvas.hidden_chars; // `last` holds the marks of the last frame. The marks of the objects this frame doesn't draw @@ -43,13 +45,62 @@ pub(super) fn hidden_chars_overlay(app: &mut VectorcraftApp, p: &egui::Painter, for &at in &marks.spaces { p.circle_filled(xf.to_screen(at), 1.2, color); } - for &(at, glyph) in &marks.ends { - p.text(xf.to_screen(at), egui::Align2::LEFT_BOTTOM, glyph, font.clone(), color); + for &(mark, a, b) in &marks.chars { + draw_char_mark(p, mark, xf.to_screen(a), xf.to_screen(b), stroke, &font); + } + for &(at, along, up) in &marks.breaks { + let at = xf.to_screen(at); + let u = unit_or(xf.to_screen(along) - at, vec2(1.0, 0.0)); + let n = unit_or(xf.to_screen(up) - at, vec2(0.0, -1.0)); + // A bent arrow: down from above the line's end, then back along the line. + let corner = at + u * 7.0 + n * 2.0; + let tip = at + u + n * 2.0; + p.add(Shape::line(vec![at + u * 7.0 + n * 8.0, corner, tip], stroke)); + p.add(Shape::line(vec![tip + u * 3.0 + n * 3.0, tip, tip + u * 3.0 - n * 3.0], stroke)); + } + for &(at, glyph, align) in &marks.ends { + p.text(xf.to_screen(at), align, glyph, font.clone(), color); } kept.marks.insert(n.id, (n.clone(), marks)); }); } +/// `v` scaled to length 1, or `or` when `v` has no length. +fn unit_or(v: egui::Vec2, or: egui::Vec2) -> egui::Vec2 { + let len = v.length(); + if len > 1e-3 { v / len } else { or } +} + +/// Draws the mark of one character on screen. `a` and `b` are the start and end of the +/// character's advance, in the direction the text reads, above its baseline. +fn draw_char_mark(p: &egui::Painter, mark: CharMark, a: Pos2, b: Pos2, stroke: Stroke, font: &egui::FontId) { + let u = unit_or(b - a, vec2(1.0, 0.0)); + let mid = a + (b - a) * 0.5; + match mark { + CharMark::Tab => { + // An arrow across the tab's advance, at least 6 px long. + let end = if (b - a).length() < 6.0 { a + u * 6.0 } else { b }; + let n = vec2(u.y, -u.x); + p.line_segment([a, end], stroke); + p.add(Shape::line(vec![end - u * 3.0 + n * 2.5, end, end - u * 3.0 - n * 2.5], stroke)); + } + CharMark::NoBreakSpace => { + p.circle_stroke(mid, 2.0, stroke); + } + CharMark::NarrowNoBreakSpace => { + p.circle_stroke(mid, 1.4, stroke); + } + CharMark::FixedSpace => { + // A short tick across the baseline's direction. + let n = vec2(u.y, -u.x) * 2.5; + p.line_segment([mid - n, mid + n], stroke); + } + CharMark::DiscretionaryHyphen => { + p.text(mid, egui::Align2::CENTER_BOTTOM, "¬", font.clone(), stroke.color); + } + } +} + /// The Show Hidden Characters marks of the text objects drawn in the last frame /// ([`crate::CanvasCache::hidden_chars`]). Each is kept with the object it was laid out from: an /// edited object is a new `Arc` and is laid out again, and all type is laid out again when the @@ -63,12 +114,51 @@ pub struct HiddenChars { pub(super) marks: std::collections::HashMap, std::sync::Arc)>, } -/// One text object's marks in document space: a dot over each space, and ¶ or # after the lines -/// that end a paragraph or the story. Type on a path has none. +/// The mark Show Hidden Characters draws over a character other than a plain space. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum CharMark { + /// A tab (U+0009): an arrow across its advance, to the tab stop. + Tab, + /// A nonbreaking space (U+00A0): a ring. + NoBreakSpace, + /// A narrow nonbreaking space (U+202F): a smaller ring. + NarrowNoBreakSpace, + /// The spaces of a set width (U+2000 to U+200A, U+205F, U+3000): a short tick. + FixedSpace, + /// A discretionary hyphen (U+00AD): ¬, where the word can break. + DiscretionaryHyphen, +} + +impl CharMark { + /// The mark of `c`, `None` for a character with no mark of its own. + pub(super) fn of(c: char) -> Option { + Some(match c { + '\t' => Self::Tab, + '\u{00A0}' => Self::NoBreakSpace, + '\u{202F}' => Self::NarrowNoBreakSpace, + '\u{2000}'..='\u{200A}' | '\u{205F}' | '\u{3000}' => Self::FixedSpace, + '\u{00AD}' => Self::DiscretionaryHyphen, + _ => return None, + }) + } +} + +/// One text object's marks in document space: a dot over each space, a [`CharMark`] over each +/// tab, nonbreaking space, space of a set width and discretionary hyphen, a bent arrow after +/// each line a forced line break (U+2028) ends, and ¶ or # after the lines that end a paragraph +/// or the story. Type on a path has the marks over characters, ¶ and the bent arrow at its +/// breaks, and # after its last character when all of its text is drawn. #[derive(Default)] pub(super) struct HiddenMarks { pub(super) spaces: Vec, - ends: Vec<(Point, &'static str)>, + /// Each mark over a character, with the start and end of the character's advance 3 pt above + /// its baseline, in the direction the text reads. + pub(super) chars: Vec<(CharMark, Point, Point)>, + /// Each forced line break: where its arrow starts, a point 1 pt further along the line and a + /// point 1 pt above the baseline from there. + pub(super) breaks: Vec<(Point, Point, Point)>, + /// ¶ and #, where they are drawn and how the text is aligned to that point. + pub(super) ends: Vec<(Point, &'static str, egui::Align2)>, } impl HiddenMarks { @@ -76,29 +166,71 @@ impl HiddenMarks { pub(super) fn of(tx: &vectorcraft_doc::TextObject) -> Self { let mut marks = Self::default(); let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), tx); - if lay.on_path { - return marks; - } let text = tx.plain_text(); let to = |q: Point| tx.xf * q; - // A list marker's glyphs (length 0) stand for no character. - for g in lay.glyphs.iter().filter(|g| g.len > 0) { - if text.get(g.byte..).is_some_and(|s| s.starts_with(' ')) { - marks.spaces.push(to(Point::new(g.origin.x + g.advance / 2.0, g.origin.y - 3.0))); + // The direction a glyph's baseline runs, and up from it (y points down). + let along = |angle: f64| vectorcraft_geom::Vec2::new(angle.cos(), angle.sin()); + let up = |angle: f64| { + let d = along(angle); + vectorcraft_geom::Vec2::new(d.y, -d.x) + }; + // A list marker's glyphs and a hyphen the layout adds at a break (length 0) stand for no + // character. Glyphs before the start of an open path draw nothing. A character drawn with + // several glyphs gets one mark. + let mut marked = None; + for g in lay.glyphs.iter().filter(|g| g.len > 0 && !g.off_path) { + let Some(c) = text.get(g.byte..).and_then(|s| s.chars().next()) else { continue }; + if marked == Some(g.byte) { + continue; } + let (d, n) = (along(g.angle), up(g.angle)); + let start = g.origin + n * 3.0; + let end = start + d * g.advance; + if c == ' ' { + marks.spaces.push(to(start + d * (g.advance / 2.0))); + } else if let Some(mark) = CharMark::of(c) { + let (a, b) = if g.rtl { (end, start) } else { (start, end) }; + marks.chars.push((mark, to(a), to(b))); + } else if lay.on_path && (c == '\n' || c == '\u{2028}') { + // Type on a path is one line: its breaks are marked where their glyphs are. + if c == '\n' { + marks.ends.push((to(g.origin), "¶", egui::Align2::LEFT_BOTTOM)); + } else { + marks.breaks.push((to(g.origin), to(g.origin + d), to(g.origin + d + n))); + } + } else { + continue; + } + marked = Some(g.byte); } + if lay.on_path { + // # after the last character, when the path holds all of the text. + let last = lay.glyphs.iter().filter(|g| g.len > 0 && !g.off_path).max_by_key(|g| g.byte + g.len); + if let Some(g) = last.filter(|g| g.byte + g.len >= text.len() && !lay.overflow) { + let d = along(g.angle); + let at = if g.rtl { g.origin - d } else { g.origin + d * (g.advance + 1.0) }; + marks.ends.push((to(at), "#", egui::Align2::LEFT_BOTTOM)); + } + return marks; + } + // Lines are in line space: `physical_point` turns them into columns in vertical type. + let at = |x: f64, y: f64| to(lay.physical_point(Point::new(x, y))); for (i, line) in lay.lines.iter().enumerate() { let last = i + 1 == lay.lines.len(); - let breaks = text.get(line.end..).is_some_and(|s| s.starts_with('\n')); - let (glyph, at) = if last && line.end >= text.len() { - ("#", true) - } else if breaks { - ("¶", true) - } else { - ("", false) + // A right-to-left line ends at its left edge. + let (x, dx) = if line.rtl { (line.x0 - 1.0, -1.0) } else { (line.x1 + 1.0, 1.0) }; + let align = match (lay.vertical, line.rtl) { + (true, _) => egui::Align2::CENTER_TOP, + (false, true) => egui::Align2::RIGHT_BOTTOM, + (false, false) => egui::Align2::LEFT_BOTTOM, }; - if at { - marks.ends.push((to(Point::new(line.x1 + 1.0, line.baseline)), glyph)); + let soft = text.get(line.start..line.end).is_some_and(|s| s.ends_with('\u{2028}')); + if last && line.end >= text.len() { + marks.ends.push((at(x, line.baseline), "#", align)); + } else if soft { + marks.breaks.push((at(x, line.baseline), at(x + dx, line.baseline), at(x, line.baseline - 1.0))); + } else if text.get(line.end..).is_some_and(|s| s.starts_with('\n')) { + marks.ends.push((at(x, line.baseline), "¶", align)); } } marks diff --git a/crates/ui-egui/src/canvas/view.rs b/crates/ui-egui/src/canvas/view.rs index 4443f12997..e0e5cc9f75 100644 --- a/crates/ui-egui/src/canvas/view.rs +++ b/crates/ui-egui/src/canvas/view.rs @@ -94,7 +94,7 @@ pub(super) const HOLD_DELAY: f32 = 0.3; /// …and how fast it zooms then (as `exp(seconds × HOLD_ZOOM)`: twice as close each second). pub(super) const HOLD_ZOOM: f64 = std::f64::consts::LN_2; -/// Performance › Animated Zoom, which needs GPU Performance as in Illustrator: the Zoom tool zooms +/// Performance › Animated Zoom, which needs GPU Performance: the Zoom tool zooms /// as it is dragged sideways or held, instead of zooming to the area dragged across, and a wheel /// notch's zoom glides in ([`wheel`]). pub(crate) fn animated_zoom(p: &vectorcraft_engine::Prefs) -> bool { diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index dc9f9fa848..43b9f5b69c 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -36,7 +36,7 @@ use tabs::{CLOSE_BEFORE_TITLE, first_tab_shown, tab_drop, tab_groups, tab_title} pub use tabs::{doc_tabs, isolation_bar, step_document}; pub(crate) use tabs::{document_window_title, show_document, window_tab}; -/// The application bar's height, in points (compact, as in PhotoCraft). +/// The application bar's height, in points (compact). pub const APP_BAR_HEIGHT: f32 = 32.0; /// The brand mark's side. const MARK: f32 = 18.0; @@ -110,7 +110,7 @@ pub fn app_bar(app: &mut VectorcraftApp, ui: &mut Ui) { gap: ui.spacing().item_spacing.x, community: crate::community::discord_width(ui, false), }); - let (switcher, ws_w, learn, discord) = (fit.switcher, fit.switcher_w, fit.learn, fit.community); + let (switcher, ws_w, arrange, learn, discord) = (fit.switcher, fit.switcher_w, fit.arrange, fit.learn, fit.community); let mut rui = ui.new_child(egui::UiBuilder::new().max_rect(right).layout(egui::Layout::right_to_left(egui::Align::Center))); let ui = &mut rui; // Workspace switcher: shows the current workspace, opens Window → Workspace. @@ -129,6 +129,11 @@ pub fn app_bar(app: &mut VectorcraftApp, ui: &mut Ui) { } ui.add_space(8.0); } + // Arrange Documents: Consolidate All Windows and the Tile layouts. + if arrange { + let resp = widgets::icon_button(ui, "layout-grid", tl!("Arrange Documents"), app.ui.tiled, BAR_ICON); + egui::Popup::menu(&resp).show(|ui| arrange_documents_popup(app, ui)); + } // Search → command palette (its shortcut opens it too). let with_shortcut = |text: &str| match &field.shortcut { Some(sc) => format!("{text} ({sc})"), @@ -181,7 +186,34 @@ pub fn app_bar(app: &mut VectorcraftApp, ui: &mut Ui) { } } -/// The side of the app bar's square icon buttons (the search icon, Explore tutorials). +/// The Arrange Documents menu ([`menus::arrange_documents_items`]): each item as the Window menu +/// shows it, grayed out while its command can't run, the Tile layout the panes show checked. +fn arrange_documents_popup(app: &mut VectorcraftApp, ui: &mut Ui) { + ui.set_min_width(200.0); + let mut clicked = None; + for it in menus::arrange_documents_items() { + match it { + menus::Item::Sep => { + ui.separator(); + } + menus::Item::Cmd(label, id, p) => { + let Some((enabled, checked)) = menus::shown_state(app, id, &p) else { continue }; + let label = crate::i18n::t_id(id, label); + let text = if checked == Some(true) { format!("✓ {label}") } else { format!(" {label}") }; + if ui.add_enabled(enabled, egui::Button::new(text).min_size(vec2(200.0, 0.0))).clicked() { + clicked = Some((id, if p.is_null() { json!({}) } else { p })); + ui.close(); + } + } + _ => {} + } + } + if let Some((id, p)) = clicked { + menus::invoke(app, id, p); + } +} + +/// The side of the app bar's square icon buttons (the search icon, Arrange Documents, Explore tutorials). const BAR_ICON: f32 = 28.0; /// The narrowest the workspace switcher gets. const MIN_SWITCHER: f32 = 64.0; @@ -225,6 +257,8 @@ struct RightGroup { switcher_w: f32, /// How the search shows. search: Search, + /// Whether Arrange Documents shows. + arrange: bool, /// Whether Explore tutorials shows. learn: bool, /// Whether the community button shows. @@ -232,8 +266,8 @@ struct RightGroup { } /// The right-hand group for the room it has. As the room runs short, the community button goes first -/// (it is also under Help), then Explore tutorials (also Window › Learn), then the search field becomes the -/// search icon, then the workspace switcher narrows to [`MIN_SWITCHER`], then the icon goes. In Safe +/// (it is also under Help), then Explore tutorials (also Window › Learn), then Arrange Documents (also Window › +/// Arrange), then the search field becomes the search icon, then the workspace switcher narrows to [`MIN_SWITCHER`], then the icon goes. In Safe /// Mode the label's width is taken first, and the switcher (also under Window › Workspace) goes when /// a minimal one does not fit. fn fit_right_group(w: &RightWidths) -> RightGroup { @@ -254,10 +288,12 @@ fn fit_right_group(w: &RightWidths) -> RightGroup { Search::Hidden => 0.0, }; let switcher_w = w.switcher.min(room - 8.0 - search_w).max(MIN_SWITCHER); - let learn_end = switcher_w + 8.0 + search_w + w.gap + w.icon; - let learn = field && room >= learn_end; + let arrange_end = switcher_w + 8.0 + search_w + w.gap + w.icon; + let arrange = field && room >= arrange_end; + let learn_end = arrange_end + w.gap + w.icon; + let learn = arrange && room >= learn_end; let community = learn && room >= learn_end + 10.0 + w.gap + w.community; - RightGroup { switcher, switcher_w, search, learn, community } + RightGroup { switcher, switcher_w, search, arrange, learn, community } } /// The app bar's search field: a button drawn as a field. The command palette's popup holds the diff --git a/crates/ui-egui/src/chrome/control_bar.rs b/crates/ui-egui/src/chrome/control_bar.rs index 71b737dbfc..2c7ae8ed20 100644 --- a/crates/ui-egui/src/chrome/control_bar.rs +++ b/crates/ui-egui/src/chrome/control_bar.rs @@ -188,9 +188,9 @@ const INLINE_FIELD_WIDTH: f32 = 80.0; /// The keys and labels of the Control bar's inline X/Y/W/H fields, in their order. const INLINE_FIELDS: [(&str, &str); 4] = [("x", "X:"), ("y", "Y:"), ("width", "W:"), ("height", "H:")]; -/// The label of an inline X/Y/W/H field. +/// The label of an inline X/Y/W/H field, underlined: a click on it opens the Transform panel. fn inline_label(t: &Tokens, lbl: &str) -> egui::RichText { - egui::RichText::new(tl!(lbl)).size(12.0).color(t.text_dim) + egui::RichText::new(tl!(lbl)).size(12.0).color(t.text).underline() } /// The room the Control bar's inline X/Y/W/H fields take: their labels as drawn in the current @@ -203,6 +203,53 @@ fn inline_transform_width(ui: &Ui, t: &Tokens) -> f32 { labels + fields + crate::panels::transform::CONSTRAIN_LINK_SIZE + ui.spacing().item_spacing.x * items as f32 } +/// The Control bar's inline X/Y/W/H fields for the selection's box `b`, rotated with rotated +/// objects: X/Y are its reference point on the page (or a symbol instance's registration point), +/// shared with the Transform panel, and W/H its own sides. Edits keep or move that point, and the +/// Transform panel's menu choice of objects, patterns or both applies to them. +fn inline_transform_fields(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, units: vectorcraft_doc::Unit, b: &vectorcraft_doc::OrientedBox) { + let reference = crate::panels::transform::panel_reference(app, ui, b); + let (refi, rp) = (reference.index, reference.point); + let origin = app.ruler_origin(); + let link = crate::panels::transform::proportional(app, ui); + let copy = crate::panels::transform::alt_enter_copies(app, ui); + let values = [(rp.x, origin.x), (rp.y, origin.y), (b.rect.width(), 0.0), (b.rect.height(), 0.0)]; + // The W/H link sits between W and H, but is made after H so Tab goes from W + // straight to H and finds the link after it. + let mut link_room = None; + let mut labels = Vec::with_capacity(INLINE_FIELDS.len()); + for ((k, lbl), (v, offset)) in INLINE_FIELDS.into_iter().zip(values) { + if k == "height" { + link_room = Some(crate::panels::transform::constrain_link_room(ui)); + } + // A click on the label opens the Transform panel, as the Transform link does; a drag scrubs. + let label = widgets::field_panel_label(ui, inline_label(t, lbl)).on_hover_text(tl!("Transform options")); + let (id, shown) = (("cb", k), Some(v - offset)); + let set = if matches!(k, "width" | "height") { + widgets::size_field(ui, id, shown, units, INLINE_FIELD_WIDTH) + } else { + widgets::num_field(ui, id, shown, units, INLINE_FIELD_WIDTH) + }; + labels.push(label); + if let Some(nv) = set { + let params = match k { + "x" => json!({"x": reference.bounds_xy(nv + offset, 0.0).0, "reference": refi, "copy": copy}), + "y" => json!({"y": reference.bounds_xy(0.0, nv + offset).1, "reference": refi, "copy": copy}), + _ => json!({k: nv, "reference": refi, "proportional": link, "copy": copy}), + }; + crate::panels::transform::run_transform(app, "object.setBounds", params); + } + } + if let Some(room) = link_room { + let id = ui.scope_id().with("cb-constrain-link"); + crate::panels::transform::constrain_link_at(app, ui, ui.interact(room, id, Sense::click())); + } + // After the fields, which each take the label before them as their own. + for label in &labels { + crate::panels::transform::popover(app, label); + } +} + /// The size of the Control bar's Align, Distribute and area type vertical alignment buttons, and /// the height of its Align To menu. const BUTTON: f32 = 24.0; @@ -710,7 +757,7 @@ fn fill_and_stroke(app: &mut VectorcraftApp, ui: &mut Ui, reserve: f32) { stroke_panel::weight_field(app, ui, "cb-stroke", weight, WEIGHT_FIELD_WIDTH); if ui.available_width() < row_width(ui, &[stroke_panel::PROFILE_DROPDOWN_WIDTH]) + reserve { left_out(ui); - } else if let Some(id) = stroke_panel::profile_dropdown(app, ui, shown_stroke.as_ref().and_then(|s| s.profile.as_ref())) { + } else if let Some(id) = stroke_panel::profile_dropdown(app, ui, shown_stroke.as_ref()) { app.run("stroke.set", json!({"profile": id})).ok(); } } else { @@ -886,7 +933,7 @@ fn gripper(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, bar: egui::Rect, d } } -/// The Control bar (Window → Control), context-sensitive like Illustrator's, docked to the top or +/// The Control bar (Window → Control), context-sensitive, docked to the top or /// the bottom of the window, or floating over the window below the menu bar, where it takes no room /// from the canvas. A floating bar is [`FLOAT_WIDTH`] wide, or as wide as the window when that is /// narrower, and is kept inside the window when the window shrinks. @@ -1036,38 +1083,11 @@ fn contents(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, bar: egui::Rect, return; } crate::panels::transform::link(app, ui); - // The bounding box, rotated with rotated objects: its centre and its own sides. let selection_box = app.selection_box(); if selection_box.is_some() && ui.available_width() < inline_transform_width(ui, t) { left_out(ui); } else if let Some(b) = selection_box { - let c = b.center(); - let origin = app.ruler_origin(); - let link = crate::panels::transform::proportional(app, ui); - let copy = crate::panels::transform::alt_enter_copies(app, ui); - let values = [(c.x, origin.x), (c.y, origin.y), (b.rect.width(), 0.0), (b.rect.height(), 0.0)]; - // The W/H link sits between W and H, but is made after H so Tab goes from W - // straight to H and finds the link after it. - let mut link_room = None; - for ((k, lbl), (v, offset)) in INLINE_FIELDS.into_iter().zip(values) { - if k == "height" { - link_room = Some(crate::panels::transform::constrain_link_room(ui)); - } - widgets::field_label(ui, inline_label(t, lbl)); - let (id, shown) = (("cb", k), Some(v - offset)); - let set = if matches!(k, "width" | "height") { - widgets::size_field(ui, id, shown, units, INLINE_FIELD_WIDTH) - } else { - widgets::num_field(ui, id, shown, units, INLINE_FIELD_WIDTH) - }; - if let Some(nv) = set { - app.run("object.setBounds", json!({k: nv + offset, "reference": 4, "proportional": link, "copy": copy})).ok(); - } - } - if let Some(room) = link_room { - let id = ui.scope_id().with("cb-constrain-link"); - crate::panels::transform::constrain_link_at(app, ui, ui.interact(room, id, Sense::click())); - } + inline_transform_fields(app, ui, t, units, &b); } // Select Similar Objects comes last: it takes only the room every control ahead of it left. trailing_select_similar(app, ui); diff --git a/crates/ui-egui/src/chrome/tabs.rs b/crates/ui-egui/src/chrome/tabs.rs index 9278b8baf3..f88372e75b 100644 --- a/crates/ui-egui/src/chrome/tabs.rs +++ b/crates/ui-egui/src/chrome/tabs.rs @@ -364,8 +364,10 @@ pub fn isolation_bar(app: &mut VectorcraftApp, ui: &mut Ui, area: egui::Rect) { ui.painter().rect_filled(crumb_rect, 3.0, t.hover); } if resp.clicked() { - if crumb.is_layer { - nav_cmd = Some(("object.exitIsolation", json!({}))); + // The top-level layer's crumb leaves isolation mode; a sublayer's or a group's + // crumb isolates that level. + if crumb.is_layer && i == 0 { + nav_cmd = Some(("object.exitIsolation", json!({ "all": true }))); } else if let Some(target) = crumb.id { nav_cmd = Some(("object.isolate", json!({ "id": target.0 }))); } @@ -401,7 +403,8 @@ pub fn isolation_bar(app: &mut VectorcraftApp, ui: &mut Ui, area: egui::Rect) { if bresp.clicked() { pattern_cmd = pattern_cmd.or(pattern_edit.as_ref().map(|_| "object.pattern.done")); if pattern_cmd.is_none() { - // Up one level: the isolated object's parent, or out of isolation mode from a layer. + // Up one level: the isolated object's parent group, or `object.exitIsolation`, which + // goes from an isolated sublayer to its parent layer and otherwise leaves isolation mode. nav_cmd = Some(match ancestry.iter().rev().nth(1).filter(|p| st.doc.node(**p).is_some_and(|n| !n.is_layer())) { Some(parent) => ("object.isolate", json!({ "id": parent.0 })), None => ("object.exitIsolation", json!({})), diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 61c67e6a70..09d31f1a5f 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -172,11 +172,11 @@ fn right_stage(g: &super::RightGroup) -> String { w if w > super::MIN_SWITCHER => "narrower switcher", _ => "minimal switcher", }; - format!("community {}, learn {}, {:?}, {switcher}", g.community, g.learn, g.search) + format!("community {}, learn {}, arrange {}, {:?}, {switcher}", g.community, g.learn, g.arrange, g.search) } -/// As the app bar's room runs short, the community button goes first, then Explore tutorials, then the search -/// field becomes the icon, then the workspace switcher narrows to its minimum, then the icon goes. +/// As the app bar's room runs short, the community button goes first, then Explore tutorials, then Arrange +/// Documents, then the search field becomes the icon, then the workspace switcher narrows to its minimum, then the icon goes. /// Whatever shows fits in the room, down to the minimal switcher alone. #[test] fn the_app_bar_gives_up_its_right_hand_controls_in_order() { @@ -193,31 +193,33 @@ fn the_app_bar_gives_up_its_right_hand_controls_in_order() { super::Search::Icon => w.gap + w.icon, super::Search::Hidden => 0.0, }; + let arrange = if g.arrange { w.gap + w.icon } else { 0.0 }; let learn = if g.learn { w.gap + w.icon } else { 0.0 }; let community = if g.community { 10.0 + w.gap + w.community } else { 0.0 }; - let used = g.switcher_w + 8.0 + search + learn + community; + let used = g.switcher_w + 8.0 + search + arrange + learn + community; assert!(used <= room || g.switcher_w == super::MIN_SWITCHER && g.search == super::Search::Hidden, "{room}: {g:?} needs {used}"); } assert_eq!( stages, [ - "community true, learn true, Field, full switcher", - "community false, learn true, Field, full switcher", - "community false, learn false, Field, full switcher", - "community false, learn false, Icon, full switcher", - "community false, learn false, Icon, narrower switcher", - "community false, learn false, Icon, minimal switcher", + "community true, learn true, arrange true, Field, full switcher", + "community false, learn true, arrange true, Field, full switcher", + "community false, learn false, arrange true, Field, full switcher", + "community false, learn false, arrange false, Field, full switcher", + "community false, learn false, arrange false, Icon, full switcher", + "community false, learn false, arrange false, Icon, narrower switcher", + "community false, learn false, arrange false, Icon, minimal switcher", // Once the icon has gone, the switcher takes the room it leaves. - "community false, learn false, Hidden, narrower switcher", - "community false, learn false, Hidden, minimal switcher", + "community false, learn false, arrange false, Hidden, narrower switcher", + "community false, learn false, arrange false, Hidden, minimal switcher", ] ); // In Safe Mode the label's width is taken first (not counted in `room`), and the switcher goes // when a minimal one does not fit. let safe = |room| right_stage(&super::fit_right_group(&right_widths(room, true))); - assert_eq!(safe(700.0), "community true, learn true, Field, full switcher"); - assert_eq!(safe(72.0), "community false, learn false, Hidden, minimal switcher"); - assert_eq!(safe(71.0), "community false, learn false, Hidden, no switcher"); + assert_eq!(safe(700.0), "community true, learn true, arrange true, Field, full switcher"); + assert_eq!(safe(72.0), "community false, learn false, arrange false, Hidden, minimal switcher"); + assert_eq!(safe(71.0), "community false, learn false, arrange false, Hidden, no switcher"); } /// What screen readers call the app bar's search field, and the icon it becomes, before the shortcut. @@ -1914,6 +1916,45 @@ fn isolation_bar_navigation_and_back_button_steps_up() { assert_eq!(app.session.active().unwrap().isolation, Some(NodeId(g2))); } +/// With a sublayer isolated, the back arrow goes up one layer at a time and then leaves isolation +/// mode. The top-level layer's crumb leaves isolation mode from any depth, and a parent sublayer's +/// crumb isolates that sublayer. +#[test] +fn isolation_bar_back_button_steps_up_through_sublayers() { + use vectorcraft_doc::NodeId; + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + let top = app.session.active().unwrap().doc.layers[0].id; + let mid = NodeId(app.run("layer.newSublayer", json!({"parent": top.0, "name": "Sublayer B"})).unwrap()["id"].as_u64().unwrap()); + let deep = NodeId(app.run("layer.newSublayer", json!({"parent": mid.0, "name": "Sublayer C"})).unwrap()["id"].as_u64().unwrap()); + app.run("layer.setCurrent", json!({"id": deep.0})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap(); + let ctx = isolation_bar_context(); + let click = |app: &mut crate::VectorcraftApp, pos: egui::Pos2| isolation_bar_gesture(app, &ctx, pos, pos); + let back = egui::pos2(15.0, 12.0); + let isolation = |app: &crate::VectorcraftApp| app.session.active().unwrap().isolation; + + app.run("object.isolate", json!({"id": deep.0})).unwrap(); + let steps = app.session.doc().unwrap().history.undo.len(); + click(&mut app, back); + assert_eq!(isolation(&app), Some(mid), "back from the deepest sublayer"); + click(&mut app, back); + assert_eq!(isolation(&app), Some(top), "back from the middle sublayer"); + click(&mut app, back); + assert_eq!(isolation(&app), None, "back from the top-level layer"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), steps, "no undo step"); + + // "Layer 1" is the first crumb, at x 30 to about 75. + app.run("object.isolate", json!({"id": deep.0})).unwrap(); + click(&mut app, egui::pos2(40.0, 12.0)); + assert_eq!(isolation(&app), None, "the top-level layer's crumb"); + + // "Sublayer B" is the second crumb, from about x 95. + app.run("object.isolate", json!({"id": deep.0})).unwrap(); + click(&mut app, egui::pos2(115.0, 12.0)); + assert_eq!(isolation(&app), Some(mid), "the parent sublayer's crumb"); +} + /// Headless frames of the isolation bar over a 1200 × 700 canvas for one pointer gesture: a press /// at `from`, a move to `to` and a release there. `from == to` is a click. fn isolation_bar_gesture(app: &mut crate::VectorcraftApp, ctx: &egui::Context, from: egui::Pos2, to: egui::Pos2) { @@ -4651,3 +4692,59 @@ fn the_control_bar_shows_the_inline_transform_fields_only_when_they_fit() { assert!(groups_seen.iter().all(|s| *s), "{count} objects: a wide bar shows every group: {groups_seen:?}"); } } + +/// A click on the Control bar's X:, Y:, W: or H: label opens the Transform panel in a popover under +/// it, as the Transform link does, and a second click closes it. The click leaves the selection and +/// its bounds as they were, and no field takes the keyboard. A drag on W: still scrubs the width and +/// opens nothing. +#[test] +fn the_control_bars_x_y_w_and_h_labels_open_the_transform_panel() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 40, "height": 30})).unwrap()["id"].clone(); + app.run("select.set", json!({ "ids": [id] })).unwrap(); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(2000.0, 600.0)); + let frame = |app: &mut crate::VectorcraftApp, events| control_bar_frame_in(app, &ctx, screen, events); + let state = |app: &crate::VectorcraftApp| { + let st = app.session.active().unwrap(); + let b = st.doc.bounds_of(&st.selection.objects, false).unwrap(); + (st.selection.objects.len(), [b.x0, b.y0, b.x1, b.y1]) + }; + // The label's own node: a label whose text is `name` (the field it names is named the same). + let label = |nodes: &[egui::accesskit::Node], name: &str| { + let n = nodes.iter().find(|n| n.role() == egui::accesskit::Role::Label && n.value() == Some(name)); + let b = n.and_then(|n| n.bounds()).unwrap_or_else(|| panic!("no {name} label")); + egui::pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32) + }; + // The Transform panel's Rotate field is not on the bar itself. + let open = |nodes: &[egui::accesskit::Node]| nodes.iter().any(|n| n.label() == Some("Rotate")); + let before = state(&app); + frame(&mut app, vec![]); + for name in ["X:", "Y:", "W:", "H:"] { + let nodes = frame(&mut app, vec![]); + assert!(!open(&nodes), "{name}: the Transform panel is closed at first"); + let at = label(&nodes, name); + frame(&mut app, vec![egui::Event::PointerMoved(at), press_at(at, true)]); + frame(&mut app, vec![press_at(at, false)]); + assert!(open(&frame(&mut app, vec![])), "{name}: a click on the label opens the Transform panel"); + assert_eq!(ctx.memory(|m| m.focused()), None, "{name}: no field took the keyboard"); + assert_eq!(state(&app), before, "{name}: the selection and its bounds stay"); + frame(&mut app, vec![egui::Event::PointerMoved(at), press_at(at, true)]); + frame(&mut app, vec![press_at(at, false)]); + assert!(!open(&frame(&mut app, vec![])), "{name}: a second click closes it"); + } + let at = label(&frame(&mut app, vec![]), "W:"); + frame(&mut app, vec![egui::Event::PointerMoved(at), press_at(at, true)]); + for i in 1..=4 { + frame(&mut app, vec![egui::Event::PointerMoved(at + egui::vec2(5.0 * i as f32, 0.0))]); + } + frame(&mut app, vec![press_at(at + egui::vec2(20.0, 0.0), false)]); + let nodes = frame(&mut app, vec![]); + assert!(!open(&nodes), "a drag on W: opens nothing"); + let (_, [x0, _, x1, _]) = state(&app); + assert!(x1 - x0 > before.1[2] - before.1[0], "a drag on W: scrubs the width: {:?} to {:?}", before.1, [x0, x1]); +} diff --git a/crates/ui-egui/src/community.rs b/crates/ui-egui/src/community.rs index 034807b8b7..97f7dffdba 100644 --- a/crates/ui-egui/src/community.rs +++ b/crates/ui-egui/src/community.rs @@ -33,7 +33,7 @@ pub fn discord_button(app: &mut VectorcraftApp, ui: &mut Ui, large: bool) -> egu let ir = egui::Rect::from_center_size(r.left_center() + vec2(h * 0.35 + icon / 2.0, 0.0), vec2(icon, icon)); if large { // The theme's accent, as the primary buttons use it, so the call to action matches the - // rest of the window (and PhotoCraft's, #4684); Discord's colour stays on the app-bar icon. + // rest of the window (#4684); Discord's colour stays on the app-bar icon. let t = Tokens::get(ui.ctx()); let fill = if resp.hovered() { t.accent } else { t.accent_strong }; ui.painter().rect_filled(r, CornerRadius::same((h / 2.0) as u8), fill); @@ -77,7 +77,7 @@ pub fn links(app: &mut VectorcraftApp, ui: &mut Ui) { links_in(app, ui, false); } -/// [`links`] for a centred column (the Home screen's, as PhotoCraft's, #4684): the Discord button +/// [`links`] for a centred column (the Home screen's, #4684): the Discord button /// and the links, each in the middle. pub fn links_centered(app: &mut VectorcraftApp, ui: &mut Ui) { links_in(app, ui, true); diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index a2c29fadc4..15f456d51f 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -240,6 +240,7 @@ fn wrap(r: Result) -> Outcome { pub fn all_commands(app: &VectorcraftApp) -> Value { let mut v: Vec = app.session.commands().into_iter().map(|c| serde_json::to_value(c).unwrap_or_default()).collect(); for (id, label, sc, params) in crate::menus::UI_COMMANDS { + let sc = crate::shortcut_editor::ui_command_default(id, sc, crate::keymap::platform()); v.push(json!({"id": id, "label": label, "shortcut": sc, "params": params, "enabled": crate::menus::enabled(app, id), "ui": true})); } Value::Array(v) @@ -274,11 +275,12 @@ pub fn inspect(app: &VectorcraftApp, ctx: &egui::Context) -> Value { // The display profile the canvas is drawn through, or why none (Preferences › // Performance › Use Monitor Profile for Canvas). "displayProfile": app.display_profile.status(app.session.prefs.monitor_profile_display), - // Window › Arrange › Tile (not saved, so not in `ui`) and the panes the last frame drew: - // each one's document index, view number (Window › New Window) and rect. Canvas - // coordinates map to the current window's pane, inside its rulers and scroll bars + // Window › Arrange › Tile and its layout (not saved, so not in `ui`) and the panes the + // last frame drew: each one's document index, view number (Window › New Window) and rect. + // Canvas coordinates map to the current window's pane, inside its rulers and scroll bars // (`canvasRect`). "tiled": app.ui.tiled, + "tileLayout": app.ui.tile_layout.name(), "panes": app.canvas.panes.last.iter().map(|(w, c)| json!({ "document": w.0, "view": w.1, @@ -2105,7 +2107,7 @@ fn set_ui(app: &mut VectorcraftApp, req: &ControlRequest) -> Outcome { r = app.run("window.panel", json!({"panel": pn})); } if let Some(st) = s("status") { - app.ui.status = st.to_string(); + app.status(st); } for (k, flag) in [ ("rulers", "view.rulers"), diff --git a/crates/ui-egui/src/control/tests.rs b/crates/ui-egui/src/control/tests.rs index 7aa73e8a7e..96c4880d39 100644 --- a/crates/ui-egui/src/control/tests.rs +++ b/crates/ui-egui/src/control/tests.rs @@ -1426,3 +1426,19 @@ fn dialog_set_refuses_a_field_the_dialog_does_not_have() { app.ui.dialog = None; assert_eq!(input_request(&mut app, "ui.dialog.set", json!({"field": "name", "value": "A"}))["error"], "no dialog open"); } + +/// `engine.commands` lists each UI command's default shortcut on this platform: Select Last +/// Selection Tool shows Ctrl+` (`Cmd+~`) on Windows and Linux and none on macOS. +#[test] +fn the_command_list_shows_this_platforms_default_shortcut() { + let mut app = VectorcraftApp::new(Session::new(), Services::default()); + let r = input_request(&mut app, "engine.commands", json!({})); + let row = r["result"].as_array().unwrap().iter().find(|c| c["id"] == "tool.selectLastSelection").cloned(); + let row = row.unwrap_or_else(|| panic!("listed: {r}")); + assert_eq!(row["shortcut"], if crate::keymap::platform().is_mac() { "" } else { "Cmd+~" }, "{row}"); + for p in [craft_keymap::Platform::Windows, craft_keymap::Platform::Linux] { + assert_eq!(crate::shortcut_editor::ui_command_default("tool.selectLastSelection", "Cmd+~", p), "Cmd+~", "{p:?}"); + } + assert_eq!(crate::shortcut_editor::ui_command_default("tool.selectLastSelection", "Cmd+~", craft_keymap::Platform::Mac), ""); + assert_eq!(crate::shortcut_editor::ui_command_default("view.zoomIn", "Cmd+=", craft_keymap::Platform::Mac), "Cmd+="); +} diff --git a/crates/ui-egui/src/cursors.rs b/crates/ui-egui/src/cursors.rs index 4db2e5cb45..83db707642 100644 --- a/crates/ui-egui/src/cursors.rs +++ b/crates/ui-egui/src/cursors.rs @@ -1,5 +1,5 @@ //! Tool cursors drawn as vector glyphs (egui only offers system cursors). Black shapes with a white -//! halo, hotspot at `p`, Illustrator's visual grammar: solid arrow (Selection), hollow arrow (Direct +//! halo, hotspot at `p`, one shape per tool: solid arrow (Selection), hollow arrow (Direct //! Selection), pen nib with state badges, crosshair for drawing tools, curved arrows for rotate. //! //! The desktop app shows them as OS cursors ([`Images`]): the system moves those itself, at once, diff --git a/crates/ui-egui/src/custom_toolbars.rs b/crates/ui-egui/src/custom_toolbars.rs index f8c3033a5e..e54085e304 100644 --- a/crates/ui-egui/src/custom_toolbars.rs +++ b/crates/ui-egui/src/custom_toolbars.rs @@ -1382,7 +1382,7 @@ fn add_menu(button: &egui::Response, t: &Tokens, bar: &CustomToolbar, actions: & let held: Vec<&'static str> = bar.slots.iter().flatten().filter_map(|id| tool_info(id).map(|t| t.id)).collect(); let heading = |ui: &mut egui::Ui, text: &str| ui.label(egui::RichText::new(text).size(12.0).color(t.text_strong)); if !held.is_empty() { - heading(ui, &format!("{}:", tl!("Remove Tool"))); + heading(ui, &crate::i18n::colon(tl!("Remove Tool"))); for tool in held.iter().filter_map(|id| tool_info(id)) { if widgets::menu_item(ui, tool.label, true, false) { actions.push(Action::RemoveTool(bar.name.clone(), tool.id)); @@ -1391,7 +1391,7 @@ fn add_menu(button: &egui::Response, t: &Tokens, bar: &CustomToolbar, actions: & ui.separator(); } for (cat, tools) in crate::edit_toolbar::sections() { - heading(ui, &format!("{}:", tl!(cat))); + heading(ui, &crate::i18n::colon(tl!(cat))); for tool in tools { if widgets::menu_item(ui, tool.label, !held.contains(&tool.id), false) { actions.push(Action::AddTool(bar.name.clone(), tool.id)); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 9e54eb12f6..b96f5a7af0 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -25,7 +25,7 @@ pub mod char_style_options; pub mod check_spelling; pub mod color_balance; pub mod color_guide_options; -mod color_picker; +pub(crate) mod color_picker; mod command; pub mod composite_fonts; pub mod confirm; @@ -167,7 +167,7 @@ pub(crate) use export_for_screens::{ open_assets as open_export_for_screens_assets, preset_list as screen_preset_list, saved_options as screen_saved_options, saved_rows as screen_saved_rows, settings_format as screen_settings_format, }; -pub(crate) use form::{humanize, number_list_text, plugin_color_button, read_number_list, unit_suffix}; +pub(crate) use form::{humanize, number_list_text, plugin_color_button, ppi_suffix, read_number_list, unit_suffix}; pub use new_document::{create_without_dialog as new_document_without_dialog, open as open_new_document, preset_card}; pub(crate) use new_document::{popup_open as new_document_popup_open, preset_name}; pub use png_options::open as open_raster_options; @@ -419,6 +419,7 @@ registry! { SliceOptions: [slices::OPTIONS] => slices::OPTIONS_SPEC, DivideSlices: [slices::DIVIDE] => slices::DIVIDE_SPEC, EpsOptions: [eps_options::KIND] => eps_options::SPEC, + EpsFlattenerOptions: [eps_options::CUSTOM_KIND] => eps_options::CUSTOM_SPEC, Recovery: [crate::recovery::KIND] => recovery::SPEC, PluginStopped: [safe_mode::STOPPED] => safe_mode::STOPPED_SPEC, SafeMode: [safe_mode::KIND] => safe_mode::SPEC, @@ -439,6 +440,7 @@ registry! { ScriptGrowth: [script_run::GROWTH_KIND] => script_run::GROWTH_SPEC, ScriptClose: [script_run::CLOSE_KIND] => script_run::CLOSE_SPEC, ScriptNotice: [script_run::NOTICE_KIND] => script_run::NOTICE_SPEC, + ScriptFiles: [script_run::PICKER_KIND] => script_run::PICKER_SPEC, VectorHalftone: [halftone::KIND] => halftone::SPEC, SimplifySlider: [simplify_slider::KIND] => simplify_slider::SPEC, SmoothSlider: [smooth_slider::KIND] => smooth_slider::SPEC, @@ -476,6 +478,7 @@ registry! { RenameArtboards: [rename_artboards::KIND] => rename_artboards::SPEC, PathToolOptions: [crate::addons::pathtools::KIND] => crate::addons::pathtools::OPTIONS_SPEC, DivideDashes: [crate::addons::pathtools::dashes::KIND] => crate::addons::pathtools::dashes::SPEC, + SmoothBridge: [crate::addons::pathtools::bridge::KIND] => crate::addons::pathtools::bridge::SPEC, TangentCircle: [crate::addons::pathtools::tangent_circle::KIND] => crate::addons::pathtools::tangent_circle::SPEC, SetCorners: [crate::addons::pathtools::set_corners::KIND] => crate::addons::pathtools::set_corners::SPEC, NearestSwatch: [crate::addons::color::nearest::KIND] => crate::addons::color::nearest::SPEC, @@ -544,8 +547,8 @@ fn hidden_controls(d: &Dialog) -> &'static [&'static str] { } // The selected rows and Randomize's seed. Some(DialogKind::Recolor) => &["__seed", "__sel"], - // The view, zoom, download speed, selected color table entry and the preset name being typed. - Some(DialogKind::SaveForWeb) => &["__color", "__kbps", "__presetName", "__view", "__zoom"], + // The view, zoom, download speed, selected color table entries and the preset name being typed. + Some(DialogKind::SaveForWeb) => &["__color", "__colors", "__kbps", "__presetName", "__view", "__zoom"], // The link that keeps width and height in proportion. Some(DialogKind::Shape | DialogKind::TransformEach) => &["__constrain"], // The attention filter, the Keys section, the search text and the key being recorded. @@ -597,7 +600,8 @@ pub fn accepts_field(d: &Dialog, field: &str) -> bool { /// Options setting set this way for several rows is sent to every row (Template also sets Lock /// and Dim Images, as its checkbox does). A DXF Options preset set this way sets its fields, as /// one picked from its menu does, and the preset it shows follows the DXF options set this way. -/// A Graph Data Column Width set this way sets every column, as Cell Style's does. +/// A Graph Data Column Width set this way sets every column, as Cell Style's does. An Import PDF +/// `allPages` set this way to the other pick sets Import PDF pages as links back to its default. pub fn set_field(d: &mut Dialog, field: String, value: Value) { if d.kind == brush_options::KIND { brush_art_options::note_set(d, &field); @@ -608,6 +612,9 @@ pub fn set_field(d: &mut Dialog, field: String, value: Value) { if d.kind == layer_options::KIND { layer_options::note_set(d, &field, &value); } + if d.kind == import_pdf::KIND { + import_pdf::note_set(d, &field, &value); + } if d.kind == "preferences" { crate::prefs_dialog::note_set(d, &field, &value); } @@ -646,6 +653,16 @@ fn run_and_close(app: &mut VectorcraftApp, id: &str, params: Value) -> DialogRes r } +/// Set a tool's options with `tool.setOption` (`params`) and close the dialog; when the tool +/// refuses one of them, nothing is set and the dialog stays open. +fn set_tool_options_and_close(app: &mut VectorcraftApp, params: Value) -> DialogResult { + let r = app.run("tool.setOption", params); + if r.is_ok() { + app.ui.dialog = None; + } + r +} + /// The field of a dialog opened over another (Import Shortcut Set over Keyboard Shortcuts) that /// holds the dialog under it, which Cancel and Escape show again. pub(crate) const PARENT: &str = "__parent"; @@ -656,18 +673,27 @@ pub(crate) fn parent(d: &Dialog) -> Option { } /// `ui.dialog.set` changed `field` of the open dialog from `old`: a choice that sets other fields -/// sets them as choosing it in the dialog does (Export for Screens' `exportPreset`), a change +/// sets them as choosing it in the dialog does (Export for Screens' `exportPreset`, EPS Options' +/// `flattenerPreset`, which drops the Custom… options), a change /// to Export for Screens' sub-folder controls ends an applied preset's item folders, as it does in -/// the dialog, and Transform Each's Relative / Absolute keeps the Scale fields' size. A value +/// the dialog, Transform Each's Relative / Absolute keeps the Scale fields' size, and Recolor +/// Artwork's `group` selects that color group and its `groupAction` runs the button at once. A value /// Composite Fonts' Show Sample can't take is refused. pub(crate) fn field_set(app: &mut VectorcraftApp, field: &str, old: Option<&Value>) -> Result<(), String> { if app.ui.dialog.as_ref().is_some_and(|d| d.kind == transform_each::KIND) { transform_each::field_set(app, field, old); return Ok(()); } + if app.ui.dialog.as_ref().is_some_and(|d| d.kind == recolor::KIND) { + return recolor::field_set(app, field); + } if let Some(d) = app.ui.dialog.as_ref().filter(|d| d.kind == composite_fonts::KIND) { return composite_fonts::field_set(d, field); } + if let Some(d) = app.ui.dialog.as_mut().filter(|d| d.kind == eps_options::KIND) { + eps_options::field_set(d, field); + return Ok(()); + } let Some(d) = app.ui.dialog.as_mut().filter(|d| d.kind == export_for_screens::KIND) else { return Ok(()) }; match field { "exportPreset" => export_for_screens::preset_set(app), @@ -706,6 +732,9 @@ pub fn cancel(app: &mut VectorcraftApp) { if d.kind == script_run::NOTICE_KIND { script_run::notice_cancel(app, &d); } + if d.kind == script_run::PICKER_KIND { + script_run::picker_cancel(app, &d); + } missing_links::cancelled(app, &d); // Find Font's next open starts with an empty replacement search. if d.kind == "findFont" @@ -817,6 +846,10 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { } let focus_first = focus_first && !clicked; let spec = spec(&d.kind); + // Opened over another dialog, which Cancel shows again: that one keeps where it was scrolled to. + if d.fields.get(PARENT).is_some_and(|p| !p.is_null()) { + modal::over_parent(ctx); + } if let Some(window) = spec.window { return window(app, ctx); } @@ -832,6 +865,9 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { if after_panel && !ctx.input(|i| i.key_down(egui::Key::Enter) || i.key_pressed(egui::Key::Enter)) { d.fields.remove(AFTER_PANEL); } + // A body can open another dialog in its place (EPS Options' Custom…): this frame's Enter + // doesn't confirm that one. + let opened = d.kind.clone(); let heading = (spec.heading)(&d); let revolves = revolve_gizmo::active(&d); if revolves { @@ -856,14 +892,16 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { if focus_first { ui.data_mut(|m| m.insert_temp(widgets::dialog_focus_flag(), true)); } + // When the dialog is taller than the window, its body scrolls, and the heading and the + // buttons stay in view. if let Some(body) = spec.body_with_actions { - match body(app, ui, &mut d) { + match modal::body_rows(ui, |ui| body(app, ui, &mut d)) { DialogAction::None => {} DialogAction::Confirm => ok = true, DialogAction::Cancel => cancel = true, } } else { - cancel = (spec.body)(app, ui, &mut d); + cancel = modal::body_rows(ui, |ui| (spec.body)(app, ui, &mut d)); } // Taken (the flag is gone): done. Still there (the window's measuring frame): next frame. if focus_first && ui.data_mut(|m| m.remove_temp::(widgets::dialog_focus_flag())).is_none() { @@ -931,7 +969,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { if ok_clicked && !rejected && !refused_during_click { ok = true; } - if spec.ok.is_some() && ok_enabled && !after_panel && !rejected && crate::shortcuts::pressed_anew(ctx, egui::Key::Enter) { + if spec.ok.is_some() && ok_enabled && !after_panel && !rejected && d.kind == opened && crate::shortcuts::pressed_anew(ctx, egui::Key::Enter) { ok = true; } if discard { @@ -997,6 +1035,8 @@ mod tests_plugin_import; #[cfg(test)] mod tests_raster_formats; #[cfg(test)] +mod tests_raster_supplied_options; +#[cfg(test)] mod tests_svg_options_range; #[cfg(test)] @@ -1042,6 +1082,9 @@ mod tests_perspective; #[cfg(test)] mod tests_modal; +#[cfg(test)] +mod tests_scroll; + #[cfg(test)] mod tests_rectangular_grid; diff --git a/crates/ui-egui/src/dialogs/brush_art_options.rs b/crates/ui-egui/src/dialogs/brush_art_options.rs index 8bc0e66a2e..64ea036fa2 100644 --- a/crates/ui-egui/src/dialogs/brush_art_options.rs +++ b/crates/ui-egui/src/dialogs/brush_art_options.rs @@ -9,7 +9,7 @@ //! open). //! Scatter: per value (`size`, `spacing`, `scatter` %, `rotation` °) `…Min`, `…Max` and `…Mode` //! (`fixed` | `random` | `pressure` | `tilt` | `bearing` | `rotation`), `rotationRelativeTo` (`page` | -//! `path`). +//! `path`), `hueJitter` (°). //! Art: `width` (%), `widthMode` (`fixed` | `pressure` | `tilt` | `bearing` | `rotation`), //! `widthMax` (the width at the heaviest pen pressure, upright or at 180°, %), `scaleMode` (`proportional` | `stretch` | `betweenGuides`), `guideStart` and //! `guideEnd` (% of the art's length), `direction` (`leftToRight` …), `flipAlong`, `flipAcross`, @@ -187,6 +187,7 @@ pub(super) fn fields(b: &Brush, def: Value, f: &mut Map) { f.insert(mode_key(key), json!(mode.id())); } f.insert("rotationRelativeTo".into(), json!(if s.rotation_relative_to_path { "path" } else { "page" })); + f.insert("hueJitter".into(), json!(s.hue_jitter)); } BrushKind::Art(a) => { let (mode, start, end) = match a.scale { @@ -268,6 +269,7 @@ pub(super) fn params(d: &Dialog) -> Value { p[*key] = json!([clamped(d, &min_key(key), range), clamped(d, &max_key(key), range)]); } p["modes"] = json!(SCATTER.map(|(key, _)| scatter_mode(d, key).id())); + p["hue_jitter"] = json!(clamped(d, "hueJitter", Scatter::HUE_JITTER_RANGE)); p } "art" => { @@ -457,6 +459,9 @@ fn scatter_body(ui: &mut egui::Ui, d: &mut Dialog) { ui.add_space(4.0); let relative = [("page", tl!("Page")), ("path", tl!("Path"))]; super::form::choice(ui, d, "rotationRelativeTo", tl!("Rotation relative to:"), (LABEL_W, 104.0), &relative); + ui.add_space(4.0); + // Each copy turns its colors' hue by its own amount up to this many degrees either way. + widgets::label_row(ui, tl!("Hue Jitter:"), LABEL_W, |ui| number(ui, d, "hueJitter", Scatter::HUE_JITTER_RANGE, "°", true)); } fn art_body(ui: &mut egui::Ui, d: &mut Dialog) { @@ -472,6 +477,13 @@ fn art_body(ui: &mut egui::Ui, d: &mut Dialog) { d.fields.insert("widthMode".into(), json!(m.id())); } }); + // A path sets its own width, flips, overlap and colorization, not how the art scales or runs. + if d.bool(super::brush_options::OBJECT) { + flips(ui, d); + ui.add_space(4.0); + super::form::check(ui, d, "overlap", tl!("Overlap")); + return; + } ui.add_space(4.0); widgets::section_header(ui, tl!("Brush Scale Options")); let scales = [ @@ -532,8 +544,11 @@ fn pattern_body(ui: &mut egui::Ui, d: &mut Dialog) { slider_row(ui, d, "scale", tl!("Scale:"), PatternBrush::SCALE_RANGE); widgets::label_row(ui, tl!("Spacing:"), LABEL_W, |ui| number(ui, d, "spacing", PatternBrush::SPACING_RANGE, "%", true)); ui.add_space(6.0); - tiles(ui, d); - ui.add_space(6.0); + // The tiles belong to the brush; a path sets its own scale, spacing, flips, fit and colorization. + if !d.bool(super::brush_options::OBJECT) { + tiles(ui, d); + ui.add_space(6.0); + } flips(ui, d); widgets::section_header(ui, tl!("Fit")); let fits = [("stretch", tl!("Stretch to fit")), ("addSpace", tl!("Add space to fit")), ("approximate", tl!("Approximate path"))]; diff --git a/crates/ui-egui/src/dialogs/brush_options.rs b/crates/ui-egui/src/dialogs/brush_options.rs index bcc880958a..eafe697a0f 100644 --- a/crates/ui-egui/src/dialogs/brush_options.rs +++ b/crates/ui-egui/src/dialogs/brush_options.rs @@ -17,10 +17,18 @@ //! New Brush opens the dialog for a brush that does not exist yet ([`open_new`]), with `__create` //! and, for dropped art, `__ids`: OK runs `brush.new` instead, which gives a name another brush has //! a number, and Cancel adds nothing. +//! +//! The panel menu's Options of Selected Object opens the dialog on the brush of the first selected +//! brushed path, with that path's own settings ([`open_object`]), with `__object`, `__targets` (the +//! brushed paths), `__opened` (the values it opened with) and `__doc` (the uid of the document). It +//! has no name, and of the Art and Pattern brush options only those a path can set for itself. OK +//! runs `brush.objectOptions` with the values changed since it opened: the paths change and the +//! brush stays as it is. OK after another document has become the active one changes nothing. use egui::{Color32, Sense, Stroke, pos2, vec2}; use serde_json::{Map, Value, json}; use vectorcraft_brush::{Bristle, Brush, BrushKind, Calligraphic, Variation}; +use vectorcraft_doc::{AppearanceItem, NodeId, NodeKind}; use super::swatch_options::{grid, label}; use super::{DialogSpec, brush_art_options, form}; @@ -39,6 +47,18 @@ const CREATE: &str = "__create"; /// The field of such a dialog holding the ids of the art dropped on the Brushes panel. const IDS: &str = "__ids"; +/// The field of a Brush Options dialog that Options of Selected Object opened. +pub(super) const OBJECT: &str = "__object"; + +/// The field of such a dialog holding the brushed paths it sets. +const TARGETS: &str = "__targets"; + +/// The field of such a dialog holding the `brush.objectOptions` params it opened with. +const OPENED: &str = "__opened"; + +/// The field of such a dialog holding the uid of the document it opened in. +const DOC: &str = "__doc"; + /// Calligraphic values: (field, label, suffix, decimals), in [`Calligraphic::RANGES`] order. const CALLI: [(&str, &str, &str, usize); 3] = [("angle", "Angle:", "°", 0), ("roundness", "Roundness:", "%", 0), ("size", "Size:", " pt", 1)]; @@ -73,6 +93,9 @@ const NIB_W: f32 = 120.0; const STROKE_W: f32 = 400.0; fn heading(d: &Dialog) -> String { + if d.bool(OBJECT) { + return tl!("Options of Selected Object").into(); + } match d.str("__type").as_str() { "bristle" => tl!("Bristle Brush Options").into(), "calligraphic" => tl!("Calligraphic Brush Options").into(), @@ -146,6 +169,118 @@ fn target(app: &VectorcraftApp) -> Option { selected.or_else(|| vectorcraft_brush::current(&st.doc)) } +/// The brush that the first brushed stroke of path `id` paints with, in library `lib`. +fn stroke_brush<'a>(app: &VectorcraftApp, lib: &'a [Brush], id: NodeId) -> Option<&'a Brush> { + let n = app.session.active()?.doc.node(id)?; + n.appearance.items.iter().find_map(|i| match i { + AppearanceItem::Stroke(st) => st.brush.as_deref().and_then(|name| lib.iter().find(|b| b.name == name)), + AppearanceItem::Fill(_) => None, + }) +} + +/// Can Options of Selected Object open: does a selected path or compound path (or one in a +/// selected group, but not a path inside a compound path, as `brush.objectOptions` takes them) +/// paint with a brush, are all their brushes of one type, and can a path set options of its own +/// for that type? These are the selections `brush.objectOptions` takes. +pub fn object_available(app: &VectorcraftApp) -> bool { + let Some(st) = app.session.active() else { return false }; + let ids = st.selection.subjects(); + if ids.is_empty() { + return false; + } + let lib = vectorcraft_brush::library(&st.doc); + let doc = &st.doc; + // The brush of every brushed stroke of the paths the command sets. + let mut brushes: Vec<&Brush> = vec![]; + for id in ids { + let Some(n) = doc.node(*id) else { continue }; + n.walk(&mut |c| { + let own = matches!(c.kind, NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. }); + let in_compound = doc.parent_of(c.id).and_then(|p| doc.node(p)).is_some_and(|p| matches!(p.kind, NodeKind::Compound { .. })); + if !own || in_compound { + return; + } + for i in &c.appearance.items { + if let AppearanceItem::Stroke(s) = i + && let Some(b) = s.brush.as_deref().and_then(|name| lib.iter().find(|b| b.name == name)) + { + brushes.push(b); + } + } + }); + } + let Some(first) = brushes.first() else { return false }; + !first.kind.stroke_option_keys().is_empty() && brushes.iter().all(|b| b.kind.type_id() == first.kind.type_id()) +} + +/// Open Options of Selected Object: the Brush Options of the brush the first selected brushed path +/// paints with, at that path's own settings, without the name and with only the options a path can +/// set for itself. +pub fn open_object(app: &mut VectorcraftApp) -> Result { + let r = app.run("brush.objectOptions", json!({}))?; + let targets = r["ids"].clone(); + let first = targets.get(0).and_then(Value::as_u64).map(NodeId).ok_or("no path painted with a brush is selected")?; + let st = app.session.active().ok_or("no document open")?; + let (lib, doc) = (vectorcraft_brush::library(&st.doc), st.uid); + let b = stroke_brush(app, &lib, first).ok_or("no path painted with a brush is selected")?; + let own: Map = serde_json::from_value(r["options"].clone()).unwrap_or_default(); + let edited = b.with_stroke_options(&own)?; + let def = serde_json::to_value(&edited).map_err(|e| e.to_string())?; + let mut f = fields(&edited, def)?; + f.insert("__brush".into(), json!(b.name)); + f.insert(OBJECT.into(), json!(true)); + f.insert(TARGETS.into(), targets); + f.insert(DOC.into(), json!(doc)); + let mut d = Dialog { kind: KIND.into(), fields: f }; + let opened = object_params(&d, b.kind.stroke_option_keys()); + d.fields.insert(OPENED.into(), Value::Object(opened)); + d.fields.insert("__keys".into(), json!(b.kind.stroke_option_keys())); + app.ui.dialog = Some(d); + Ok(Value::Null) +} + +/// The fields' `brush.options` params that a path can set for itself (`keys`). +fn object_params(d: &Dialog, keys: &[&str]) -> Map { + match params(d) { + Value::Object(p) => p.into_iter().filter(|(k, _)| keys.contains(&k.as_str())).collect(), + _ => Map::new(), + } +} + +/// What of option value `now` changed from `was`, the value it opened with: `None` when nothing +/// did; of a range or a list of modes, the items that changed with `null` for the others, and of a +/// colorization, the fields that changed. The paths keep their own values for the rest. +fn changed_part(was: Option<&Value>, now: Value) -> Option { + match (was, now) { + (Some(w), n) if *w == n => None, + (Some(Value::Array(w)), Value::Array(n)) if w.len() == n.len() => { + Some(Value::Array(w.iter().zip(n).map(|(w, n)| if *w == n { Value::Null } else { n }).collect())) + } + (Some(Value::Object(w)), Value::Object(n)) => Some(Value::Object(n.into_iter().filter(|(f, v)| w.get(f) != Some(v)).collect())), + (_, n) => Some(n), + } +} + +/// OK of Options of Selected Object: `brush.objectOptions` on the paths it opened for, with the +/// values changed since it opened ([`changed_part`]). The dialog closes when they are set. When +/// another document has become the active one, it closes as Cancel does and changes nothing. +fn confirm_object(app: &mut VectorcraftApp, d: &Dialog) -> Result { + if d.fields.get(DOC).and_then(Value::as_u64) != app.session.active().map(|doc| doc.uid) { + app.ui.dialog = None; + return Ok(json!({})); + } + let keys: Vec = d.fields.get("__keys").and_then(|v| serde_json::from_value(v.clone()).ok()).unwrap_or_default(); + let keys: Vec<&str> = keys.iter().map(String::as_str).collect(); + let opened = d.fields.get(OPENED).and_then(Value::as_object).cloned().unwrap_or_default(); + let changed: Map = + object_params(d, &keys).into_iter().filter_map(|(k, v)| changed_part(opened.get(&k), v).map(|v| (k, v))).collect(); + let r = app.run("brush.objectOptions", json!({ "ids": d.fields.get(TARGETS).cloned().unwrap_or_default(), "params": changed })); + if r.is_ok() { + app.ui.dialog = None; + } + r +} + /// Open the Brush Options of a new brush of type `ty` (`calligraphic` | `scatter` | `art` | /// `bristle` | `pattern`), the second step of New Brush. The fields start from the type's default /// values and the name "New Brush", numbered when another brush has it. A scatter or art @@ -240,7 +375,13 @@ fn create(app: &mut VectorcraftApp, d: &Dialog) -> Result { /// OK: make the new brush when New Brush opened the dialog, else edit the brush. fn ok(app: &mut VectorcraftApp, d: &Dialog) -> Result { - if d.bool(CREATE) { create(app, d) } else { confirm(app, d) } + if d.bool(CREATE) { + create(app, d) + } else if d.bool(OBJECT) { + confirm_object(app, d) + } else { + confirm(app, d) + } } /// The value of field `key` within `range`. @@ -279,13 +420,16 @@ fn params(d: &Dialog) -> Value { } fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { - grid(ui, |ui| { - label(ui, tl!("Name:")); - let max = if d.str("__type") == "bristle" { Bristle::MAX_NAME_CHARS } else { usize::MAX }; - form::text_edit_limited(ui, d, "name", 240.0, max); - ui.end_row(); - }); - ui.add_space(10.0); + // Options of Selected Object sets a path's settings, not the brush, so it has no name. + if !d.bool(OBJECT) { + grid(ui, |ui| { + label(ui, tl!("Name:")); + let max = if d.str("__type") == "bristle" { Bristle::MAX_NAME_CHARS } else { usize::MAX }; + form::text_edit_limited(ui, d, "name", 240.0, max); + ui.end_row(); + }); + ui.add_space(10.0); + } match d.str("__type").as_str() { "bristle" => bristle_body(app, ui, d), "calligraphic" => calligraphic_body(app, ui, d), diff --git a/crates/ui-egui/src/dialogs/brush_options/tests.rs b/crates/ui-egui/src/dialogs/brush_options/tests.rs index df45452a02..de59668708 100644 --- a/crates/ui-egui/src/dialogs/brush_options/tests.rs +++ b/crates/ui-egui/src/dialogs/brush_options/tests.rs @@ -153,6 +153,7 @@ fn scatter_options_show_each_value_with_its_mode_and_ok_applies_them() { "Random", "Rotation relative to:", "Page", + "Hue Jitter:", "Colorization", "Method:", "Tints", @@ -163,10 +164,11 @@ fn scatter_options_show_each_value_with_its_mode_and_ok_applies_them() { let d = app.ui.dialog.as_ref().unwrap(); assert_eq!((d.f64("sizeMin", 0.0), d.f64("sizeMax", 0.0), d.str("sizeMode")), (60.0, 140.0, "random".into())); assert_eq!((d.str("rotationRelativeTo"), d.str("colorization")), ("page".into(), "tints".into())); - // Values are kept within their ranges (rotation here); Fixed takes the first value. + assert_eq!(d.f64("hueJitter", -1.0), 0.0); + // Values are kept within their ranges (rotation and hue jitter here); Fixed takes the first value. set( &mut app, - json!({"sizeMode": "fixed", "sizeMin": 5000, "spacingMode": "pressure", "rotationMin": -400, "rotationRelativeTo": "path", "colorization": "hueShift"}), + json!({"sizeMode": "fixed", "sizeMin": 5000, "spacingMode": "pressure", "rotationMin": -400, "rotationRelativeTo": "path", "colorization": "hueShift", "hueJitter": 400}), ); assert!(shown(&mut app).contains("Hue Shift")); super::super::confirm(&mut app).unwrap(); @@ -177,12 +179,14 @@ fn scatter_options_show_each_value_with_its_mode_and_ok_applies_them() { (&json!([5000.0, 140.0]), &json!(-180.0), &json!(["fixed", "pressure", "random", "random"])) ); assert_eq!((&def["rotation_relative_to_path"], &def["colorization"]["method"]), (&json!(true), &json!("hueShift"))); + assert_eq!(def["hue_jitter"], json!(180.0)); assert!(def["colorization"]["key"].is_object(), "the art's colour as the key: {def}"); assert!(drawn_height(&app, id) > before, "the stroke redraws with the bigger confetti"); // Opened again, it shows what was set. app.run("ui.brushOptions", json!({"name": "Confetti"})).unwrap(); let d = app.ui.dialog.as_ref().unwrap(); assert_eq!((d.str("sizeMode"), d.str("spacingMode"), d.str("colorization")), ("fixed".into(), "pressure".into(), "hueShift".into())); + assert_eq!(d.f64("hueJitter", 0.0), 180.0); } #[test] @@ -883,3 +887,160 @@ fn art_width_and_pattern_scale_have_sliders() { let shown = tree(|ui| super::super::show(&mut app, ui.ctx())); assert_eq!(slider_value(&shown, "Scale:"), (Some(100.0), Some(1.0), Some(10000.0), Some("100%".into()))); } + +/// A level line, selected, painted with brush `brush`. +fn brushed_line(app: &mut VectorcraftApp, y: f64, brush: &str) -> u64 { + let id = app.run("shape.line", json!({"x1": 20, "y1": y, "x2": 220, "y2": y})).unwrap()["id"].as_u64().unwrap(); + app.run("brush.apply", json!({"name": brush, "ids": [id]})).unwrap(); + id +} + +/// The own brush settings of the first stroke of path `id`. +fn own_options(app: &VectorcraftApp, id: u64) -> Value { + let st = app.session.active().unwrap().doc.node(NodeId(id)).and_then(|n| n.appearance.stroke().cloned()).unwrap(); + Value::Object(st.brush_options) +} + +fn select(app: &mut VectorcraftApp, ids: &[u64]) { + app.run("select.set", json!({ "ids": ids })).unwrap(); +} + +#[test] +fn options_of_selected_object_set_one_paths_art_brush_settings() { + let mut app = app(); + let a = brushed_line(&mut app, 50.0, "Arrow"); + let b = brushed_line(&mut app, 100.0, "Arrow"); + select(&mut app, &[a]); + assert!(object_available(&app)); + app.run("ui.brushObjectOptions", json!({})).unwrap(); + let text = shown(&mut app); + for label in ["Options of Selected Object", "Width:", "Flip Along", "Flip Across", "Overlap", "Colorization", "OK"] { + assert!(text.contains(label), "{label} in {text}"); + } + for label in ["Name:", "Brush Scale Options", "Direction:"] { + assert!(!text.contains(label), "{label} in {text}"); + } + set(&mut app, json!({"width": 50})); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(own_options(&app, a), json!({"width": 50.0})); + assert_eq!(own_options(&app, b), json!({})); + assert_eq!(app.run("brush.get", json!({"name": "Arrow"})).unwrap()["width"], json!(100.0), "the brush keeps its width"); + // Opened again, it shows the path's own width, and OK without a change changes nothing. + app.run("ui.brushObjectOptions", json!({})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().f64("width", 0.0), 50.0); + super::super::confirm(&mut app).unwrap(); + assert_eq!(own_options(&app, a), json!({"width": 50.0})); +} + +#[test] +fn options_of_selected_object_change_only_the_values_edited_on_each_path() { + let mut app = app(); + let a = brushed_line(&mut app, 50.0, "Confetti"); + let b = brushed_line(&mut app, 100.0, "Confetti"); + app.run("brush.objectOptions", json!({"ids": [a], "params": {"size": [50, 80]}})).unwrap(); + app.run("brush.objectOptions", json!({"ids": [b], "params": {"size": [60, 120]}})).unwrap(); + select(&mut app, &[a, b]); + app.run("ui.brushObjectOptions", json!({})).unwrap(); + // The dialog shows the first path's values; only the smallest size is edited. + assert_eq!(app.ui.dialog.as_ref().unwrap().f64("sizeMax", 0.0), 80.0); + set(&mut app, json!({"sizeMin": 40})); + super::super::confirm(&mut app).unwrap(); + assert_eq!(own_options(&app, a)["size"], json!([40.0, 80.0])); + assert_eq!(own_options(&app, b)["size"], json!([40.0, 120.0]), "the second path keeps its own largest size"); +} + +/// The modes the first stroke of path `id` draws its brush `brush` with. +fn drawn_modes(app: &VectorcraftApp, id: u64, brush: &str) -> Vec { + let lib = vectorcraft_brush::library(&app.session.active().unwrap().doc); + let b = lib.iter().find(|b| b.name == brush).unwrap(); + let own = own_options(app, id); + match b.with_stroke_options(own.as_object().unwrap()).unwrap().kind { + BrushKind::Calligraphic(c) => c.modes().to_vec(), + BrushKind::Scatter(s) => s.modes().to_vec(), + _ => vec![], + } +} + +#[test] +fn options_of_selected_object_keep_the_modes_they_show_when_a_value_changes() { + let mut app = app(); + // Confetti's size varies at random from 60% to 140%; a size of 60% to 60% leaves the mode the + // dialog shows. + let s = brushed_line(&mut app, 50.0, "Confetti"); + select(&mut app, &[s]); + app.run("ui.brushObjectOptions", json!({})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("sizeMode"), "random"); + set(&mut app, json!({"sizeMax": 60})); + super::super::confirm(&mut app).unwrap(); + assert_eq!(own_options(&app, s)["size"], json!([60.0, 60.0])); + assert_eq!(drawn_modes(&app, s, "Confetti")[0], Variation::Random); + // 6 pt. Flat's angle is Fixed; a variation set without a mode keeps it Fixed. + let c = brushed_line(&mut app, 100.0, "6 pt. Flat"); + select(&mut app, &[c]); + app.run("ui.brushObjectOptions", json!({})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("angleMode"), "fixed"); + set(&mut app, json!({"angleVariation": 30})); + super::super::confirm(&mut app).unwrap(); + assert_eq!(drawn_modes(&app, c, "6 pt. Flat")[0], Variation::Fixed); +} + +#[test] +fn options_of_selected_object_show_what_a_path_can_set_for_each_type() { + let mut app = app(); + // Calligraphic: OK without a change leaves the path on the brush's settings. + let c = brushed_line(&mut app, 40.0, "6 pt. Flat"); + select(&mut app, &[c]); + app.run("ui.brushObjectOptions", json!({})).unwrap(); + let text = shown(&mut app); + for label in ["Angle:", "Roundness:", "Size:"] { + assert!(text.contains(label), "{label} in {text}"); + } + super::super::confirm(&mut app).unwrap(); + assert_eq!(own_options(&app, c), json!({})); + // Pattern: scale, spacing, flips and fit, not the tiles. + let p = brushed_line(&mut app, 80.0, "Diamonds"); + select(&mut app, &[p]); + app.run("ui.brushObjectOptions", json!({})).unwrap(); + let text = shown(&mut app); + for label in ["Scale:", "Spacing:", "Fit", "Flip Along"] { + assert!(text.contains(label), "{label} in {text}"); + } + assert!(!text.contains("Side Tile"), "{text}"); + set(&mut app, json!({"scale": 200})); + super::super::confirm(&mut app).unwrap(); + assert_eq!(own_options(&app, p), json!({"scale": 200.0})); + // Bristle brushes, nothing selected and two brush types are refused. + let r = brushed_line(&mut app, 120.0, "Bristle Round"); + select(&mut app, &[r]); + assert!(!object_available(&app)); + assert!(app.run("ui.brushObjectOptions", json!({})).is_err()); + select(&mut app, &[c, p]); + assert!(!object_available(&app), "the menu item is off for two brush types"); + assert!(app.run("ui.brushObjectOptions", json!({})).is_err()); + assert!(app.ui.dialog.is_none()); + select(&mut app, &[p, r]); + assert!(!object_available(&app), "the menu item is off for a pattern and a bristle brush"); + app.run("select.none", json!({})).unwrap(); + assert!(!object_available(&app)); +} + +#[test] +fn options_of_selected_object_change_nothing_after_another_document_became_active() { + let mut app = app(); + let a = brushed_line(&mut app, 50.0, "Arrow"); + select(&mut app, &[a]); + app.run("ui.brushObjectOptions", json!({})).unwrap(); + set(&mut app, json!({"width": 50})); + // A second document with a brushed path of the same id becomes the active one. + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + app.run("document.activate", json!({"index": 1})).unwrap(); + let other = brushed_line(&mut app, 50.0, "Arrow"); + assert_eq!(other, a); + // OK closes the dialog as Cancel does. + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(own_options(&app, other), json!({}), "the second document's path keeps the brush's settings"); + app.run("document.activate", json!({"index": 0})).unwrap(); + assert_eq!(own_options(&app, a), json!({}), "the first document's path keeps the brush's settings"); +} diff --git a/crates/ui-egui/src/dialogs/brush_replace_art.rs b/crates/ui-egui/src/dialogs/brush_replace_art.rs index cc1a08b251..f1ebf1083f 100644 --- a/crates/ui-egui/src/dialogs/brush_replace_art.rs +++ b/crates/ui-egui/src/dialogs/brush_replace_art.rs @@ -44,7 +44,7 @@ pub fn replace(app: &mut VectorcraftApp, name: &str, ids: &[u64]) { return; } // A preview on a copy of the document checks the art without changing anything. - if !app.session.in_interaction() && app.session.begin_interaction("Replace Brush Art").is_ok() { + if !app.session.in_interaction() && app.begin_interaction("Replace Brush Art").is_ok() { let checked = app.session.preview("brush.replaceArt", ¶ms); // The interaction began above, on the active document: ending it puts that document back // as it was, and can fail only when no document is open, when there is nothing to put back. diff --git a/crates/ui-egui/src/dialogs/bullets_numbering.rs b/crates/ui-egui/src/dialogs/bullets_numbering.rs index 43f15edbb8..3eb9b38547 100644 --- a/crates/ui-egui/src/dialogs/bullets_numbering.rs +++ b/crates/ui-egui/src/dialogs/bullets_numbering.rs @@ -12,14 +12,20 @@ //! preset picked), `bullet` (`dot`, `dash`, `circle` or `square`), `number` (`arabic`, //! `upperLetters`, `lowerLetters`, `upperRoman`, `lowerRoman`, `twoDigits` or `threeDigits`), //! `listAlign` (`left` or `right`), `listLevel` (1 to 9; 1 for paragraphs in no list), -//! `leftIndent` and `firstLineIndent` (pt), as `text.setFormat` takes them, with `__initial` (the -//! values it opened with) and `__targets` (the type and range it acts on). +//! `leftIndent` and `firstLineIndent` (pt), as `text.setFormat` takes them, `startAt` (the Numbers +//! tab's Start At box) and `startNumber` (its number, 1 to 999999999), with `__initial` (the values +//! it opened with) and `__targets` (the type and range it acts on). +//! +//! Start At is VectorCraft's own: on, OK gives the first numbered paragraph the number in the +//! field (`text.setFormat` `startNumber`), and the numbered paragraphs after it count on from it; +//! off, the paragraphs count on from the paragraph before (`restartNumbering` false). The box is on +//! when the paragraphs have a number of their own, off when none has, and blank when they differ. //! //! Behavior reference (public documentation): //! . use serde_json::{Map, Value, json}; -use vectorcraft_doc::text::{LIST_HANGING_INDENT, LIST_LEVELS, NumberStyle, ParaList}; +use vectorcraft_doc::text::{LIST_HANGING_INDENT, LIST_LEVELS, MAX_LIST_START, NumberStyle, ParaList}; use super::swatch_options::label; use super::{DialogSpec, form}; @@ -52,7 +58,7 @@ const ARROWS: egui::EventFilter = egui::EventFilter { tab: false, horizontal_arr /// The fields `ui.dialog.set` can set while the dialog does not hold them: the dialog leaves a /// field out where the paragraphs differ, and holds no `bullet` or `number` for paragraphs in no /// list or in another kind of list. -const INPUTS: [&str; 7] = ["list", "bullet", "number", "listAlign", "listLevel", "leftIndent", "firstLineIndent"]; +const INPUTS: [&str; 9] = ["list", "bullet", "number", "listAlign", "listLevel", "leftIndent", "firstLineIndent", "startAt", "startNumber"]; pub(super) const SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Bullets and Numbering").into(), @@ -85,8 +91,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { crate::panels::character::text_style(app).ok_or("select some type first")?; // While typing, the dialog acts on the paragraphs of the text being edited. let mut targets = json!({}); - if let Some((id, a, b)) = crate::panels::character::text_editing(app) { - crate::panels::character::end_typing(app); + if let Some((id, a, b)) = crate::panels::character::text_editing_kept(app)? { targets = json!({"ids": [id.0], "start": a, "end": b}); } let mut values = Map::new(); @@ -114,6 +119,13 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { if let Some(v) = shared_para_field(app, |p| p.first_line_indent) { values.insert("firstLineIndent".into(), json!(v)); } + // …and Start At: on with the number when the paragraphs share one, off when none has one. + if let Some(start) = shared_para(app, |p| p.list.and_then(|l| l.start)) { + values.insert("startAt".into(), json!(start.is_some())); + if let Some(n) = start { + values.insert("startNumber".into(), json!(n)); + } + } let tab = tab.unwrap_or(if list == Some("number") { "numbers" } else { "bullets" }); let mut fields = Value::Object(values.clone()); fields[INITIAL] = Value::Object(values); @@ -210,6 +222,29 @@ fn number_tab(ui: &mut egui::Ui, d: &mut Dialog) { } None => {} } + ui.add_space(8.0); + start_at(ui, d); +} + +/// The Start At box and its number, 1 to [`MAX_LIST_START`]: the box shows a dash while the +/// paragraphs' numbers differ, and a click then turns it on; the number field is dimmed unless the +/// box is on, and shows 1 until a number is typed. +fn start_at(ui: &mut egui::Ui, d: &mut Dialog) { + ui.horizontal(|ui| { + let on = d.fields.get("startAt").and_then(Value::as_bool); + if widgets::check3(ui, tl!("Start at:"), on, true) { + d.fields.insert("startAt".into(), json!(on != Some(true))); + } + let value = d.fields.get("startNumber").and_then(Value::as_f64).unwrap_or(1.0); + ui.add_enabled_ui(on == Some(true), |ui| { + let name = Some(tl!("Start at:")); + if let Some(v) = + widgets::range_field_named(ui, ("bullets-numbering", "startNumber"), name, value, 1.0..=f64::from(MAX_LIST_START), "", 0, 90.0) + { + d.fields.insert("startNumber".into(), json!(v)); + } + }); + }); } /// A row of preset buttons named `names`, `current` selected, each drawn by `paint` (painter, @@ -367,6 +402,20 @@ fn params(d: &Dialog) -> Map { { p.insert("listLevel".into(), json!(l)); } + // …and Start At, unless the paragraphs are made bulleted or taken out of their list: on, the + // number shown; off, the paragraphs count on from the one before. + if let Some(on) = d.fields.get("startAt").and_then(Value::as_bool) + && !matches!(field("list"), Some("none" | "bullet")) + { + let n = d.fields.get("startNumber").and_then(Value::as_f64).unwrap_or(1.0); + let was_on = initial.and_then(|m| m.get("startAt")).and_then(Value::as_bool); + let was_n = initial.and_then(|m| m.get("startNumber")).and_then(Value::as_f64); + if on && (was_on != Some(true) || was_n != Some(n)) { + p.insert("startNumber".into(), json!(n)); + } else if !on && was_on != Some(false) { + p.insert("restartNumbering".into(), json!(false)); + } + } // For paragraphs in a list and paragraphs in none, an indent left as it was is not sent: // `text.setFormat` then gives each paragraph that joins the list its hanging indent. let mixed = initial.is_some_and(|m| !m.contains_key("list")); @@ -690,7 +739,8 @@ mod tests { app.run("text.setFormat", json!({"ids": [id], "listAlign": "right", "listLevel": 2, "start": 0, "end": 0})).unwrap(); app.run("ui.bulletsAndNumbering", json!({})).unwrap(); let held = app.ui.dialog.as_ref().unwrap().fields.clone(); - for key in INPUTS { + // Neither paragraph has a number of its own, so Start at is off, not blank. + for key in INPUTS.into_iter().filter(|k| !["startAt", "startNumber"].contains(k)) { assert!(!held.contains_key(key), "{key} is blank"); } let fields = json!([ @@ -737,6 +787,67 @@ mod tests { assert_eq!((first(&app, id).0.map(|l| l.level), paras(&app, id).1.list.map(|l| l.level)), (Some(2), Some(2))); } + /// Start at: the box opens off for paragraphs without a number of their own and on with the + /// number for one that has it; a change shows on the type at once, OK keeps it as one undo + /// step, Cancel puts the type back, and turning the box off sends `restartNumbering` false. + #[test] + fn start_at_gives_the_first_numbered_paragraph_its_number() { + let (mut app, id) = app(); + app.run("text.setFormat", json!({"number": "arabic"})).unwrap(); + let undo = app.session.active().unwrap().history.undo.len(); + app.run("ui.bulletsAndNumbering", json!({})).unwrap(); + let d = app.ui.dialog.clone().unwrap(); + assert_eq!((d.fields.get("startAt"), d.fields.get("startNumber")), (Some(&json!(false)), None)); + set(&mut app, "startAt", json!(true)); + set(&mut app, "startNumber", json!(4)); + frame(&mut app); + let starts = |app: &VectorcraftApp| { + let (one, two) = paras(app, id); + (one.list.and_then(|l| l.start), two.list.and_then(|l| l.start)) + }; + assert_eq!(starts(&app), (Some(4), None), "previewed on the type"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo, "the preview adds no undo step"); + super::super::cancel(&mut app); + assert_eq!(starts(&app), (None, None), "Cancel puts it back"); + app.run("ui.bulletsAndNumbering", json!({})).unwrap(); + set(&mut app, "startAt", json!(true)); + set(&mut app, "startNumber", json!(4)); + super::super::confirm(&mut app).unwrap(); + assert_eq!((starts(&app), app.session.active().unwrap().history.undo.len()), ((Some(4), None), undo + 1)); + // One paragraph with a number and one without: the box is blank, and OK sends nothing for it. + app.run("ui.bulletsAndNumbering", json!({})).unwrap(); + let d = app.ui.dialog.clone().unwrap(); + assert!(!d.fields.contains_key("startAt") && !changes(¶ms(&d))); + // The blank box shows a dash, not an empty box. + use egui::accesskit::{Role, Toggled}; + let mut shown = d.clone(); + let tree = crate::widgets::accessibility_tests::tree(|ui| start_at(ui, &mut shown)); + let check = tree.iter().find(|n| n.label() == Some("Start at:") && n.role() == Role::CheckBox).map(|n| n.toggled()); + assert_eq!(check, Some(Some(Toggled::Mixed))); + // A preset that makes the paragraphs bulleted sends no number. + set(&mut app, "startAt", json!(true)); + pick_preset(&mut app, "bullet", Some("dot")); + let p = params(app.ui.dialog.as_ref().unwrap()); + assert!(!p.contains_key("startNumber") && !p.contains_key("restartNumbering")); + super::super::cancel(&mut app); + // A paragraph with a number opens the box on with it, and off sends it back to counting on. + let solo = app.run("text.create", json!({"x": 10, "y": 200, "text": "Solo"})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [solo]})).unwrap(); + app.run("text.setFormat", json!({"number": "arabic", "startNumber": 9})).unwrap(); + app.run("ui.bulletsAndNumbering", json!({})).unwrap(); + let d = app.ui.dialog.clone().unwrap(); + assert_eq!((d.fields.get("startAt"), d.f64("startNumber", 0.0)), (Some(&json!(true)), 9.0)); + assert!(!changes(¶ms(&d)), "nothing changed yet"); + set(&mut app, "startAt", json!(false)); + assert_eq!(params(app.ui.dialog.as_ref().unwrap()).get("restartNumbering"), Some(&json!(false))); + super::super::confirm(&mut app).unwrap(); + let start = match &app.session.active().unwrap().doc.node(NodeId(solo)).unwrap().kind { + NodeKind::Text(t) => t.para_at(0).list.map(|l| l.start), + _ => panic!("not text"), + }; + assert_eq!(start, Some(None), "still numbered, with no number of its own"); + } + /// `text.setFormat` sets `listLevel` only on paragraphs in a list, so a Level change alone on /// paragraphs in no list sends nothing and adds no undo step; with a preset it applies. #[test] diff --git a/crates/ui-egui/src/dialogs/char_style_options.rs b/crates/ui-egui/src/dialogs/char_style_options.rs index 02515a3b89..c07f7af647 100644 --- a/crates/ui-egui/src/dialogs/char_style_options.rs +++ b/crates/ui-egui/src/dialogs/char_style_options.rs @@ -1036,6 +1036,7 @@ fn content_id(ui: &egui::Ui) -> egui::Id { /// (as drawn last frame). The section list stays put while the content scrolls. Returns whether /// the dialog asks to be canceled (never: Cancel comes from the button row in `dialogs::show`). fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + super::modal::fits_itself(ui); let window = ui.ctx().memory(|m| m.area_rect(ui.layer_id().id)).map_or(0.0, |r| r.height()); let content = ui.ctx().data(|m| m.get_temp::(content_id(ui))).unwrap_or(0.0); let rest = (window - content).max(0.0); @@ -1073,7 +1074,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { ui.separator(); if let Ok(attrs) = edited_attrs(d) { for (key, value) in attrs { - ui.label(format!("{}: {}", super::humanize(&key), value)); + ui.label(super::form::attribute_line(&key, &value)); } } } diff --git a/crates/ui-egui/src/dialogs/color_picker.rs b/crates/ui-egui/src/dialogs/color_picker.rs index f86ee17f51..758832cd92 100644 --- a/crates/ui-egui/src/dialogs/color_picker.rs +++ b/crates/ui-egui/src/dialogs/color_picker.rs @@ -103,11 +103,22 @@ impl Channel { Channel::Green => "G", } } - fn is_hsb(self) -> bool { + /// The channel's name, translated: Hue, Saturation, Brightness, Red, Green or Blue. + pub(crate) fn name(self) -> &'static str { + match self { + Channel::Hue => tl!("Hue"), + Channel::Saturation => tl!("Saturation"), + Channel::Brightness => tl!("Brightness"), + Channel::Red => tl!("Red"), + Channel::Green => tl!("Green"), + Channel::Blue => tl!("Blue"), + } + } + pub(crate) fn is_hsb(self) -> bool { matches!(self, Channel::Hue | Channel::Saturation | Channel::Brightness) } /// Indices of (slider, field x, field y) into the channel's space: [h, s, b] or [r, g, b]. - fn axes(self) -> (usize, usize, usize) { + pub(crate) fn axes(self) -> (usize, usize, usize) { match self { Channel::Hue => (0, 1, 2), Channel::Saturation => (1, 0, 2), @@ -119,7 +130,7 @@ impl Channel { } /// The color field's axes (across, up) as keys and screen readers see them: hue in degrees, /// saturation and brightness in percent, red, green and blue from 0 to 255. - fn field_axes(self) -> [widgets::FieldAxis<'static>; 2] { + pub(crate) fn field_axes(self) -> [widgets::FieldAxis<'static>; 2] { let axis = |i: usize| { let (name, units, suffix) = match (self.is_hsb(), i) { (true, 0) => (tl!("Hue"), 360.0, "°"), @@ -282,6 +293,19 @@ pub(super) fn over_effect(parent: &Dialog, field: &str, colour: Color) -> Dialog ); d.fields.insert(super::PARENT.into(), serde_json::to_value(parent).unwrap_or_default()); store(&mut d, &Picked::of(colour)); + d.fields.insert(crate::screen_color::PICKER_ID.into(), json!(crate::screen_color::picker_id())); + d +} + +/// The entry of the dialog's color list that a Color Picker opened with [`over_list_entry`] sets. +const COLOUR_INDEX: &str = "__colourIndex"; + +/// The Color Picker over the dialog `parent`, on `colour`, that sets entry `index` of the dialog's +/// list of colors `field` (Document Setup's `gridColors`) with its OK and goes back to it, leaving +/// the other entries as they are. Cancel goes back to `parent` as it was. It previews nothing. +pub(super) fn over_list_entry(parent: &Dialog, field: &str, index: usize, colour: Color) -> Dialog { + let mut d = over_effect(parent, field, colour); + d.fields.insert(COLOUR_INDEX.into(), json!(index)); d } @@ -360,6 +384,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> DialogAction { let p = picked(d); let original = d.fields.get("original").and_then(color_value).unwrap_or(p.color); let gamut = gamut_fix(app, ui.ctx(), "picker-gamut", &p.color); + super::modal::fits_itself(ui); let (side, values_w, button_w, stacked) = layout_size(ui); let field_w = side + SLIDER_GAP + SLIDER_W; let content_w = if stacked { field_w.max(values_w) } else { field_w + COLUMN_GAP + values_w }; @@ -406,10 +431,19 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> DialogAction { let track = |z: f32| c32(&Picked::of(slider_color(channel, z, x, y)).snapped(web).color); let (v, suffix, max) = channel_value(channel, &p); let shown = widgets::SliderValue::field(v as f64, 0.0..=max as f64, suffix, 0); - if let (Some(z), _) = - widgets::channel_slider_valued(ui, "cp-slider", tl!(channel.label()), Some(shown), z, vec2(SLIDER_W, side), &track) - { - pick = Some(field_pick(channel, z, x, y)); + match widgets::channel_slider_stepped( + ui, + "cp-slider", + tl!(channel.label()), + Some(shown), + z, + true, + vec2(SLIDER_W, side), + &track, + ) { + (Some(z), ..) => pick = Some(field_pick(channel, z, x, y)), + (None, _, Some(v)) => pick = Some(field_pick(channel, (v / max as f64) as f32, x, y)), + _ => {} } }); } @@ -495,13 +529,18 @@ fn preview(app: &mut VectorcraftApp, d: &mut Dialog) { if unchanged || !selected { return; } - let _ = app.session.begin_interaction(if artboard { + let label = if artboard { "Artboard Options" } else if d.bool("stroke") { "Stroke Color" } else { "Fill Color" - }); + }; + // A failure to begin (typing that can't be kept) shows, and nothing previews. + if let Err(e) = app.begin_interaction(label) { + app.status(e); + return; + } if let Err(e) = app.session.preview(cmd, ¶ms) { app.status(e.to_string()); } @@ -724,7 +763,20 @@ fn swatch_list(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, current: &Colo fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { if let Some(field) = d.fields.get(COLOUR_FIELD).and_then(Value::as_str) { let mut parent = super::parent(d).ok_or("the dialog it was opened over is no longer open")?; - parent.fields.insert(field.to_string(), json!(picked(d).color.to_hex())); + let hex = json!(picked(d).color.to_hex()); + match d.fields.get(COLOUR_INDEX) { + None => { + parent.fields.insert(field.to_string(), hex); + } + Some(index) => { + let entry = index + .as_u64() + .and_then(|i| usize::try_from(i).ok()) + .and_then(|i| parent.fields.get_mut(field)?.as_array_mut()?.get_mut(i)) + .ok_or("no such color")?; + *entry = hex; + } + } // The dialog previews the new colour when it comes back: end this picker's interaction, as // Cancel does, so the dialog starts its preview afresh. let _ = app.session.cancel_interaction(); diff --git a/crates/ui-egui/src/dialogs/color_picker/tests.rs b/crates/ui-egui/src/dialogs/color_picker/tests.rs index 0786df7ca9..15344a131c 100644 --- a/crates/ui-egui/src/dialogs/color_picker/tests.rs +++ b/crates/ui-egui/src/dialogs/color_picker/tests.rs @@ -670,7 +670,8 @@ fn warnings_fit_below_the_preview_without_widening_the_dialog() { } let after = ctx.memory(|m| m.area_rect(id)).unwrap(); assert!((before.size() - after.size()).length() < 1.0, "{before:?} vs {after:?}"); - click_at(&ctx, &mut app, warnings[1].center()); + // The cube icon left of the web correction corrects the color too. + click_at(&ctx, &mut app, warnings[1].center() - vec2(19.0, 0.0)); assert!(is_web_safe(&picked(app.ui.dialog.as_ref().unwrap()).color), "web correction remains clickable"); } diff --git a/crates/ui-egui/src/dialogs/command.rs b/crates/ui-egui/src/dialogs/command.rs index 9cb59853a6..de7836f0a5 100644 --- a/crates/ui-egui/src/dialogs/command.rs +++ b/crates/ui-egui/src/dialogs/command.rs @@ -36,7 +36,7 @@ pub(super) const SPEC: DialogSpec = DialogSpec { let mut rows = v.as_str() == Some("rows"); ui.add_space(4.0); egui::Grid::new("text-flow").num_columns(2).spacing([12.0, 8.0]).show(ui, |ui| { - let row = ui.label(egui::RichText::new(format!("{}:", tl!("Text Flow"))).color(Tokens::get(ui.ctx()).text)); + let row = ui.label(egui::RichText::new(crate::i18n::colon(tl!("Text Flow"))).color(Tokens::get(ui.ctx()).text)); ui.label_inputs_by(row.id, |ui| { ui.horizontal(|ui| { if widgets::radio(ui, tl!("By Rows"), rows, true) { @@ -250,8 +250,14 @@ const PATH_ALIGN: form::Choices = &[("Ascender", "ascender"), ("Descender", "des const AREA_FIT: form::Choices = &[("None", "none"), ("Auto Size", "autoHeight"), ("Shrink Text to Fit", "shrinkText"), ("Block", "block")]; /// Area Type Options › First Baseline. -const FIRST_BASELINE: form::Choices = - &[("Ascent", "ascent"), ("Cap Height", "capHeight"), ("x Height", "xHeight"), ("Leading", "leading"), ("Fixed", "fixed")]; +const FIRST_BASELINE: form::Choices = &[ + ("Ascent", "ascent"), + ("Cap Height", "capHeight"), + ("x Height", "xHeight"), + ("Leading", "leading"), + ("Em Box Height", "emBoxHeight"), + ("Fixed", "fixed"), +]; /// Area Type Options › Align (vertical alignment of the lines in each row/column). const VERTICAL_ALIGN: form::Choices = &[("Top", "top"), ("Center", "center"), ("Bottom", "bottom"), ("Justify", "justify")]; @@ -313,6 +319,35 @@ mod tests { assert_eq!(t.area.vertical_align, VerticalAlign::Center); } + /// Area Type Options › First Baseline offers Em Box Height: OK sets it with its Min, and the + /// dialog opens again with it chosen. + #[test] + fn area_type_options_dialog_sets_the_em_box_height_first_baseline() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let id = app.run("text.create", json!({"x": 20, "y": 20, "text": "Hello", "area": {"width": 200, "height": 200}})).unwrap()["id"] + .as_u64() + .unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + // The labels `i18n::tests::first_baseline_choices_are_in_complete_catalogs` checks. + let labels: Vec<&str> = choices("text.areaOptions", "firstBaseline").unwrap().iter().map(|(l, _)| *l).collect(); + assert_eq!(labels, ["Ascent", "Cap Height", "x Height", "Leading", "Em Box Height", "Fixed"]); + crate::menus::invoke(&mut app, "text.areaOptions", json!({})); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("firstBaseline"), "ascent"); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| crate::dialogs::show(&mut app, ui.ctx())); + out.textures_delta.clear(); + let fields = &mut app.ui.dialog.as_mut().unwrap().fields; + fields.insert("firstBaseline".into(), json!("emBoxHeight")); + fields.insert("firstBaselineMin".into(), json!(4.0)); + crate::dialogs::confirm(&mut app).unwrap(); + let NodeKind::Text(t) = &app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind else { panic!("text") }; + assert_eq!((t.area.first_baseline, t.area.first_baseline_min), (vectorcraft_doc::FirstBaseline::EmBoxHeight, 4.0)); + crate::menus::invoke(&mut app, "text.areaOptions", json!({})); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("firstBaseline"), "emBoxHeight"); + } + /// Area Type Options shows the gutter between rows beside the gutter, and OK sets a gutter /// between rows of its own. #[test] @@ -433,6 +468,47 @@ mod tests { assert!(p[0] == p[1] && p[1] == p[2] && p[0] < 128, "red in grayscale: {p:?}"); } + /// Object › Rasterize… opens this dialog with its options as parameter labels (#7991): in + /// French the heading, every field label and the resolution's unit ("ppp") are drawn in French. + #[test] + fn rasterize_dialog_is_drawn_in_the_ui_language() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + let entries = crate::menus::menu_entries(&app); + let item = entries.iter().find(|e| e.path == ["Object"] && e.label == "Rasterize…").expect("listed"); + let (cmd, p) = crate::menus::click_target(&item.label, item.command.as_deref().unwrap(), &item.params); + crate::menus::invoke(&mut app, &cmd, p); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("__label"), "Rasterize"); + let keys: Vec = app.ui.dialog.as_ref().unwrap().fields.keys().filter(|k| !k.starts_with("__")).cloned().collect(); + assert_eq!(keys.len(), 6, "{keys:?}"); + assert_eq!(form::humanize("ppi"), "Resolution:"); + crate::i18n::set_current(crate::i18n::Lang::from_code("fr").unwrap()); + let shown = crate::tests_labels::painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + let heading = heading_label(app.ui.dialog.as_ref().unwrap()); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert_eq!(heading, "Pixelliser"); + let french = ["Ajouter autour de l’objet", "Lissage", "Arrière-plan", "Masque d’écrêtage", "Modèle colorimétrique", "Résolution", "ppp"]; + for s in french { + assert!(shown.contains(s), "{s} in {shown}"); + } + for s in ["Rasterize", "Add Around", "Anti Alias", "Background", "Clipping Mask", "Color Model", "Resolution", "Ppi", "ppi"] { + assert!(!shown.contains(s), "{s} left in English: {shown}"); + } + // Every language with complete menus heads the dialog as the menu item that opened it + // reads, and has a row for each label, the unit and the Color Model choices. + for lang in crate::i18n::Lang::all().filter(|l| l.complete_menus()) { + let menu = crate::i18n::tr(lang, &item.label); + assert_ne!(menu, item.label, "{}: menu item", lang.code()); + assert_eq!(heading_in(lang, "Rasterize"), menu.trim_end_matches('…').trim_end(), "{}: heading", lang.code()); + let labels = keys.iter().map(|k| form::humanize(k).trim_end_matches(':').to_string()); + for label in labels.chain(["{n} ppi", "Grayscale", "Bitmap"].map(String::from)) { + assert!(crate::i18n::has(lang, &label), "{}: {label}", lang.code()); + } + } + } + /// Object › Path › Clean Up… opens this dialog headed "Clean Up", which most catalogs hold only /// as the menu label "Clean Up…" (#7991). In French the heading and every option are translated. #[test] @@ -530,6 +606,56 @@ mod tests { assert_eq!(cols(&app), 2, "one Undo takes the whole change back"); } + /// Grid Repeat Options labels its column fields Columns and Flip Columns, as the Rows and Flip + /// Rows fields beside them are spelled out. + #[test] + fn grid_repeat_options_spell_out_columns() { + let mut app = grid_options_app(); + let shown = crate::tests_labels::painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + for s in ["Rows:", "Columns:", "Flip Rows:", "Flip Columns:"] { + assert!(shown.contains(s), "{s} in {shown}"); + } + assert!(!shown.contains("Cols"), "no Cols label: {shown}"); + } + + /// Object › Create Gradient Mesh… opens this dialog with the menu's rows, cols, appearance and + /// highlight. In French the heading and the four labels are translated, and "cols" is labeled + /// Columns (#7991). + #[test] + fn create_gradient_mesh_dialog_is_drawn_in_the_ui_language() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + let entries = crate::menus::menu_entries(&app); + let item = entries.iter().find(|e| e.path == ["Object"] && e.label == "Create Gradient Mesh…").expect("listed"); + let (cmd, p) = crate::menus::click_target(&item.label, item.command.as_deref().unwrap(), &item.params); + crate::menus::invoke(&mut app, &cmd, p); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("__label"), "Create Gradient Mesh"); + assert_eq!(form::humanize("cols"), "Columns:"); + crate::i18n::set_current(crate::i18n::Lang::from_code("fr").unwrap()); + let shown = crate::tests_labels::painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + let heading = heading_label(app.ui.dialog.as_ref().unwrap()); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert_eq!(heading, "Créer un filet de dégradé"); + for s in ["Créer un filet de dégradé", "Lignes", "Colonnes", "Aspect"] { + assert!(shown.contains(s), "{s} in {shown}"); + } + for s in ["Create Gradient Mesh", "Rows", "Cols", "Columns", "Appearance", "Highlight"] { + assert!(!shown.contains(s), "{s} left in English: {shown}"); + } + // Every language with complete menus heads the dialog as the menu item reads and has the + // four labels. + for lang in crate::i18n::Lang::all().filter(|l| l.complete_menus()) { + let menu = crate::i18n::tr(lang, &item.label); + assert_ne!(menu, item.label, "{}: menu item", lang.code()); + assert_eq!(heading_in(lang, "Create Gradient Mesh"), menu.trim_end_matches('…').trim_end(), "{}: heading", lang.code()); + for key in ["rows", "cols", "appearance", "highlight"] { + let label = form::humanize(key); + assert!(crate::i18n::has(lang, label.trim_end_matches(':')), "{}: {label}", lang.code()); + } + } + } + /// Radial and Mirror Repeat Options have no Preview (their public pages list none): their /// fields apply on OK only, and the dialog takes no `preview`. #[test] diff --git a/crates/ui-egui/src/dialogs/dimension.rs b/crates/ui-egui/src/dialogs/dimension.rs index 140ace0fde..3a977e76c6 100644 --- a/crates/ui-egui/src/dialogs/dimension.rs +++ b/crates/ui-egui/src/dialogs/dimension.rs @@ -4,7 +4,7 @@ use super::DialogSpec; use crate::{VectorcraftApp, state::Dialog, theme::Tokens, widgets}; use egui::{RichText, Ui}; use serde_json::{Value, json}; -use vectorcraft_doc::dimension::DimensionOptions; +use vectorcraft_doc::dimension::{ArrowStyle, DimensionOptions}; pub const KIND: &str = "dimensionOptions"; pub(super) const SPEC: DialogSpec = DialogSpec { @@ -32,6 +32,10 @@ const UNITS: Choices = &[ ]; const LINE_TYPES: Choices = &[("solid", "Solid"), ("dashed", "Dashed"), ("dotted", "Dotted")]; const ARROWS: Choices = &[("filled", "Filled"), ("open", "Open"), ("tick", "Tick"), ("none", "None")]; +/// The style of each `ARROWS` entry, in the same order. +const ARROW_STYLES: [ArrowStyle; 4] = [ArrowStyle::Filled, ArrowStyle::Open, ArrowStyle::Tick, ArrowStyle::None]; +/// The size of an Arrow Style preview: a line with the head at its right end. +const ARROW_PREVIEW: egui::Vec2 = egui::vec2(40.0, 16.0); const POSITIONS: Choices = &[("away", "Away from the Line"), ("between", "Between Line and Object")]; const ALIGNMENTS: Choices = &[("left", "Left"), ("center", "Center"), ("right", "Right")]; @@ -69,6 +73,29 @@ fn choose(ui: &mut Ui, fields: &mut serde_json::Map, key: &str, l }); changed } +/// The Arrow Style dropdown: each style shows a drawn preview of its arrowhead before its name, in +/// the open list and in the closed field. +fn arrow_style(ui: &mut Ui, fields: &mut serde_json::Map, id: &str) -> bool { + const KEY: &str = "arrowStyle"; + let mut changed = false; + widgets::label_row(ui, tl!("Arrow Style:"), 96.0, |ui| { + let current = fields.get(KEY).and_then(Value::as_str).unwrap_or_default(); + let shown = ARROWS.iter().position(|(v, _)| *v == current); + let names: Vec<&str> = ARROWS.iter().map(|(_, s)| tl!(*s)).collect(); + let icon = |ui: &Ui, rect: egui::Rect, i: usize, ink: egui::Color32, _: bool| { + if let Some(style) = ARROW_STYLES.get(i) { + crate::panels::stroke::paint_arrow(ui, rect, style.arrowhead().as_ref(), false, ink); + } + }; + if let Some((value, _)) = + widgets::dropdown_icon_names_sized(ui, ("dimension", id), shown, &names, 150.0, ARROW_PREVIEW, icon).and_then(|i| ARROWS.get(i)) + { + fields.insert(KEY.into(), json!(value)); + changed = true; + } + }); + changed +} fn number(ui: &mut Ui, fields: &mut serde_json::Map, key: &str, label: &str, range: (f64, f64), suffix: &str) -> bool { let mut changed = false; widgets::label_row(ui, tl!(label), 96.0, |ui| { @@ -160,7 +187,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { color(ui, f, "lineColor"); }); ui.horizontal(|ui| { - choose(ui, f, "arrowStyle", "Arrow Style:", ARROWS); + arrow_style(ui, f, "arrowStyle"); number(ui, f, "arrowScale", "Arrow Scale:", (1.0, 1000.0), "%"); }); }); @@ -211,7 +238,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { Ok(o) => { let sample = o.label(72.0, false).unwrap_or_default(); let t = Tokens::get(ui.ctx()); - ui.label(RichText::new(format!("{}: {sample}", tl!("Preview (1 inch on the page)"))).color(t.text)); + ui.label(RichText::new(format!("{} {sample}", crate::i18n::colon(tl!("Preview (1 inch on the page)")))).color(t.text)); } Err(e) => { ui.colored_label(Tokens::get(ui.ctx()).text, e); @@ -310,7 +337,7 @@ pub fn properties_section(app: &mut VectorcraftApp, ui: &mut Ui) { changed |= number(ui, &mut f, "lineWeight", "Line Weight:", (0.1, 100.0), "pt"); changed |= color(ui, &mut f, "lineColor"); }); - ui.horizontal(|ui| changed |= choose(ui, &mut f, "arrowStyle", "Arrow Style:", ARROWS)); + ui.horizontal(|ui| changed |= arrow_style(ui, &mut f, "props-arrowStyle")); ui.horizontal(|ui| { changed |= number(ui, &mut f, "fontSize", "Font Size:", (1.0, 1000.0), "pt"); changed |= color(ui, &mut f, "textColor"); @@ -377,4 +404,56 @@ mod tests { assert!(text.contains(label), "{label}: {text}"); } } + + /// Whether a frame drew a picture (a textured mesh) just before the text `name` on its line. + fn picture_before(out: &egui::FullOutput, name: &str) -> bool { + fn collect(s: &egui::Shape, texts: &mut Vec<(String, egui::Rect)>, pictures: &mut Vec) { + match s { + egui::Shape::Text(t) => texts.push((t.galley.text().to_owned(), t.visual_bounding_rect())), + egui::Shape::Mesh(m) if m.texture_id != egui::TextureId::default() => pictures.push(m.calc_bounds()), + egui::Shape::Vec(v) => v.iter().for_each(|s| collect(s, texts, pictures)), + _ => {} + } + } + let (mut texts, mut pictures) = (vec![], vec![]); + for c in &out.shapes { + collect(&c.shape, &mut texts, &mut pictures); + } + texts + .iter() + .filter(|(t, _)| t == name) + .any(|(_, r)| pictures.iter().any(|p| p.max.x <= r.min.x + 1.0 && r.min.x - p.max.x < 16.0 && p.min.y < r.max.y && p.max.y > r.min.y)) + } + + /// The frame `f` draws, once its previews are loaded. + fn frame(app: &mut VectorcraftApp, mut f: impl FnMut(&mut VectorcraftApp, &mut Ui)) -> egui::FullOutput { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + ctx.run_ui(egui::RawInput::default(), |ui| f(app, ui)).textures_delta.clear(); + ctx.run_ui(egui::RawInput::default(), |ui| f(app, ui)) + } + + /// The Arrow Style field of the Tool Options and of Properties shows the style's arrowhead, + /// drawn, before its name (#8049). + #[test] + fn arrow_style_shows_a_drawn_arrowhead() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("tool.options", json!({"tool":"dimension"})).unwrap(); + let out = frame(&mut app, |app, ui| super::super::show(app, ui.ctx())); + assert!(picture_before(&out, "Filled"), "Tool Options"); + app.ui.dialog = None; + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("dimension.create", json!({"a":[10,10],"b":[110,10],"options":{"arrowStyle":"tick"}})).unwrap(); + let out = frame(&mut app, properties_section); + assert!(picture_before(&out, "Tick"), "Properties"); + } + + /// Each Arrow Style entry previews the style its value names. + #[test] + fn arrow_previews_follow_the_listed_styles() { + assert_eq!(ARROWS.len(), ARROW_STYLES.len()); + for ((value, _), style) in ARROWS.iter().zip(ARROW_STYLES) { + assert_eq!(serde_json::to_value(style).unwrap(), json!(value)); + } + } } diff --git a/crates/ui-egui/src/dialogs/document_setup.rs b/crates/ui-egui/src/dialogs/document_setup.rs index 1946cc86b2..187e36e6b0 100644 --- a/crates/ui-egui/src/dialogs/document_setup.rs +++ b/crates/ui-egui/src/dialogs/document_setup.rs @@ -175,17 +175,30 @@ fn general(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool close } +/// The id of the Transparency tab's box that shows grid color `index` (0 or 1). +fn grid_color_box_id(index: usize) -> egui::Id { + egui::Id::unique(("grid-color-box", index)) +} + +/// The grid colors' hex codes that Document Setup `d` holds now (empty strings for entries that are +/// not strings). +fn grid_colors(d: &Dialog) -> Vec { + d.fields.get("gridColors").and_then(Value::as_array).map(|a| a.iter().map(|c| c.as_str().unwrap_or("").to_string()).collect()).unwrap_or_default() +} + fn transparency(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { let t = Tokens::get(ui.ctx()); widgets::subheader(ui, tl!("Transparency Grid")); let sizes: Vec<(&str, &str)> = GridSize::ALL.iter().map(|g| (g.id(), g.label())).collect(); choice(ui, d, "gridSize", tl!("Grid Size:"), &sizes); - let colors: Vec = d - .fields - .get("gridColors") - .and_then(Value::as_array) - .map(|a| a.iter().map(|c| c.as_str().unwrap_or("").to_string()).collect()) - .unwrap_or_default(); + // A preset name in the fields (any case, as `document.setup` takes it) becomes the preset's two + // colors, which the hex fields and the Color Picker edit one at a time. + if let Some((_, pair)) = + d.fields.get("gridColors").and_then(Value::as_str).and_then(|n| GRID_COLOR_PRESETS.iter().find(|(p, _)| p.eq_ignore_ascii_case(n))) + { + d.fields.insert("gridColors".into(), json!(pair.map(|c| c.to_hex()))); + } + let colors = grid_colors(d); let preset = GRID_COLOR_PRESETS .iter() .find(|(_, pair)| colors.len() == 2 && colors.iter().zip(pair).all(|(h, c)| h.eq_ignore_ascii_case(&c.to_hex()))) @@ -196,18 +209,40 @@ fn transparency(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { d.fields.insert("gridColors".into(), json!(pair.map(|c| c.to_hex()))); } }); - // The two colours (the first is also the paper colour): editing either makes them Custom. + // The two colours (the first is also the paper colour): editing either makes them Custom. A + // click on a color's box, or Space or Enter with the keyboard on it, opens the Color Picker on + // that color (white when its hex is not a color), and the picker's OK sets that color. The + // picker opens after the row, on the color Document Setup holds then: a press on a box ends a + // hex field's editing in the same frame, and that field's edit is the color the picker opens on. + // A hex field's edit replaces its own color in the pair Document Setup holds when it commits. + let mut pick = None; widgets::label_row(ui, "", LABEL, |ui| { for i in 0..2 { let hex = colors.get(i).map_or("", |h| h.trim_start_matches('#')); + let colour = vectorcraft_color::Color::from_hex(hex); + let name = format!("{} {}", tl!("Grid Colors:"), i + 1); let (chip, _) = ui.allocate_exact_size(egui::vec2(18.0, 18.0), egui::Sense::hover()); - if let Some(c) = vectorcraft_color::Color::from_hex(hex) { + let resp = ui.interact(chip, grid_color_box_id(i), egui::Sense::click()); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &name)); + let keyed = resp.has_focus() + && ui.input_mut(|inp| { + inp.consume_key(egui::Modifiers::NONE, egui::Key::Space) | inp.consume_key(egui::Modifiers::NONE, egui::Key::Enter) + }); + if resp.clicked() || keyed { + pick = Some(i); + } + if resp.hovered() { + ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand); + } + if let Some(c) = colour { ui.painter().rect_filled(chip, 2.0, crate::panels::c32(&c)); } ui.painter().rect_stroke(chip, 2.0, egui::Stroke::new(1.0, t.input_border), egui::StrokeKind::Inside); - let name = format!("{} {}", tl!("Grid Colors:"), i + 1); + if resp.has_focus() { + ui.painter().rect_stroke(chip.expand(2.0), 3.0, ui.visuals().selection.stroke, egui::StrokeKind::Outside); + } if let Some(c) = widgets::hex_field_named(ui, ("grid-color", i), Some(&name), hex).and_then(|h| vectorcraft_color::Color::from_hex(&h)) { - let mut v = colors.clone(); + let mut v = grid_colors(d); v.resize(2, "#ffffff".into()); v[i] = c.to_hex(); d.fields.insert("gridColors".into(), json!(v)); @@ -215,6 +250,10 @@ fn transparency(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { ui.add_space(10.0); } }); + if let Some(i) = pick { + let c = grid_colors(d).get(i).and_then(|h| vectorcraft_color::Color::from_hex(h.trim_start_matches('#'))); + *d = super::color_picker::over_list_entry(d, "gridColors", i, c.unwrap_or(vectorcraft_color::Color::WHITE)); + } ui.add_space(4.0); check(ui, d, "simulatePaper", tl!("Simulate Colored Paper")); ui.add_space(14.0); @@ -635,4 +674,242 @@ mod tests { assert_eq!(fill(&app, id), before); assert_eq!(undo_steps(&app), steps); } + + /// The Light pair a new document's transparency grid starts with. + const LIGHT: [&str; 2] = ["#ffffff", "#cccccc"]; + + fn hex(h: &str) -> Color { + Color::from_hex(h).unwrap_or_else(|| panic!("bad hex {h}")) + } + + /// The grid colors Document Setup `d` holds. + fn dialog_grid(d: &crate::state::Dialog) -> Vec { + d.fields["gridColors"].as_array().unwrap().iter().map(|c| hex(c.as_str().unwrap())).collect() + } + + /// A new document with Document Setup open on its Transparency tab, drawn in the context returned. + fn transparency_tab() -> (VectorcraftApp, egui::Context) { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("file.documentSetup", json!({})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("tab".into(), json!("Transparency")); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, Default::default()); + for _ in 0..4 { + dialog_frame(&mut app, &ctx, vec![]); + } + (app, ctx) + } + + /// Clicks the box of grid color `index`. + fn click_grid_box(app: &mut VectorcraftApp, ctx: &egui::Context, index: usize) { + let at = ctx.read_response(super::grid_color_box_id(index)).unwrap_or_else(|| panic!("no box {index}")).rect.center(); + let button = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + dialog_frame(app, ctx, vec![Event::PointerMoved(at), button(true)]); + dialog_frame(app, ctx, vec![button(false)]); + } + + /// The Color Picker is open over Document Setup, on `color`, and Document Setup's OK has not run. + fn assert_picker_over_setup(app: &VectorcraftApp, color: &str, case: &str) { + let d = app.ui.dialog.as_ref().unwrap_or_else(|| panic!("{case}: no dialog")); + assert_eq!(d.kind, "colorPicker", "{case}"); + assert_eq!(d.fields.get("color").and_then(vectorcraft_engine::cmd::color_value), Some(hex(color)), "{case}"); + assert_eq!(crate::dialogs::parent(d).map(|p| p.kind), Some(super::KIND.to_string()), "{case}"); + assert_eq!(undo_steps(app), 0, "{case}: Document Setup's OK has not run"); + } + + /// A click on either grid color's box opens the Color Picker over Document Setup on that + /// color. Its OK sets only that color, the Grid Colors menu names the pair (Custom, or the + /// preset it matches), and Document Setup's OK applies the pair in one undo step. + #[test] + fn a_grid_color_box_opens_the_color_picker_and_its_ok_sets_that_color() { + for (index, picked, pair, name) in [(0, "#00ff00", ["#00ff00", "#cccccc"], "Custom"), (1, "#c4dcff", ["#ffffff", "#c4dcff"], "Blue")] { + let (mut app, ctx) = transparency_tab(); + click_grid_box(&mut app, &ctx, index); + assert_picker_over_setup(&app, LIGHT[index], name); + app.ui.dialog.as_mut().unwrap().fields.insert("color".into(), json!(picked)); + crate::dialogs::confirm(&mut app).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.kind.as_str(), dialog_grid(d)), (super::KIND, pair.map(hex).to_vec()), "{name}"); + assert_eq!(undo_steps(&app), 0, "{name}: the picker's OK leaves the document as it is"); + dialog_frame(&mut app, &ctx, vec![]); + let texts: Vec = dialog_frame(&mut app, &ctx, vec![]).into_iter().map(|(t, _)| t).collect(); + assert!(texts.iter().any(|t| t == name), "{name}: {texts:?}"); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + let st = app.session.active().unwrap(); + assert_eq!((st.doc.setup.grid_colors, st.doc.setup.grid_colors_name()), (pair.map(hex), name)); + assert_eq!(undo_steps(&app), 1, "{name}"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().doc.setup.grid_colors, LIGHT.map(hex), "{name}"); + } + } + + /// With the keyboard on a grid color's box, Enter or Space opens the Color Picker on that + /// color instead of pressing Document Setup's OK. + #[test] + fn enter_or_space_on_a_grid_color_box_opens_the_color_picker() { + for (index, key) in [(0, egui::Key::Enter), (1, egui::Key::Space)] { + let (mut app, ctx) = transparency_tab(); + ctx.memory_mut(|m| m.request_focus(super::grid_color_box_id(index))); + dialog_frame(&mut app, &ctx, vec![]); + let press = Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + dialog_frame(&mut app, &ctx, vec![press]); + assert_picker_over_setup(&app, LIGHT[index], &format!("{key:?}")); + } + } + + /// Cancel in the Color Picker goes back to Document Setup with the grid colors as they were, + /// and so does its OK on the color it opened on; Document Setup's OK then records no undo step. + #[test] + fn grid_color_picker_cancel_or_an_unchanged_ok_changes_nothing() { + for cancel in [true, false] { + let (mut app, ctx) = transparency_tab(); + click_grid_box(&mut app, &ctx, 1); + assert_picker_over_setup(&app, LIGHT[1], &format!("cancel {cancel}")); + if cancel { + app.ui.dialog.as_mut().unwrap().fields.insert("color".into(), json!("#ff0000")); + crate::dialogs::cancel(&mut app); + } else { + crate::dialogs::confirm(&mut app).unwrap(); + } + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.kind.as_str(), dialog_grid(d)), (super::KIND, LIGHT.map(hex).to_vec()), "cancel {cancel}"); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.active().unwrap().doc.setup.grid_colors_name(), "Light"); + assert_eq!(undo_steps(&app), 0, "cancel {cancel}"); + } + } + + /// With a preset name in Document Setup's `gridColors` field, the grid color boxes show the + /// preset's colors, and the Color Picker opens on the clicked one; its OK sets that color and + /// keeps the preset's other one. + #[test] + fn a_grid_color_box_opens_the_picker_when_the_field_names_a_preset() { + let (mut app, ctx) = transparency_tab(); + app.ui.dialog.as_mut().unwrap().fields.insert("gridColors".into(), json!("blue")); + dialog_frame(&mut app, &ctx, vec![]); + click_grid_box(&mut app, &ctx, 1); + assert_picker_over_setup(&app, "#c4dcff", "blue"); + app.ui.dialog.as_mut().unwrap().fields.insert("color".into(), json!("#00ff00")); + crate::dialogs::confirm(&mut app).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.kind.as_str(), dialog_grid(d)), (super::KIND, ["#ffffff", "#00ff00"].map(hex).to_vec())); + } + + /// The screen color sampler works in the Color Picker of a grid color: the color sampled goes + /// to that picker, and its OK sets the grid color. + #[test] + fn the_grid_color_picker_takes_a_screen_sampled_color() { + let (mut app, ctx) = transparency_tab(); + let (tx, rx) = std::sync::mpsc::channel::(); + let mut rx = Some(rx); + app.services.screen_color = Some(Box::new(move || rx.take().ok_or_else(|| "shown twice".to_string()))); + click_grid_box(&mut app, &ctx, 0); + assert_picker_over_setup(&app, LIGHT[0], "before sampling"); + app.run("ui.sampleScreenColor", json!({"picker": true})).unwrap(); + tx.send(Ok(Some([0.0, 0.5, 1.0]))).unwrap(); + crate::screen_color::poll(&mut app, &ctx); + let sampled = app.ui.dialog.as_ref().unwrap().fields.get("color").and_then(vectorcraft_engine::cmd::color_value).unwrap(); + assert_ne!(sampled.to_hex(), LIGHT[0]); + crate::dialogs::confirm(&mut app).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + let grid: Vec = dialog_grid(d).iter().map(Color::to_hex).collect(); + assert_eq!((d.kind.as_str(), grid), (super::KIND, vec![sampled.to_hex(), LIGHT[1].to_string()])); + } + + /// Clicks the hex field that shows `digits` and types `typed` over its text, leaving the edit + /// pending; returns the field's id. + fn type_into_hex_field(app: &mut VectorcraftApp, ctx: &egui::Context, digits: &str, typed: &str) -> egui::Id { + let texts = dialog_frame(app, ctx, vec![]); + let at = texts.iter().find(|(t, _)| t == digits).unwrap_or_else(|| panic!("no field {digits}: {texts:?}")).1.center(); + let button = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + dialog_frame(app, ctx, vec![Event::PointerMoved(at), button(true)]); + dialog_frame(app, ctx, vec![button(false)]); + let field = ctx.memory(|m| m.focused()).unwrap_or_else(|| panic!("field {digits} has no focus")); + dialog_frame(app, ctx, vec![Event::Text(typed.into())]); + assert_eq!(ctx.memory(|m| m.focused()), Some(field), "the edit in {digits} is pending"); + field + } + + /// A click on a grid color's box whose press and release come in one frame, while that + /// color's hex field holds an edit, opens the Color Picker on the edited color: the press + /// commits the edit before the picker opens. The picker's unchanged OK keeps the edit, and the + /// other color stays as it was. + #[test] + fn a_grid_color_box_clicked_during_a_hex_edit_opens_the_picker_on_the_edit() { + for index in [0, 1] { + let (mut app, ctx) = transparency_tab(); + type_into_hex_field(&mut app, &ctx, LIGHT[index].trim_start_matches('#'), "123456"); + let at = ctx.read_response(super::grid_color_box_id(index)).unwrap_or_else(|| panic!("no box {index}")).rect.center(); + let button = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + dialog_frame(&mut app, &ctx, vec![Event::PointerMoved(at), button(true), button(false)]); + let case = format!("box {index}"); + assert_picker_over_setup(&app, "#123456", &case); + let mut pair = LIGHT; + pair[index] = "#123456"; + assert_eq!(dialog_grid(&crate::dialogs::parent(app.ui.dialog.as_ref().unwrap()).unwrap()), pair.map(hex).to_vec(), "{case}"); + crate::dialogs::confirm(&mut app).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.kind.as_str(), dialog_grid(d)), (super::KIND, pair.map(hex).to_vec()), "{case}"); + } + } + + /// A hex field's edit that commits in the frame a Grid Colors preset is chosen replaces only + /// its own color in the preset's pair: the other color is the preset's. The test gives the + /// field the focus while the Grid Colors menu is open, then chooses a preset with a click whose + /// press and release come in one frame. + #[test] + fn a_hex_edit_committed_with_a_preset_choice_keeps_the_presets_other_color() { + let field = { + let (mut app, ctx) = transparency_tab(); + type_into_hex_field(&mut app, &ctx, "ffffff", "123456") + }; + let (mut app, ctx) = transparency_tab(); + let click = |app: &mut VectorcraftApp, label: &str, frames: usize| { + let texts = dialog_frame(app, &ctx, vec![]); + let at = texts.iter().find(|(t, _)| t == label).unwrap_or_else(|| panic!("no {label}: {texts:?}")).1.center(); + let button = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + if frames == 1 { + dialog_frame(app, &ctx, vec![Event::PointerMoved(at), button(true), button(false)]); + } else { + dialog_frame(app, &ctx, vec![Event::PointerMoved(at), button(true)]); + dialog_frame(app, &ctx, vec![button(false)]); + } + }; + click(&mut app, "Light", 2); + ctx.memory_mut(|m| m.request_focus(field)); + dialog_frame(&mut app, &ctx, vec![]); + let select_all = Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND }; + dialog_frame(&mut app, &ctx, vec![select_all, Event::Text("123456".into())]); + assert_eq!(ctx.memory(|m| m.focused()), Some(field), "the edit is pending"); + let texts: Vec = dialog_frame(&mut app, &ctx, vec![]).into_iter().map(|(t, _)| t).collect(); + assert!(texts.iter().any(|t| t == "123456") && texts.iter().any(|t| t == "Blue"), "{texts:?}"); + click(&mut app, "Blue", 1); + assert_eq!(dialog_grid(app.ui.dialog.as_ref().unwrap()), ["#123456", "#c4dcff"].map(hex).to_vec()); + } + + /// The picker's OK sets nothing when the dialog under it has no such color or is gone: it is + /// an error, and the picker stays open. + #[test] + fn grid_color_picker_without_its_color_or_its_dialog_is_an_error() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("file.documentSetup", json!({})).unwrap(); + let setup = app.ui.dialog.clone().unwrap(); + let mut short = setup.clone(); + short.fields.insert("gridColors".into(), json!(["#ffffff"])); + let mut orphan = crate::dialogs::color_picker::over_list_entry(&setup, "gridColors", 0, Color::WHITE); + orphan.fields.remove(crate::dialogs::PARENT); + for picker in [crate::dialogs::color_picker::over_list_entry(&short, "gridColors", 1, Color::WHITE), orphan] { + app.ui.dialog = Some(picker); + app.ui.dialog.as_mut().unwrap().fields.insert("color".into(), json!("#ff0000")); + assert!(crate::dialogs::confirm(&mut app).is_err()); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some("colorPicker")); + } + assert_eq!(app.session.active().unwrap().doc.setup.grid_colors, LIGHT.map(hex)); + assert_eq!(undo_steps(&app), 0); + } } diff --git a/crates/ui-egui/src/dialogs/effect.rs b/crates/ui-egui/src/dialogs/effect.rs index ac2798ec40..987fceeea4 100644 --- a/crates/ui-egui/src/dialogs/effect.rs +++ b/crates/ui-egui/src/dialogs/effect.rs @@ -41,7 +41,7 @@ fn three_d_refusal(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, } else if !app.session.in_interaction() && d.fields.get(TRIED) != Some(¶ms) { // Waits for another interaction to end: trying inside it would replace its preview and // cancel it. A failure to begin leaves no interaction: the preview below then reports it. - let _ = app.session.begin_interaction(&d.str("__label")); + let _ = app.begin_interaction(&d.str("__label")); match app.session.preview(cmd, ¶ms) { Ok(_) => { d.fields.remove(form::REFUSED); @@ -255,9 +255,14 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { d.fields.insert("preview".into(), json!(pv)); if pv && (changed || pv_changed || !app.session.in_interaction()) { let label = d.str("__label"); - let _ = app.session.begin_interaction(&label); - let (cmd, p) = command(d); - let _ = app.session.preview(cmd, &p); + // A failure to begin (typing that can't be kept) shows, and nothing previews. + match app.begin_interaction(&label) { + Ok(()) => { + let (cmd, p) = command(d); + let _ = app.session.preview(cmd, &p); + } + Err(e) => app.status(e), + } } else if !pv && pv_changed { let _ = app.session.cancel_interaction(); } @@ -317,6 +322,13 @@ fn center_round(x: f64) -> f64 { (x * 1e4).round() / 1e4 } +/// The value screen readers give Blur Center at `c` (0 to 1 of the bounds): Horizontal and +/// Vertical in percent, each label followed by the UI language's colon. +pub(super) fn blur_center_value(c: [f64; 2]) -> String { + let percent = |v: f64| (v * 1000.0).round() / 10.0; + format!("{} {}%, {} {}%", crate::i18n::colon(tl!("Horizontal")), percent(c[0]), crate::i18n::colon(tl!("Vertical")), percent(c[1])) +} + /// Radial Blur's Blur Center: a box standing for the object's bounds, with the blur's pattern (rays /// for Zoom, rings for Spin) drawn about the center. A press or a drag in the box puts the center /// there; with the keyboard focus the arrow keys move it 1 % of the box (10 % with Shift). The @@ -334,9 +346,8 @@ fn blur_center(ui: &mut egui::Ui, d: &mut Dialog) { let (rect, _) = ui.allocate_exact_size(egui::vec2(CENTER_BOX, CENTER_BOX), Sense::hover()); let id = ui.scope_id().with("radial-blur-center"); let resp = ui.interact(rect, id, Sense::click_and_drag()); - let percent = |v: f64| (v * 1000.0).round() / 10.0; let name = tl!("Blur Center").to_string(); - let value = format!("{}: {}%, {}: {}%", tl!("Horizontal"), percent(c[0]), tl!("Vertical"), percent(c[1])); + let value = blur_center_value(c); let enabled = ui.is_enabled(); resp.widget_info(|| egui::WidgetInfo { current_text_value: Some(value.clone()), @@ -391,7 +402,7 @@ fn blur_center(ui: &mut egui::Ui, d: &mut Dialog) { ui.vertical(|ui| { egui::Grid::new("blur-center-fields").num_columns(2).spacing([8.0, 8.0]).show(ui, |ui| { for (i, label) in ["Horizontal", "Vertical"].into_iter().enumerate() { - let row = ui.label(egui::RichText::new(format!("{}:", tl!(label))).color(t.text)); + let row = ui.label(egui::RichText::new(crate::i18n::colon(tl!(label))).color(t.text)); ui.label_inputs_by(row.id, |ui| { if let Some(x) = widgets::range_field_named(ui, ("blur-center", i), None, c[i] * 100.0, 0.0..=100.0, &form::unit_suffix("%"), 1, 72.0) diff --git a/crates/ui-egui/src/dialogs/effect_gallery.rs b/crates/ui-egui/src/dialogs/effect_gallery.rs index fe0de205fc..39c2dc6c7c 100644 --- a/crates/ui-egui/src/dialogs/effect_gallery.rs +++ b/crates/ui-egui/src/dialogs/effect_gallery.rs @@ -1,4 +1,4 @@ -//! Effect → Effect Gallery: browse Photoshop-style raster filters by category, build a stack, and +//! Effect → Effect Gallery: browse raster filters by category, build a stack, and //! apply it as separate appearance effects in one undo step. //! //! Each filter has a thumbnail, and the dialog has its own preview, as the @@ -29,7 +29,7 @@ const PREVIEW_H: usize = 84; /// Dialog kind for the Effect Gallery. pub const KIND: &str = "effectGallery"; -/// Raster effect submenus in the gallery (the six Photoshop-style folders it holds). +/// Raster effect submenus in the gallery (the six raster filter folders it holds). const CATEGORIES: [(&str, &[&str]); 6] = [ ("Artistic", &["Effect", "Artistic"]), ("Brush Strokes", &["Effect", "Brush Strokes"]), @@ -313,11 +313,20 @@ fn stack_batch_params(stack: &[StackEntry]) -> Value { } /// Live canvas preview of the stack (`command.batch` would settle the dialog interaction each frame). +/// Typing in progress is kept as its own undo step first; only the gallery's own earlier preview is +/// canceled. fn preview_stack_on_canvas(app: &mut VectorcraftApp, stack: &[StackEntry]) { + if let Err(e) = app.keep_typing() { + app.status(e); + return; + } if app.session.in_interaction() { let _ = app.session.cancel_interaction(); } - let _ = app.session.begin_interaction("Effect Gallery"); + if let Err(e) = app.begin_interaction("Effect Gallery") { + app.status(e); + return; + } for (i, entry) in stack.iter().enumerate() { let params = Value::Object(entry.params.clone()); if app.run("effect.apply", json!({ "effect": entry.effect, "params": params })).is_err() { @@ -425,7 +434,7 @@ fn sample_drawing(w: usize, h: usize) -> Vec { out } -/// Run one Photoshop-style filter on a premultiplied RGBA buffer. Leaves it unchanged when `id` +/// Run one raster filter on a premultiplied RGBA buffer. Leaves it unchanged when `id` /// is not one of those filters or the buffer is the wrong size. fn apply_pixel(id: &str, params: &Map, data: &mut [u8], w: usize, h: usize) { let Some(n) = w.checked_mul(h).and_then(|n| n.checked_mul(4)) else { return }; @@ -766,6 +775,39 @@ mod tests { assert!(app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.effects.is_empty()); } + /// With Real-time Drawing off, typing in progress when the stack previews is kept as a step of + /// its own, not canceled with the gallery's earlier preview. + #[test] + fn stack_preview_keeps_typing_in_progress() { + use vectorcraft_tools::{PointerEvent, PointerKind}; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + app.run("prefs.set", json!({"key": "realTimeDrawing", "value": false})).unwrap(); + let id = app.run("text.create", json!({"x": 100, "y": 100, "text": "Hello", "size": 20})).unwrap()["id"].as_u64().unwrap(); + let id = vectorcraft_doc::NodeId(id); + let v = vectorcraft_engine::ViewInfo::default(); + app.session.select_tool("type", v).unwrap(); + let b = app.session.active().unwrap().doc.bounds_of(&[id], false).unwrap(); + for k in [PointerKind::Down, PointerKind::Up] { + app.session.pointer(&PointerEvent::new(k, b.x1 - 1.0, b.center().y), v).unwrap(); + } + app.session.tool_text(" world", v).unwrap(); + let plain = |app: &VectorcraftApp| match &app.session.active().unwrap().doc.node(id).unwrap().kind { + vectorcraft_doc::NodeKind::Text(t) => t.plain_text(), + _ => panic!("not text"), + }; + assert_eq!(plain(&app), "Hello", "the typing waits"); + let steps = app.session.active().unwrap().history.undo.len(); + app.run("ui.effectGalleryDialog", json!({})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("stack".into(), json!([{ "effect": "artistic.cutout", "visible": true, "params": { "levels": 3 } }])); + frame(&mut app); + let st = app.session.active().unwrap(); + assert_eq!(st.interaction.as_ref().map(|it| it.label.as_str()), Some("Effect Gallery")); + assert_eq!(st.history.undo.len(), steps + 1, "the typing is a step of its own"); + assert_eq!(plain(&app), "Hello world"); + } + #[test] fn stack_ok_is_one_undo_step() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); diff --git a/crates/ui-egui/src/dialogs/eps_options.rs b/crates/ui-egui/src/dialogs/eps_options.rs index 8d34706df4..0eb1853065 100644 --- a/crates/ui-egui/src/dialogs/eps_options.rs +++ b/crates/ui-egui/src/dialogs/eps_options.rs @@ -6,14 +6,20 @@ //! Fields: `document.export` params (`format: eps`, `path?`, the artboard choice) and the EPS //! options of `document.exportEps`. OK remembers the options for next time and writes the file //! (asking where when there is no path); bad options keep the dialog open. +//! +//! Custom… beside the flattener preset opens Custom Transparency Flattener Options over the +//! dialog: its OK sets every flattener option as `flattener` (the preset then shows [Custom]) and +//! goes back to EPS Options; Cancel goes back with the options as they were. Choosing a preset +//! drops the custom options. use serde_json::{Map, Value, json}; -use vectorcraft_engine::cmd::{FlattenOptions, fileio}; +use vectorcraft_engine::cmd::{FlattenOptions, FlattenerPreset, fileio}; use vectorcraft_eps::{Level, Overprint, Preview}; use super::DialogSpec; use super::document_setup::{LABEL, check, choice}; use crate::state::Dialog; +use crate::theme::Tokens; use crate::{VectorcraftApp, io, widgets}; pub(super) const KIND: &str = "epsOptions"; @@ -25,7 +31,18 @@ pub(super) const SPEC: DialogSpec = DialogSpec { ok: Some("Export"), min_width: 420.0, max_width: Some(460.0), - inputs: |_| &["path"], + inputs: |_| &["path", "flattener"], + ..DialogSpec::FORM +}; + +/// Custom Transparency Flattener Options, opened over EPS Options by Custom…. +pub(super) const CUSTOM_KIND: &str = "epsFlattenerOptions"; + +pub(super) const CUSTOM_SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("Custom Transparency Flattener Options").into(), + body: custom_body, + confirm: custom_confirm, + min_width: 420.0, ..DialogSpec::FORM }; @@ -61,11 +78,12 @@ pub fn open(app: &mut VectorcraftApp, params: &Value) { fields.extend(o.iter().map(|(k, v)| (k.clone(), v.clone()))); } } - fields.insert("format".into(), json!("eps")); - // A built-in preset named by id (`medium`) shows as its name. - if let Some(label) = fields.get("flattenerPreset").and_then(Value::as_str).and_then(|p| FlattenOptions::preset_label(&p.to_ascii_lowercase())) { - fields.insert("flattenerPreset".into(), json!(label)); + // A preset asked for without options of its own replaces the custom options used last. + if params.get("flattenerPreset").is_some() && params.get("flattener").is_none() { + fields.remove("flattener"); } + fields.insert("format".into(), json!("eps")); + builtin_label(&mut fields); app.ui.dialog = Some(Dialog::new(KIND, Value::Object(fields))); } @@ -90,8 +108,19 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { let overprints: Vec<(&str, &str)> = Overprint::ALL.iter().map(|o| (o.id(), o.label())).collect(); choice(ui, d, "overprints", tl!("Overprints:"), &overprints); let presets = app.session.flattener_presets(); - let names: Vec<(&str, &str)> = presets.iter().map(|p| (p.name.as_str(), p.name.as_str())).collect(); - choice(ui, d, "flattenerPreset", tl!("Preset:"), &names); + let current = flattener(d, &app.session.prefs.flattener_presets).ok(); + let mut custom = false; + widgets::label_row(ui, tl!("Preset:"), LABEL, |ui| { + if let Some(p) = super::flatten::preset_dropdown(ui, "eps-flattener-preset", &presets, &d.str("flattenerPreset"), current.as_ref(), 180.0) { + d.fields.insert("flattenerPreset".into(), json!(p.name)); + d.fields.remove("flattener"); + } + custom = widgets::flat_button_fit(ui, tl!("Custom…"), 72.0).clicked(); + }); + if custom { + *d = over(d, &app.session.prefs.flattener_presets); + return false; + } ui.add_space(8.0); widgets::subheader(ui, tl!("Fonts")); // Type is written as glyph outlines, which need no fonts. @@ -122,6 +151,81 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { false } +/// `ui.dialog.set` changed `field` of EPS Options `d`: a preset set there drops the Custom… +/// options, as choosing it in the dropdown does, and a built-in one named by id shows as its name. +pub(super) fn field_set(d: &mut Dialog, field: &str) { + if field == "flattenerPreset" { + d.fields.remove("flattener"); + builtin_label(&mut d.fields); + } +} + +/// A built-in preset named by id (`medium`) in `fields` shows as its name. +fn builtin_label(fields: &mut Map) { + if let Some(label) = fields.get("flattenerPreset").and_then(Value::as_str).and_then(|p| FlattenOptions::preset_label(&p.to_ascii_lowercase())) { + fields.insert("flattenerPreset".into(), json!(label)); + } +} + +/// The flattener options EPS Options `d` exports with: its preset, with the Custom… options over it. +fn flattener(d: &Dialog, saved: &[FlattenerPreset]) -> Result { + FlattenOptions::for_export(d.fields.get("flattenerPreset").and_then(Value::as_str), d.fields.get("flattener"), saved) +} + +/// Custom Transparency Flattener Options over EPS Options `parent`, on the options it exports with +/// (the default preset's while those are not valid), without alpha: EPS has none. +pub(super) fn over(parent: &Dialog, saved: &[FlattenerPreset]) -> Dialog { + let mut o = flattener(parent, saved).unwrap_or_default(); + o.preserve_alpha = false; + let mut d = Dialog::new(CUSTOM_KIND, json!({})); + super::flatten::put_options(&mut d.fields, &o); + d.fields.insert(super::PARENT.into(), serde_json::to_value(parent).unwrap_or_default()); + d +} + +/// The options Custom Transparency Flattener Options `d` holds. +fn custom_options(d: &Dialog) -> Result { + FlattenOptions::from_params_with(&Value::Object(d.fields.clone()), &[]) +} + +/// Whether the EPS Options under `d` keep overprints (Overprints: Preserve). +fn overprints_kept(d: &Dialog) -> bool { + super::parent(d).is_none_or(|p| Overprint::from_id(&p.str("overprints")) != Some(Overprint::Discard)) +} + +/// The flattener options; the two Preserve switches show what the export does and are set by the +/// format (no alpha) and by EPS Options' Overprints. +fn custom_body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + let current = custom_options(d); + // Values refused stay as entered, so that changing another option keeps them. The Preserve + // switches can't be set here, so the fields keep their own values of them. + let (mut o, unread) = super::flatten::shown_options(&d.fields, ¤t); + o.preserve_alpha = false; + o.preserve_overprints &= overprints_kept(d); + super::flatten::fields_editor(ui, "eps-flattener", &mut d.fields, &mut o, &unread, true); + if let Err(e) = ¤t { + ui.label(egui::RichText::new(e).color(Tokens::get(ui.ctx()).text_dim).size(11.5)); + } + ui.add_space(8.0); + super::form::caption(ui, tl!("EPS has no alpha transparency, and Overprints sets whether overprints are kept.")); + false +} + +/// OK: EPS Options again, exporting with these options (a built-in preset under them, so that +/// deleting a saved preset leaves them whole); bad options keep the dialog open. +fn custom_confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let mut o = custom_options(d)?; + o.preserve_alpha = false; + let mut parent = super::parent(d).ok_or("the dialog it was opened over is no longer open")?; + if FlattenOptions::preset(&parent.str("flattenerPreset")).is_none() { + let medium = FlattenOptions::preset_label(FlattenOptions::PRESETS[1]).unwrap_or_default(); + parent.fields.insert("flattenerPreset".into(), json!(medium)); + } + parent.fields.insert("flattener".into(), serde_json::to_value(&o).map_err(|e| e.to_string())?); + app.ui.dialog = Some(parent); + Ok(Value::Null) +} + /// Check the options, remember them, and write the file(s). fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let params = fileio::eps::resolve(&super::form::params(d), &app.session.prefs.flattener_presets)?; diff --git a/crates/ui-egui/src/dialogs/expand.rs b/crates/ui-egui/src/dialogs/expand.rs index 383ea567df..cda98afada 100644 --- a/crates/ui-egui/src/dialogs/expand.rs +++ b/crates/ui-egui/src/dialogs/expand.rs @@ -1,7 +1,9 @@ //! Object → Expand: what to expand (Object: live shapes, type and effects; Fill: gradient and pattern fills; //! Stroke: strokes into filled outlines) and what gradient fills become (a gradient mesh, or a //! number of objects). Options the selection has nothing for are disabled. OK runs -//! `object.expand` as one undo step. +//! `object.expand` as one undo step and keeps its choices for the rest of the app's run: the dialog +//! opens on them, and Object › Expand… chosen with Alt (Option) expands with them at once +//! ([`expand_now`]). //! //! Fields: `object`, `fill`, `stroke`, `gradient` (`objects` | `mesh`), `steps` (1..1000), and //! `__object`, `__fill`, `__stroke` (that option has something to expand: `object.expand.info`), @@ -31,15 +33,51 @@ pub(crate) fn appearance_first() -> &'static str { tl!("Expand Appearance first (Object › Expand Appearance)") } -/// Open Expand for the selection, every option on (as `object.expand {}` does). A selection with -/// appearance attributes (effects, several fills or strokes…) refuses with [`appearance_first`]: -/// the menu item is dimmed for it. +/// Open Expand for the selection, on the choices OK last expanded with in this run of the app, or +/// every option on (as `object.expand {}` does) before that. A selection with appearance attributes +/// (effects, several fills or strokes…) refuses with [`appearance_first`]: the menu item is dimmed +/// for it. pub fn open(app: &mut VectorcraftApp) -> Result { + let fields = fields(app)?; + app.ui.dialog = Some(Dialog::new(KIND, fields)); + Ok(Value::Null) +} + +/// Object › Expand… chosen with Alt (Option): expand the selection at once, in one undo step, with +/// the choices OK last expanded with in this run of the app (the dialog's defaults before that), as +/// OK in the dialog opened on them would. When none of those choices has something to expand in the +/// selection, the dialog opens on them instead, and nothing changes. A selection with appearance +/// attributes refuses with [`appearance_first`], as [`open`] does. +pub fn expand_now(app: &mut VectorcraftApp) -> Result { + let d = Dialog::new(KIND, fields(app)?); + if !OPTIONS.iter().any(|(key, _)| d.bool(key) && option_enabled(&d, key)) { + app.ui.dialog = Some(d); + return Ok(Value::Null); + } + app.run(CMD, params(&d)) +} + +/// The choices OK last expanded with (`app.ui.expand_options`), when each one holds a value the +/// dialog shows: a switch for Object, Fill and Stroke, `objects` or `mesh`, and 1 to 1000 steps. +fn remembered(app: &VectorcraftApp) -> Option<&Value> { + let o = &app.ui.expand_options; + let switches = OPTIONS.iter().all(|(key, _)| o[key].is_boolean()); + let gradient = matches!(o["gradient"].as_str(), Some("objects" | "mesh")); + let steps = o["steps"].as_f64().is_some_and(|n| (1.0..=MAX_STEPS as f64).contains(&n.round())); + (switches && gradient && steps).then_some(o) +} + +/// The dialog's fields for the selection: the remembered choices (or the defaults) and what each +/// option has to expand. +fn fields(app: &mut VectorcraftApp) -> Result { let info = app.session.execute("object.expand.info", &json!({})).map_err(|e| e.to_string())?; if info["appearance"] == json!(true) { return Err(appearance_first().into()); } - let mut fields = json!({"object": true, "fill": true, "stroke": true, "gradient": "objects", "steps": DEFAULT_STEPS}); + let mut fields = match remembered(app) { + Some(o) => json!({"object": o["object"], "fill": o["fill"], "stroke": o["stroke"], "gradient": o["gradient"], "steps": o["steps"]}), + None => json!({"object": true, "fill": true, "stroke": true, "gradient": "objects", "steps": DEFAULT_STEPS}), + }; for (key, _) in OPTIONS { fields[format!("__{key}")] = info[key].clone(); } @@ -47,8 +85,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { for key in ["fill", "stroke", "gradient"] { fields[format!("__{key}_symbol")] = json!(info["symbolArt"][key] == json!(true)); } - app.ui.dialog = Some(Dialog::new(KIND, fields)); - Ok(Value::Null) + Ok(fields) } fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { @@ -112,8 +149,12 @@ fn params(d: &Dialog) -> Value { }) } +/// OK: expand, and keep the choices once the expansion succeeded. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { - run_and_close(app, CMD, params(d)) + let choices = params(d); + let r = run_and_close(app, CMD, choices.clone())?; + app.ui.expand_options = choices; + Ok(r) } #[cfg(test)] @@ -253,4 +294,140 @@ mod tests { app.run("select.none", json!({})).unwrap(); assert!(!crate::menus::enabled(&app, "ui.expandDialog")); } + + /// A rectangle with a linear gradient fill and no stroke is selected. + fn gradient_rectangle(app: &mut VectorcraftApp) { + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 100, "height": 60})).unwrap(); + app.run("paint.setFill", json!({"gradient": {"kind": "linear"}})).unwrap(); + app.run("paint.setStroke", json!({"none": true})).unwrap(); + } + + /// Object › Expand… from the in-window menu, with Alt held or not. + fn choose_expand(app: &mut VectorcraftApp, alt: bool) { + let entries = crate::menus::menu_entries(app); + let e = entries.iter().find(|e| e.path == ["Object"] && e.label == "Expand…").expect("Object › Expand…"); + assert!(e.enabled, "Expand… is available"); + let target = crate::menus::click_target(&e.label, e.command.as_deref().unwrap(), &e.params); + let held = if alt { egui::Modifiers::ALT } else { egui::Modifiers::NONE }; + let (cmd, p) = crate::menus::with_held_keys(target, held); + crate::menus::invoke(app, &cmd, p); + } + + /// Whether the selected object is a clip group holding a gradient mesh (Expand Gradient To › + /// Gradient Mesh) rather than solid objects. + fn expanded_to_a_mesh(app: &VectorcraftApp) -> bool { + let st = app.session.doc().unwrap(); + let g = st.doc.node(st.selection.objects[0]).unwrap(); + let NodeKind::Group { children, clip: true } = &g.kind else { panic!("a clip group: {:?}", g.kind) }; + children.iter().any(|c| matches!(c.kind, NodeKind::Mesh(_))) + } + + #[test] + fn the_dialog_opens_on_the_choices_ok_last_expanded_with() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + gradient_rectangle(&mut app); + choose_expand(&mut app, false); + let d = app.ui.dialog.as_mut().expect("the Expand dialog"); + d.fields.insert("gradient".into(), json!("mesh")); + d.fields.insert("steps".into(), json!(12)); + d.fields.insert("stroke".into(), json!(false)); + super::super::confirm(&mut app).unwrap(); + assert!(expanded_to_a_mesh(&app)); + app.run("edit.undo", json!({})).unwrap(); + let kept = json!({"object": true, "fill": true, "stroke": false, "gradient": "mesh", "steps": 12.0}); + choose_expand(&mut app, false); + assert_eq!(params(app.ui.dialog.as_ref().unwrap()), kept, "it opens on the choices OK expanded with"); + // Cancel leaves them as they were. + app.ui.dialog.as_mut().unwrap().fields.insert("gradient".into(), json!("objects")); + super::super::cancel(&mut app); + assert_eq!(app.ui.expand_options, kept); + // So does an OK that fails, and nothing changes. + choose_expand(&mut app, false); + app.ui.dialog.as_mut().unwrap().fields.insert("steps".into(), json!(5000)); + let before = app.session.doc().unwrap().doc.clone(); + assert!(super::super::confirm(&mut app).is_err()); + assert_eq!(app.session.doc().unwrap().doc, before); + assert_eq!(app.ui.expand_options, kept); + choose_expand(&mut app, false); + assert_eq!(params(app.ui.dialog.as_ref().unwrap()), kept); + } + + #[test] + fn alt_expands_at_once_with_the_choices_ok_last_expanded_with() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + gradient_rectangle(&mut app); + choose_expand(&mut app, false); + app.ui.dialog.as_mut().unwrap().fields.insert("gradient".into(), json!("mesh")); + super::super::confirm(&mut app).unwrap(); + app.run("edit.undo", json!({})).unwrap(); + let undo = app.session.doc().unwrap().history.undo.len(); + choose_expand(&mut app, true); + assert!(app.ui.dialog.is_none(), "no dialog"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); + assert!(expanded_to_a_mesh(&app), "the kept Gradient Mesh choice"); + } + + #[test] + fn alt_before_any_ok_expands_with_the_defaults() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + gradient_rectangle(&mut app); + let undo = app.session.doc().unwrap().history.undo.len(); + choose_expand(&mut app, true); + assert!(app.ui.dialog.is_none(), "no dialog"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1); + assert!(!expanded_to_a_mesh(&app), "the gradient becomes objects, the default"); + assert!(app.ui.expand_options.is_null(), "Alt keeps no choices of its own"); + } + + #[test] + fn alt_opens_the_dialog_when_the_kept_choices_expand_nothing_in_the_selection() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 100, "height": 60})).unwrap(); + // Fill alone was kept, and a plain rectangle has no gradient or pattern fill. + app.ui.expand_options = json!({"object": false, "fill": true, "stroke": false, "gradient": "objects", "steps": 255.0}); + let before = app.session.doc().unwrap().doc.clone(); + let undo = app.session.doc().unwrap().history.undo.len(); + choose_expand(&mut app, true); + let d = app.ui.dialog.as_ref().expect("the Expand dialog"); + assert_eq!(params(d), app.ui.expand_options, "it opens on the kept choices"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo, "nothing recorded"); + assert_eq!(app.session.doc().unwrap().doc, before); + } + + #[test] + fn alt_refuses_a_selection_with_appearance_attributes_and_a_bad_immediate() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + zig_zag_line(&mut app); + let before = app.session.doc().unwrap().doc.clone(); + assert_eq!(app.run("ui.expandDialog", json!({"immediate": true})).unwrap_err(), appearance_first()); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.doc().unwrap().doc, before, "the line is left as it was"); + app.run("effect.expandAppearance", json!({})).unwrap(); + assert!(app.run("ui.expandDialog", json!({"immediate": "yes"})).is_err()); + assert!(app.ui.dialog.is_none()); + app.run("ui.expandDialog", json!({"immediate": false})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND)); + } + + #[test] + fn kept_choices_with_a_value_the_dialog_does_not_show_are_left_out() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + gradient_rectangle(&mut app); + for bad in [ + json!({"object": "yes", "fill": true, "stroke": true, "gradient": "mesh", "steps": 12}), + json!({"object": true, "fill": true, "stroke": true, "gradient": "strips", "steps": 12}), + json!({"object": true, "fill": true, "stroke": true, "gradient": "mesh", "steps": 0}), + json!({"object": true, "fill": true, "stroke": true, "gradient": "mesh"}), + ] { + app.ui.expand_options = bad; + app.run("ui.expandDialog", json!({})).unwrap(); + assert_eq!( + params(app.ui.dialog.as_ref().unwrap()), + json!({"object": true, "fill": true, "stroke": true, "gradient": "objects", "steps": 255.0}) + ); + app.ui.dialog = None; + } + } } diff --git a/crates/ui-egui/src/dialogs/export_for_screens.rs b/crates/ui-egui/src/dialogs/export_for_screens.rs index 026f477a0e..298e6d2c45 100644 --- a/crates/ui-egui/src/dialogs/export_for_screens.rs +++ b/crates/ui-egui/src/dialogs/export_for_screens.rs @@ -1,4 +1,4 @@ -//! File → Export → Export for Screens, laid out as Illustrator's: on the left the Artboards and +//! File → Export → Export for Screens: on the left the Artboards and //! Assets tabs (thumbnails with checkboxes, in a grid or a list), Clear Selection and the prefix; //! on the right Select (All, a range or Full Document, Include Bleed, Include Artboard Fill), the destination (folder //! picker, Open Location after Export, Create Sub-folders by scale or by format; the web downloads @@ -721,7 +721,7 @@ fn tiles( ui.painter().galley(label_pos, galley, t.text); false }; - // The checkbox sits on the thumbnail's lower left corner, as Illustrator's. + // The checkbox sits on the thumbnail's lower left corner. let bx = egui::Rect::from_min_size(egui::pos2(pic.left() + 4.0, pic.bottom() - 18.0), egui::vec2(14.0, 14.0)); let mut child = ui.new_child(egui::UiBuilder::new().max_rect(bx)); if widgets::check_box(&mut child, &name, checked, true) || resp.clicked() || caption_clicked { diff --git a/crates/ui-egui/src/dialogs/flare_options.rs b/crates/ui-egui/src/dialogs/flare_options.rs index 9c374f3cf5..5b6834d46e 100644 --- a/crates/ui-egui/src/dialogs/flare_options.rs +++ b/crates/ui-egui/src/dialogs/flare_options.rs @@ -16,7 +16,7 @@ use vectorcraft_geom::Point; use vectorcraft_tools::extra::{FLARE_OPTIONS, flare_params}; use super::document_setup::check; -use super::{DialogResult, DialogSpec, form, run_and_close}; +use super::{DialogResult, DialogSpec, form, set_tool_options_and_close}; use crate::state::Dialog; use crate::{VectorcraftApp, widgets}; @@ -155,12 +155,14 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { values.insert(key.into(), json!(d.bool(key))); } if let Some((cmd, params)) = command { + // Options the tool would refuse leave the dialog open, before the flare is accepted. + vectorcraft_tools::option_check::check_values(vectorcraft_tools::create("flare").as_ref(), &values)?; // Accept the preview once; option persistence follows successful artwork creation. let result = form::commit_preview(app, &cmd, params)?; app.run("tool.setOption", json!({ "tool": "flare", "values": values }))?; Ok(result) } else { - run_and_close(app, "tool.setOption", json!({ "tool": "flare", "values": values })) + set_tool_options_and_close(app, json!({ "tool": "flare", "values": values })) } } @@ -312,10 +314,11 @@ mod tests { super::super::confirm(&mut app).unwrap(); let parts = flare_parts(&app); assert_eq!(parts.iter().filter(|p| *p == "Ring").count(), 3, "{parts:?}"); - // Out-of-range values are kept within the option's range. - app.run("tool.setOption", json!({"tool": "flare", "values": {"opacity": 900, "diameter": -4}})).unwrap(); - let o = app.session.tool_options_of("flare"); - assert_eq!((o["opacity"].as_f64(), o["diameter"].as_f64()), (Some(100.0), Some(0.0))); + // An out-of-range value is an error, and no option changes. + let before = app.session.tool_options_of("flare"); + let e = app.run("tool.setOption", json!({"tool": "flare", "values": {"opacity": 50, "diameter": -4}})).unwrap_err(); + assert_eq!(e, "tool `flare`: `diameter` must be a number from 0 to 1000"); + assert_eq!(app.session.tool_options_of("flare"), before); } #[test] diff --git a/crates/ui-egui/src/dialogs/flatten.rs b/crates/ui-egui/src/dialogs/flatten.rs index 0c5bc7dbee..a22631c8e2 100644 --- a/crates/ui-egui/src/dialogs/flatten.rs +++ b/crates/ui-egui/src/dialogs/flatten.rs @@ -48,6 +48,53 @@ pub(crate) fn put_options(fields: &mut Map, o: &FlattenOptions) { } } +/// The options `fields` hold over `base` as they were entered, values out of range included, for +/// the editor to show while [`FlattenOptions::from_params_with`] refuses them, and the keys of the +/// values of the wrong type, which take `base`'s value here and show blank in the editor. +pub(crate) fn entered_options(fields: &Map, base: &FlattenOptions) -> (FlattenOptions, Vec) { + let Ok(Value::Object(mut v)) = serde_json::to_value(base) else { return (base.clone(), Vec::new()) }; + let mut unread = Vec::new(); + for (k, val) in fields { + let Some(slot) = v.get_mut(k) else { continue }; + let old = std::mem::replace(slot, val.clone()); + if serde_json::from_value::(Value::Object(v.clone())).is_err() { + v.insert(k.clone(), old); + unread.push(k.clone()); + } + } + (serde_json::from_value(Value::Object(v)).unwrap_or_else(|_| base.clone()), unread) +} + +/// The options a dialog's `fields` hold, for [`fields_editor`]: `current` when they are valid, else +/// the values entered over the default preset's, with the keys of the values of the wrong type. +pub(crate) fn shown_options(fields: &Map, current: &Result) -> (FlattenOptions, Vec) { + match current { + Ok(o) => (o.clone(), Vec::new()), + Err(_) => entered_options(fields, &FlattenOptions::default()), + } +} + +/// [`options_editor`] on the option fields of a dialog: `o` and `unread` from [`shown_options`]. +/// Each option whose control was set is written into `fields`, also when it equals the value shown, +/// so that it replaces a value of the wrong type; the other fields stay as they were entered. With +/// `fixed_preserve`, the two Preserve switches show but can't be changed. +pub(crate) fn fields_editor( + ui: &mut egui::Ui, + id: &str, + fields: &mut Map, + o: &mut FlattenOptions, + unread: &[String], + fixed_preserve: bool, +) { + let set = editor(ui, id, o, true, fixed_preserve, unread); + let Ok(Value::Object(m)) = serde_json::to_value(&*o) else { return }; + for k in set { + if let Some(v) = m.get(k) { + fields.insert(k.into(), v.clone()); + } + } +} + /// The options the fields hold (a `preset` not loaded yet: its own). fn options(d: &Dialog, saved: &[FlattenerPreset]) -> Result { if d.str("preset") != d.str(APPLIED) { @@ -101,10 +148,9 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { save_row(app, ui, d); } ui.add_space(10.0); - let mut o = current.clone().unwrap_or_default(); - if options_editor(ui, "flatten-dialog", &mut o, true) { - put_options(&mut d.fields, &o); - } + // Values refused stay as entered, so that changing another option keeps them. + let (mut o, unread) = shown_options(&d.fields, ¤t); + fields_editor(ui, "flatten-dialog", &mut d.fields, &mut o, &unread, false); if let Err(e) = ¤t { ui.label(egui::RichText::new(e).color(Tokens::get(ui.ctx()).text_dim).size(11.5)); } @@ -180,8 +226,19 @@ const FIELD: f32 = 56.0; /// panel edit them: the raster/vector balance, both resolutions and the six switches. Returns true /// when one changed. pub(crate) fn options_editor(ui: &mut egui::Ui, id: &str, o: &mut FlattenOptions, enabled: bool) -> bool { - let t = Tokens::get(ui.ctx()); let before = o.clone(); + editor(ui, id, o, enabled, false, &[]); + *o != before +} + +/// The option controls, with the value fields of the options named in `unread` blank. With +/// `fixed_preserve`, Preserve Alpha Transparency and Preserve Overprints and Spot Colors show but +/// can't be changed (the file format or another control sets them). Returns the keys of the +/// options whose controls were set, also to the value they showed. +fn editor(ui: &mut egui::Ui, id: &str, o: &mut FlattenOptions, enabled: bool, fixed_preserve: bool, unread: &[String]) -> Vec<&'static str> { + let t = Tokens::get(ui.ctx()); + let mut set = Vec::new(); + let field_value = |key: &str, v: f64| (!unread.iter().any(|k| k == key)).then_some(v); let dim = |ui: &mut egui::Ui, s: &str| { ui.label(egui::RichText::new(tl!(s)).color(t.text_dim).size(11.5)); }; @@ -203,44 +260,51 @@ pub(crate) fn options_editor(ui: &mut egui::Ui, id: &str, o: &mut FlattenOptions ); if let Some(b) = x.map(|x| (x as f64 * 100.0).round()).or(keyed) { o.balance = b; + set.push("balance"); } dim(ui, tl!("Vectors")); + let value = field_value("balance", o.balance); if let Some(v) = - widgets::range_field_named(ui, (id, "balance"), Some(tl!("Raster/Vector Balance:")), o.balance, 0.0..=100.0, "", 0, FIELD - 12.0) + widgets::range_field_named(ui, (id, "balance"), Some(tl!("Raster/Vector Balance:")), value, 0.0..=100.0, "", 0, FIELD - 12.0) { o.balance = v; + set.push("balance"); } }); ui.add_space(4.0); egui::Grid::new((id, "resolutions")).num_columns(2).spacing([8.0, 4.0]).show(ui, |ui| { - for (label, key) in [(tl!("Line Art and Text Resolution:"), 0), (tl!("Gradient and Mesh Resolution:"), 1)] { + for (label, key, name) in + [(tl!("Line Art and Text Resolution:"), 0, "lineArtPpi"), (tl!("Gradient and Mesh Resolution:"), 1, "gradientPpi")] + { widgets::dim_label(ui, label); ui.horizontal(|ui| { let v = if key == 0 { &mut o.line_art_ppi } else { &mut o.gradient_ppi }; - if let Some(n) = widgets::range_field_named(ui, (id, key), Some(label), *v, 1.0..=2400.0, "", 0, FIELD) { + if let Some(n) = widgets::range_field_named(ui, (id, key), Some(label), field_value(name, *v), 1.0..=2400.0, "", 0, FIELD) { *v = n; + set.push(name); } - dim(ui, "ppi"); + dim(ui, super::ppi_suffix().trim()); }); ui.end_row(); } }); ui.add_space(4.0); - let switches: [(&str, &mut bool); 6] = [ - (tl!("Convert All Text to Outlines"), &mut o.text_to_outlines), - (tl!("Convert All Strokes to Outlines"), &mut o.strokes_to_outlines), - (tl!("Clip Complex Regions"), &mut o.clip_complex_regions), - (tl!("Anti-alias Rasters"), &mut o.anti_alias), - (tl!("Preserve Alpha Transparency"), &mut o.preserve_alpha), - (tl!("Preserve Overprints and Spot Colors"), &mut o.preserve_overprints), + let switches: [(&str, &mut bool, bool, &'static str); 6] = [ + (tl!("Convert All Text to Outlines"), &mut o.text_to_outlines, false, "textToOutlines"), + (tl!("Convert All Strokes to Outlines"), &mut o.strokes_to_outlines, false, "strokesToOutlines"), + (tl!("Clip Complex Regions"), &mut o.clip_complex_regions, false, "clipComplexRegions"), + (tl!("Anti-alias Rasters"), &mut o.anti_alias, false, "antiAlias"), + (tl!("Preserve Alpha Transparency"), &mut o.preserve_alpha, fixed_preserve, "preserveAlpha"), + (tl!("Preserve Overprints and Spot Colors"), &mut o.preserve_overprints, fixed_preserve, "preserveOverprints"), ]; - for (label, v) in switches { - if widgets::check(ui, label, *v, enabled) { + for (label, v, fixed, key) in switches { + if widgets::check(ui, label, *v, enabled && !fixed) { *v = !*v; + set.push(key); } } }); - *o != before + set } #[cfg(test)] @@ -394,4 +458,42 @@ mod tests { assert!(super::super::confirm(&mut app).unwrap_err().contains("resolutions")); assert!(app.ui.dialog.is_some()); } + + /// Changing a switch beside a value out of range keeps the values entered. + #[test] + fn a_switch_changed_beside_a_bad_value_keeps_the_values_entered() { + let mut app = scene(); + app.run("ui.flattenTransparencyDialog", json!({})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("balance".into(), json!(20)); + d.fields.insert("gradientPpi".into(), json!(9000)); + d.fields.insert("lineArtPpi".into(), json!("many")); + let mut f = super::super::tests_eps::Frames::new(); + let (_, at) = f.control(&mut app, "Convert All Text to Outlines", egui::accesskit::Role::CheckBox); + let before = app.ui.dialog.as_ref().unwrap().bool("textToOutlines"); + f.click(&mut app, at); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(d.bool("textToOutlines"), !before, "the switch changes"); + assert_eq!((d.f64("balance", 0.0), d.f64("gradientPpi", 0.0)), (20.0, 9000.0), "the other values stay as entered"); + assert_eq!(d.fields["lineArtPpi"], json!("many"), "a value of the wrong type stays to be refused"); + assert!(super::super::confirm(&mut app).is_err()); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("lineArtPpi".into(), json!(300)); + assert!(super::super::confirm(&mut app).unwrap_err().contains("resolutions")); + } + + /// A value of the wrong type shows blank, and typing the default preset's value into its + /// field replaces it, so OK flattens. + #[test] + fn the_default_value_typed_over_a_value_of_the_wrong_type_replaces_it() { + let mut app = scene(); + app.run("ui.flattenTransparencyDialog", json!({})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("lineArtPpi".into(), json!("many")); + let default = FlattenOptions::default().line_art_ppi; + let mut f = super::super::tests_eps::Frames::new(); + f.type_into(&mut app, "Line Art and Text Resolution:", &default.to_string()); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["lineArtPpi"], json!(default)); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none() && !transparent_left(&app)); + } } diff --git a/crates/ui-egui/src/dialogs/form.rs b/crates/ui-egui/src/dialogs/form.rs index d386c1f028..b46f35a79f 100644 --- a/crates/ui-egui/src/dialogs/form.rs +++ b/crates/ui-egui/src/dialogs/form.rs @@ -111,7 +111,7 @@ fn lengths(kind: &str) -> &'static [&'static str] { /// number: fields that ↑/↓ step by one (Shift: ten) and that do math, as the distances do. fn suffix(kind: &str, key: &str) -> Option<&'static str> { match (kind, key) { - ("rotate" | "shear" | "reflect" | "move" | "lineSegment", "angle") => Some("°"), + ("rotate" | "shear" | "reflect" | "move" | "lineSegment", "angle") | ("shear", "axisAngle") => Some("°"), ("scale", "sx" | "sy") | ("spiral", "decay") => Some("%"), _ => None, } @@ -138,6 +138,7 @@ fn order(kind: &str) -> &'static [&'static str] { "spiral" => &["radius", "decay", "segments"], "artboardOptions" => &["name", "width", "height"], "lineSegment" => &["length", "angle"], + "shear" => &["angle", "axis", "axisAngle"], _ => &[], } } @@ -163,8 +164,7 @@ fn choices(kind: &str, key: &str) -> Vec<(&'static str, &'static str)> { match (kind, key) { ("offsetPath", "joins") => vec![("miter", tl!("Miter")), ("round", tl!("Round")), ("bevel", tl!("Bevel"))], ("average", "axis") => vec![axis("horizontal", "Horizontal"), axis("vertical", "Vertical"), axis("both", "Both")], - ("reflect", "axis") => vec![axis("horizontal", "Horizontal"), axis("vertical", "Vertical"), axis("angle", "Angle")], - ("shear", "axis") => vec![axis("horizontal", "Horizontal"), axis("vertical", "Vertical")], + ("reflect" | "shear", "axis") => vec![axis("horizontal", "Horizontal"), axis("vertical", "Vertical"), axis("angle", "Angle")], _ => vec![], } } @@ -368,11 +368,19 @@ pub(super) fn grid_then(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit, more: imp if lengths.contains(&k.as_str()) { length_field(ui, d, &k, &humanized(&k), unit); } else if let Some(suffix) = suffix(&d.kind, &k) { - let row = row_label(ui, &humanized(&k)); + let label = match (d.kind.as_str(), k.as_str()) { + ("shear", "axisAngle") => tl!("Axis Angle").into(), + _ => humanized(&k), + }; + // Shear's Axis Angle is the axis while the Angle axis is chosen, and keeps its value otherwise. + let enabled = d.kind != "shear" || k != "axisAngle" || d.str("axis") == "angle"; + let row = row_label(ui, &label); ui.label_inputs_by(row.id, |ui| { - if let Some(v) = crate::widgets::plain_field(ui, ("dlg-num", &k), d.f64(&k, 0.0), suffix, 3, FIELD_W) { - d.fields.insert(k, json!(v)); - } + ui.add_enabled_ui(enabled, |ui| { + if let Some(v) = crate::widgets::plain_field(ui, ("dlg-num", &k), d.f64(&k, 0.0), suffix, 3, FIELD_W) { + d.fields.insert(k, json!(v)); + } + }); }); ui.end_row(); } else if let Some(ends) = skew_ends(&d.kind, &k) { @@ -503,7 +511,9 @@ pub(super) fn param_fields( } } Value::Number(n) => { - if let Some(x) = crate::widgets::plain_field(ui, ("fx-num", &k), n.as_f64().unwrap_or(0.0), "", 3, 140.0) { + // A resolution (Object › Rasterize's `ppi`) shows its unit in the UI language. + let suffix = if k == "ppi" { crate::i18n::fill_once(tl!("{n} ppi"), &[("n", "")]) } else { String::new() }; + if let Some(x) = crate::widgets::plain_field(ui, ("fx-num", &k), n.as_f64().unwrap_or(0.0), &suffix, 3, 140.0) { d.fields.insert(k.clone(), typed_number(x)); changed = true; } @@ -778,6 +788,12 @@ pub(crate) fn unit_suffix(unit: &str) -> String { if unit.is_empty() || unit.starts_with(['°', '%', '′', '″']) { unit.to_string() } else { format!(" {unit}") } } +/// What a resolution field shows after its value in the interface language: the `{n} ppi` row +/// without its number (" ppi", French " ppp"). +pub(crate) fn ppi_suffix() -> String { + crate::i18n::fill_once(tl!("{n} ppi"), &[("n", "")]) +} + /// A number of a list as [`value_field`] shows it: at most 4 decimals, without trailing zeros. fn number_text(x: f64) -> String { let s = format!("{x:.4}"); @@ -798,6 +814,7 @@ pub(crate) fn humanize(k: &str) -> String { } } match s.as_str() { + "Ppi" => "Resolution:".into(), "Dx" => "Horizontal".into(), "Dy" => "Vertical".into(), "Sx" => "Horizontal %".into(), @@ -828,15 +845,23 @@ pub(crate) fn humanize(k: &str) -> String { "Create" => "Create New Fields by:".into(), "Height Width" => "Height/Width:".into(), "Traps With Process Color" => "Traps with Process Color:".into(), + "Cols" => "Columns:".into(), + "Flip Cols" => "Flip Columns:".into(), _ => format!("{s}:"), } } -/// [`humanize`] translated where it is painted: the ":" stays outside the translated text. +/// A style attribute as the style dialogs list it: the [`humanized`] key, then its value. +pub(super) fn attribute_line(key: &str, value: &Value) -> String { + format!("{} {value}", humanized(key)) +} + +/// [`humanize`] translated where it is painted: the ":" stays outside the translated text and is +/// written as the UI language writes a label's colon ([`crate::i18n::colon`]). pub(super) fn humanized(k: &str) -> String { let h = humanize(k); match h.strip_suffix(':') { - Some(base) => format!("{}:", tl!(base)), + Some(base) => crate::i18n::colon(tl!(base)), None => tl!(&h).to_string(), } } @@ -1040,7 +1065,12 @@ fn preview_or_rollback(app: &mut crate::VectorcraftApp, d: &mut Dialog, label: & pub(super) fn preview_now(app: &mut crate::VectorcraftApp, d: &mut Dialog, label: &str, cmd: &str, params: Value) -> Option { let mut result = None; if d.fields.get(PREVIEWED) != Some(¶ms) || !app.session.in_interaction() { - let _ = app.session.begin_interaction(label); + // A failure to begin (typing that can't be kept) shows, and nothing previews on the + // interaction still in progress. + if let Err(e) = app.begin_interaction(label) { + app.status(e); + return None; + } match app.session.preview(cmd, ¶ms) { Ok(r) => { d.fields.remove(REFUSED); @@ -1154,6 +1184,27 @@ mod plugin_field_tests { assert_eq!([shown("mm"), shown("°"), shown("%"), shown("1/min"), shown("µm")], ["5 mm", "5°", "5%", "5 1/min", "5 µm"]); } + /// A resolution field's unit is the `{n} ppi` row without its number. + #[test] + fn the_ppi_unit_is_translated() { + assert_eq!(ppi_suffix(), " ppi"); + crate::i18n::set_current(crate::i18n::Lang::from_code("fr").unwrap()); + let fr = ppi_suffix(); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert_eq!(fr, " ppp"); + } + + /// [`ppi_suffix`] drops the number from the `{n} ppi` row, so every catalog writes the number + /// first and then a space before the unit. + #[test] + fn every_catalog_writes_the_ppi_unit_after_the_number() { + for lang in crate::i18n::Lang::all() { + let row = crate::i18n::tr(lang, "{n} ppi"); + let unit = row.strip_prefix("{n}").unwrap_or_default(); + assert!(unit.starts_with(char::is_whitespace) && !unit.trim().is_empty(), "{}: {row:?}", lang.code()); + } + } + #[test] fn number_lists_read_as_typed_within_their_limits() { let spec = ParamSpec::NumberList { min: 0.0, max: 360.0, default: vec![45.0], min_items: 1, max_items: 3 }; @@ -1167,6 +1218,98 @@ mod plugin_field_tests { } } +#[cfg(test)] +mod settled_typing_tests { + use super::*; + use vectorcraft_engine::{Session, ViewInfo}; + use vectorcraft_tools::{PointerEvent, PointerKind}; + + /// An app with Real-time Drawing off and " world" typed after "Hello", not yet applied → the + /// type's id. + fn typing(app: &mut crate::VectorcraftApp) -> u64 { + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + app.run("prefs.set", json!({"key": "realTimeDrawing", "value": false})).unwrap(); + let id = app.run("text.create", json!({"x": 100, "y": 100, "text": "Hello", "size": 20})).unwrap()["id"].as_u64().unwrap(); + let v = ViewInfo::default(); + app.session.select_tool("type", v).unwrap(); + let b = app.session.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap(); + for k in [PointerKind::Down, PointerKind::Up] { + app.session.pointer(&PointerEvent::new(k, b.x1 - 1.0, b.center().y), v).unwrap(); + } + app.session.tool_text(" world", v).unwrap(); + id + } + + fn plain(app: &crate::VectorcraftApp, id: u64) -> String { + match &app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind { + vectorcraft_doc::NodeKind::Text(t) => t.plain_text(), + _ => panic!("not text"), + } + } + + /// A dialog's preview while typing is in progress keeps the typing as its own step and starts + /// from it; the status bar shows the warning of the typing's preview that keeping it applied. + #[test] + fn a_dialog_preview_keeps_the_typing_and_shows_its_warning() { + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + let id = typing(&mut app); + assert_eq!(plain(&app, id), "Hello", "the typing waits"); + let steps = app.session.active().unwrap().history.undo.len(); + let mut d = Dialog::new("test", json!({})); + assert!(preview_now(&mut app, &mut d, "Fill Color", "paint.setFill", json!({"color": "#00a000"})).is_some()); + assert_eq!(plain(&app, id), "Hello world"); + let st = app.session.active().unwrap(); + assert_eq!(st.history.undo.len(), steps + 1, "the typing is a step of its own"); + assert_eq!(st.interaction.as_ref().map(|it| it.label.as_str()), Some("Fill Color")); + + // The typing's deferred preview warns that type is skipped (as Bloat does with type selected). + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let rect = app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 200, "height": 200})).unwrap(); + let text = app.run("text.create", json!({"x": 300, "y": 200, "text": "Hi"})).unwrap(); + app.run("select.set", json!({"ids": [rect["id"], text["id"]]})).unwrap(); + app.run("prefs.set", json!({"key": "realTimeDrawing", "value": false})).unwrap(); + app.session.begin_interaction("Typing").unwrap(); + let p = json!({"tool": "bloat", "points": [[290.0, 200.0]], "width": 200.0, "height": 200.0}); + app.session.doc_mut().unwrap().interaction.as_mut().unwrap().preview = Some(("object.liquify".into(), p)); + app.ui.status.clear(); + let mut d = Dialog::new("test", json!({})); + assert!(preview_now(&mut app, &mut d, "Fill Color", "paint.setFill", json!({"color": "#00a000"})).is_some()); + assert!(app.ui.status.contains("type"), "{:?}", app.ui.status); + } + + /// The font menus end the typing session before their preview: the typing Real-time Drawing + /// off left unapplied is kept as a step of its own. + #[test] + fn ending_typing_for_the_font_menus_keeps_the_typing() { + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + let id = typing(&mut app); + let steps = app.session.active().unwrap().history.undo.len(); + crate::panels::character::end_typing(&mut app); + assert_eq!(plain(&app, id), "Hello world"); + let st = app.session.active().unwrap(); + assert_eq!(st.history.undo.len(), steps + 1); + assert!(st.interaction.is_none()); + assert_ne!(app.session.tool_options().get("typing").and_then(Value::as_bool), Some(true), "the typing session is over"); + } + + /// A Character panel change keeps the typing first and acts on the characters the Type tool + /// selected in the typed text, not on a selection cut short to the text before the typing. + #[test] + fn a_character_change_acts_on_characters_selected_in_the_typing() { + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + let id = typing(&mut app); + app.session.set_tool_option("select", &json!({"start": 6, "end": 11})); + crate::panels::character::range_style(&mut app, json!({"underline": true})); + assert_eq!(plain(&app, id), "Hello world"); + let vectorcraft_doc::NodeKind::Text(t) = &app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind else { + panic!("not text") + }; + let underlined: String = t.runs.iter().filter(|r| r.style.underline).map(|r| r.text.as_str()).collect(); + assert_eq!(underlined, "world"); + } +} + #[cfg(test)] mod typed_number_tests { use super::*; diff --git a/crates/ui-egui/src/dialogs/freehand.rs b/crates/ui-egui/src/dialogs/freehand.rs index 93e3a1c2ff..78fdd8bdd1 100644 --- a/crates/ui-egui/src/dialogs/freehand.rs +++ b/crates/ui-egui/src/dialogs/freehand.rs @@ -21,7 +21,7 @@ use serde_json::{Map, Value, json}; use vectorcraft_brush::Variation; use super::document_setup::check; -use super::{DialogSpec, form, run_and_close}; +use super::{DialogSpec, form, set_tool_options_and_close}; use crate::state::Dialog; use crate::theme::Tokens; use crate::{VectorcraftApp, widgets}; @@ -334,22 +334,65 @@ fn body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { /// Side of the Blob Brush tip preview's square, in points. const TIP_PREVIEW: f32 = 64.0; -/// The Blob Brush's tip preview: a square with the tip at its Angle and Roundness and a line along -/// its long axis, and beside it three dabs of the tip, the middle one darker. A click or a drag in -/// the square points the Angle at the pointer and gives the square the keyboard focus; screen -/// readers get it as the Angle slider, and its keys step the Angle as a dialog slider's do -/// ([`widgets::stepped_area`]) within -180° to 180°. +/// Half the length of the Blob Brush tip in its preview, in points. +const TIP_LONG: f32 = 18.0; + +/// How far from a Roundness dot of the tip preview a press still takes the dot, in points. +const TIP_DOT_REACH: f32 = 8.0; + +/// The Blob Brush's tip preview: a square with the tip at its Angle and Roundness, a line with an +/// arrowhead along its long axis and a black dot at each end of its short axis, and beside it three +/// dabs of the tip, the middle one darker. A click or a drag that starts on a dot sets the +/// Roundness from the pointer's distance from the center along the short axis +/// ([`blob_tip_roundness_at`]) until the release, inside the square or out of it, and gives the +/// Roundness slider the keyboard focus. A click or a drag that starts anywhere else in the square +/// points the Angle at the pointer and gives the Angle slider the focus. Screen readers get the +/// square as the Angle slider and then the Roundness slider, and their keys step the Angle within +/// -180° to 180° and the Roundness within 0% to 100% as a dialog slider's do +/// ([`widgets::stepped_area`]). fn blob_tip_preview(ui: &mut egui::Ui, d: &mut Dialog) { let t = Tokens::get(ui.ctx()); let (rect, _) = ui.allocate_exact_size(egui::vec2(CONTENT_W, TIP_PREVIEW), egui::Sense::hover()); let square = egui::Rect::from_min_size(rect.min, egui::vec2(TIP_PREVIEW, TIP_PREVIEW)); + let center = square.center(); let response = ui.interact(square, ui.scope_id().with("freehand-tip-angle"), egui::Sense::click_and_drag()); + // Whether the press that started this click or drag was on a dot: it is kept until the release. + let on_dot = response.id.with("on-dot"); + let near_dot = |p: egui::Pos2, d: &Dialog| { + blob_tip_dots(center, d.f64("angle", 0.0), d.f64("roundness", 100.0)).iter().any(|dot| dot.distance(p) <= TIP_DOT_REACH) + }; + let mut started = ui.data(|m| m.get_temp::(on_dot)); + if started.is_none() && response.is_pointer_button_down_on() { + let pressed = ui.input(|i| i.pointer.press_origin()).is_some_and(|p| near_dot(p, d)); + ui.data_mut(|m| m.insert_temp(on_dot, pressed)); + started = Some(pressed); + } + // A click whose press and release came in the same frame: its press is among this frame's events. + let dot_drag = started.unwrap_or_else(|| { + let press = ui.input(|i| { + i.events.iter().rev().find_map(|e| match e { + egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, .. } => Some(*pos), + _ => None, + }) + }); + response.clicked() && press.is_some_and(|p| near_dot(p, d)) + }); + if !response.is_pointer_button_down_on() { + ui.data_mut(|m| m.remove_temp::(on_dot)); + } if let Some((p, _)) = widgets::pointer_phase(&response) { - let delta = p - square.center(); - if delta.length_sq() > 1.0 { + let delta = p - center; + if dot_drag { + d.fields.insert("roundness".into(), json!(blob_tip_roundness_at(delta, d.f64("angle", 0.0)))); + } else if delta.length_sq() > 1.0 { d.fields.insert("angle".into(), json!(f64::from((-delta.y).atan2(delta.x)).to_degrees().round())); } } + if dot_drag && response.is_pointer_button_down_on() { + ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing); + } else if response.hover_pos().is_some_and(|p| near_dot(p, d)) && !response.is_pointer_button_down_on() { + ui.ctx().set_cursor_icon(egui::CursorIcon::Grab); + } let painter = ui.painter_at(rect); painter.rect_filled(square, 2.0, t.input); painter.rect_stroke(square, 2.0, egui::Stroke::new(1.0, t.input_border), egui::StrokeKind::Inside); @@ -358,11 +401,17 @@ fn blob_tip_preview(ui: &mut egui::Ui, d: &mut Dialog) { if let Some(a) = widgets::stepped_area(ui, &response, tl!("Angle"), Some(shown)) { d.fields.insert("angle".into(), json!(a)); } - let a = d.f64("angle", 0.0).clamp(-180.0, 180.0).to_radians(); - // The long axis on screen (y down: a positive angle tilts it up to the right) and the short one. - let u = egui::vec2(a.cos() as f32, -a.sin() as f32); - let v = egui::vec2(-u.y, u.x); - let long = 18.0; + // The Roundness slider takes the focus and the keys only: the square's response reads the pointer. + let roundness = ui.interact(square, ui.scope_id().with("freehand-tip-roundness"), egui::Sense::focusable_noninteractive()); + if dot_drag && (response.drag_started() || response.clicked()) { + widgets::focus_by_pointer(ui, roundness.id); + } + let shown = widgets::SliderValue::field(d.f64("roundness", 100.0), 0.0..=100.0, "%", 0); + if let Some(r) = widgets::stepped_area(ui, &roundness, tl!("Roundness"), Some(shown)) { + d.fields.insert("roundness".into(), json!(r)); + } + let (u, v) = blob_tip_axes(d.f64("angle", 0.0)); + let long = TIP_LONG; let short = long * blob_tip_short_ratio(d.f64("roundness", 100.0)); let dab = |center: egui::Pos2, color: egui::Color32| { let points = (0..32) @@ -373,15 +422,44 @@ fn blob_tip_preview(ui: &mut egui::Ui, d: &mut Dialog) { .collect(); painter.add(egui::Shape::convex_polygon(points, color, egui::Stroke::NONE)); }; - let center = square.center(); dab(center, t.text); - painter.line_segment([center, center + u * 25.0], egui::Stroke::new(1.0, t.accent)); + painter.line_segment([center, center + u * 22.0], egui::Stroke::new(1.0, t.accent)); + let arrowhead = vec![center + u * 28.0, center + u * 22.0 + v * 3.0, center + u * 22.0 - v * 3.0]; + painter.add(egui::Shape::convex_polygon(arrowhead, t.accent, egui::Stroke::NONE)); + // Black with a white rim, so a dot shows on the tip and on the square in either theme. + for dot in blob_tip_dots(center, d.f64("angle", 0.0), d.f64("roundness", 100.0)) { + painter.circle(dot, 3.0, egui::Color32::BLACK, egui::Stroke::new(1.0, egui::Color32::WHITE)); + } let strip = square.right() + 2.5 * long; for (i, color) in [t.text_dim, t.text, t.text_dim].into_iter().enumerate() { dab(egui::pos2(strip + i as f32 * 1.5 * long, center.y), color); } } +/// The tip preview's long axis on screen at Angle `angle` (degrees, y down: a positive angle tilts +/// it up to the right), and its short axis. +fn blob_tip_axes(angle: f64) -> (egui::Vec2, egui::Vec2) { + let a = angle.clamp(-180.0, 180.0).to_radians(); + let u = egui::vec2(a.cos() as f32, -a.sin() as f32); + (u, egui::vec2(-u.y, u.x)) +} + +/// The two Roundness dots of the tip preview centered on `center`: the ends of the tip's short +/// axis at Angle `angle` and Roundness `roundness`. +fn blob_tip_dots(center: egui::Pos2, angle: f64, roundness: f64) -> [egui::Pos2; 2] { + let (_, v) = blob_tip_axes(angle); + let short = v * (TIP_LONG * blob_tip_short_ratio(roundness)); + [center + short, center - short] +} + +/// The Roundness, in whole percent from 0 to 100, that a dot of the tip preview dragged to `offset` +/// from the preview's center gives at Angle `angle`: the distance along the tip's short axis, on +/// either side of the center, as a percentage of half the tip's length. +fn blob_tip_roundness_at(offset: egui::Vec2, angle: f64) -> f64 { + let (_, v) = blob_tip_axes(angle); + (f64::from(offset.dot(v).abs() / TIP_LONG) * 100.0).round().clamp(0.0, 100.0) +} + /// The preview tip's short axis as a fraction of its long axis: Roundness in percent, with 0 /// percent drawn as 0.1 percent, the minimum the brush draws with. fn blob_tip_short_ratio(roundness: f64) -> f32 { @@ -391,7 +469,7 @@ fn blob_tip_short_ratio(roundness: f64) -> f32 { /// OK: set the tool's options. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let values: Map = KEYS.iter().filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone()))).collect(); - run_and_close(app, "tool.setOption", json!({ "tool": d.str("tool"), "values": values })) + set_tool_options_and_close(app, json!({ "tool": d.str("tool"), "values": values })) } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/freehand/tests.rs b/crates/ui-egui/src/dialogs/freehand/tests.rs index 3a73d6f3bb..6ec010a8bd 100644 --- a/crates/ui-egui/src/dialogs/freehand/tests.rs +++ b/crates/ui-egui/src/dialogs/freehand/tests.rs @@ -28,6 +28,24 @@ fn blob_tip_fields_confirm_and_cancel() { assert_eq!(app.session.tool_options_of("blobBrush")["roundness"], json!(0.0)); } +/// OK with a Fidelity the Smooth tool refuses shows the error and keeps the dialog open, with +/// nothing set; a Fidelity it takes then closes it. +#[test] +fn a_refused_fidelity_keeps_the_dialog_open() { + let mut app = app(); + app.run("tool.options", json!({"tool": "smooth"})).unwrap(); + let before = app.session.tool_options_of("smooth"); + app.ui.dialog.as_mut().unwrap().fields.insert("fidelity".into(), json!(0.01)); + let e = super::super::confirm(&mut app).unwrap_err(); + assert_eq!(e, "tool `smooth`: `fidelity` must be a number from 0.05 to 100"); + assert!(app.ui.dialog.is_some(), "the dialog stays open"); + assert_eq!(app.session.tool_options_of("smooth"), before); + app.ui.dialog.as_mut().unwrap().fields.insert("fidelity".into(), json!(5)); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.tool_options_of("smooth")["fidelity"], json!(5.0)); +} + #[test] fn the_tip_preview_is_as_flat_as_the_tip_the_brush_draws() { for roundness in [-5.0, 0.0, 0.05, 0.1, 1.0, 50.0, 100.0, 120.0] { @@ -36,6 +54,30 @@ fn the_tip_preview_is_as_flat_as_the_tip_the_brush_draws() { } } +/// A Roundness dot of the tip preview gives its distance from the center along the tip's short +/// axis as a percentage of half the tip's length, on either side and at any Angle: 0% at the +/// center, 100% at half the length and past it. A move along the long axis leaves it as it is, and +/// the dots drawn for a Roundness give that Roundness back. +#[test] +fn a_roundness_dot_sets_its_distance_along_the_short_axis() { + for angle in [0.0, 30.0, 90.0, -135.0, 180.0] { + let (u, v) = blob_tip_axes(angle); + for (along, want) in [(0.0, 0.0), (4.5, 25.0), (-9.0, 50.0), (18.0, 100.0), (-18.0, 100.0), (40.0, 100.0), (-400.0, 100.0)] { + for sideways in [0.0, 7.0, -30.0] { + assert_eq!(blob_tip_roundness_at(v * along + u * sideways, angle), want, "angle {angle}, {along} along, {sideways} sideways"); + } + } + let center = egui::pos2(32.0, 32.0); + for roundness in [0.0, 1.0, 37.0, 50.0, 99.0, 100.0] { + let [a, b] = blob_tip_dots(center, angle, roundness); + assert!(((a - center) + (b - center)).length() < 1e-4, "the dots face each other across the center"); + for dot in [a, b] { + assert_eq!(blob_tip_roundness_at(dot - center, angle), roundness, "angle {angle}"); + } + } + } +} + /// The labels the open dialog paints. fn painted(app: &mut VectorcraftApp) -> String { crate::tests_labels::painted_text(app, |app, ui| super::super::show(app, ui.ctx())) diff --git a/crates/ui-egui/src/dialogs/graph_data.rs b/crates/ui-egui/src/dialogs/graph_data.rs index 90cc7d9f55..ab46dbd82c 100644 --- a/crates/ui-egui/src/dialogs/graph_data.rs +++ b/crates/ui-egui/src/dialogs/graph_data.rs @@ -28,14 +28,13 @@ use crate::{VectorcraftApp, widgets}; pub const KIND: &str = "graphData"; /// The sheet's size: a row of labels over a graph's categories, a column of labels before its -/// series; the least it shows; a cell's longest text. +/// series; the least it shows. const MAX_ROWS: usize = MAX_GRAPH_CATEGORIES + 1; const MAX_COLS: usize = MAX_GRAPH_SERIES + 1; const MIN_ROWS: usize = 8; const MIN_COLS: usize = 6; -const MAX_CELL: usize = 256; /// The largest file Import Data reads, 1 MB (1,048,576 bytes), the same as Import Data Sets'. -const MAX_IMPORT_BYTES: usize = 1 << 20; +const MAX_IMPORT_BYTES: usize = vectorcraft_engine::cmd::MAX_GRAPH_DATA_FILE; /// The Cell Style limits (Adjust column width and decimal digits). const MAX_DECIMALS: u64 = 10; const MAX_WIDTH: u64 = 20; @@ -105,75 +104,25 @@ pub(crate) fn grid_from_data(v: &Value) -> Grid { grid } -/// The sheet as `graph.setData` takes it: series labels, category labels (none when all are blank) -/// and the values (a blank cell, or text that isn't a number, has none), without the empty rows and -/// columns past the data. +/// The sheet as `graph.setData` takes it ([`vectorcraft_engine::cmd::graph_data_from_grid`]), +/// which Import Data Sets' `%` columns also use. pub(crate) fn data_from_grid(grid: &Grid) -> Value { - let filled = |s: &String| !s.trim().is_empty(); - // At most a graph's rows and columns, as a file gives (`grid_from_text`): a grid sent by - // automation is any size, and the values are their product. - let grid = &grid[..grid.len().min(MAX_ROWS)]; - let rows = grid.iter().rposition(|r| r.iter().take(MAX_COLS).any(filled)).map_or(1, |i| i + 1).max(1); - let cols = grid.iter().take(rows).filter_map(|r| r.iter().take(MAX_COLS).rposition(filled)).max().map_or(1, |i| i + 1).max(1); - let label = |s: &str| { - let s = s.trim(); - // A label typed in straight quotes (as the CSV form takes a number as a label) is the text inside. - s.strip_prefix('"').and_then(|t| t.strip_suffix('"')).unwrap_or(s).to_string() - }; - // Series labels up to the last one given (none when all are blank). - let mut series: Vec = (1..cols).map(|c| label(&cell(grid, 0, c))).collect(); - while series.last().is_some_and(String::is_empty) { - series.pop(); - } - let mut categories: Vec = (1..rows).map(|r| label(&cell(grid, r, 0))).collect(); - if categories.iter().all(String::is_empty) { - categories.clear(); - } - let values: Vec> = (1..rows) - .map(|r| { - (1..cols) - .map(|c| { - let t = cell(grid, r, c); - t.trim().parse::().ok().filter(|v| v.is_finite() && !t.trim().starts_with('"')).map_or(Value::Null, |v| json!(v)) - }) - .collect() - }) - .collect(); - json!({ "series": series, "categories": categories, "rows": values }) + vectorcraft_engine::cmd::graph_data_from_grid(grid) } -/// Text from a file or the clipboard as cells: tab-separated when any line holds a tab, else -/// comma-separated (decided once, so a label with a comma in a tab-separated file stays whole), at -/// most a graph's rows and columns. +/// Text from a file or the clipboard as cells ([`vectorcraft_engine::cmd::graph_grid_from_text`]). pub(crate) fn grid_from_text(text: &str) -> Grid { - let sep = if text.contains('\t') { '\t' } else { ',' }; - text.lines().take(MAX_ROWS).map(|l| l.trim_end_matches('\r').split(sep).take(MAX_COLS).map(|c| clean(c.trim())).collect()).collect() + vectorcraft_engine::cmd::graph_grid_from_text(text) } -/// A text file's bytes as text: UTF-16 with its byte-order mark (spreadsheets' "Unicode Text"), -/// else UTF-16 without one when the bytes hold NUL bytes and Import Data Sets' rule gives them a -/// byte order ([`vectorcraft_engine::cmd::utf16_order_without_mark`]), else UTF-8 with or without -/// one. UTF-16 is read as it is after a byte-order mark: an odd last byte is left out, and an -/// unpaired surrogate reads as U+FFFD. +/// A text file's bytes as text ([`vectorcraft_engine::cmd::graph_data_text`]). pub(crate) fn decode(bytes: &[u8]) -> String { - let utf16 = |rest: &[u8], le: bool| { - let units: Vec = rest.as_chunks::<2>().0.iter().map(|p| if le { u16::from_le_bytes(*p) } else { u16::from_be_bytes(*p) }).collect(); - String::from_utf16_lossy(&units) - }; - match bytes { - [0xFF, 0xFE, rest @ ..] => utf16(rest, true), - [0xFE, 0xFF, rest @ ..] => utf16(rest, false), - [0xEF, 0xBB, 0xBF, rest @ ..] => String::from_utf8_lossy(rest).into_owned(), - _ => match bytes.contains(&0).then(|| vectorcraft_engine::cmd::utf16_order_without_mark(bytes)).flatten() { - Some(le) => utf16(bytes, le), - None => String::from_utf8_lossy(bytes).into_owned(), - }, - } + vectorcraft_engine::cmd::graph_data_text(bytes) } -/// A cell's text: one line (tabs and line breaks become spaces), at most MAX_CELL characters. +/// A cell's text ([`vectorcraft_engine::cmd::graph_cell_text`]). fn clean(s: &str) -> String { - s.chars().map(|c| if matches!(c, '\t' | '\r' | '\n') { ' ' } else { c }).take(MAX_CELL).collect() + vectorcraft_engine::cmd::graph_cell_text(s) } fn cell(grid: &[Vec], r: usize, c: usize) -> String { diff --git a/crates/ui-egui/src/dialogs/graph_type.rs b/crates/ui-egui/src/dialogs/graph_type.rs index 838ba066d9..766ae898ee 100644 --- a/crates/ui-egui/src/dialogs/graph_type.rs +++ b/crates/ui-egui/src/dialogs/graph_type.rs @@ -577,9 +577,9 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { false } -/// `text` with the colon of a field label. +/// `text` with the colon of a field label, as the UI language writes it. fn colon(text: &str) -> String { - format!("{text}:") + crate::i18n::colon(text) } /// A checkbox bound to `d.fields[key]`, dimmed while the type picked has no use for it. @@ -977,6 +977,22 @@ mod tests { assert!(app.ui.dialog.is_none()); } + /// Field labels end in the UI language's colon: in French a no-break space and a colon (#7991). + #[test] + fn field_labels_use_the_language_colon() { + let mut app = app_with_graph("column"); + crate::menus::invoke(&mut app, COMMAND, json!({})); + set(&mut app, PAGE, json!("valueAxis")); + let fr = crate::i18n::Lang::from_code("fr").unwrap(); + crate::i18n::set_current(fr); + let mut h = harness(app); + h.run_steps(3); + let want = format!("{}\u{a0}:", crate::i18n::tr(fr, "Suffix")); + let found = h.query_by_role_and_label(Role::TextInput, &want).is_some(); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert!(found, "a text field named {want:?}"); + } + /// A Type button changes the graph's type and keeps its data. #[test] fn a_type_button_changes_the_graph_type_and_keeps_its_data() { diff --git a/crates/ui-egui/src/dialogs/import_pdf.rs b/crates/ui-egui/src/dialogs/import_pdf.rs index 4ef8c925d8..bedd3387c2 100644 --- a/crates/ui-egui/src/dialogs/import_pdf.rs +++ b/crates/ui-egui/src/dialogs/import_pdf.rs @@ -3,7 +3,10 @@ //! //! Fields: `mode` (`open` | `place`), `name`, `path?`, `pageCount`, `page` (the page shown, and the //! one placed; 1-based), `allPages`, `range` and `linkPages` (open: Import PDF Pages as Links, for -//! a file read from a path and opened without a password), `cropTo` and `password`. `__locked` is set +//! a file read from a path and opened without a password; `null` until it is checked or cleared, +//! when it follows the pages picked: on for All, off for a range; picking the other of All and +//! Range sets it back to `null`; `__linkable` is false for a file `linkPages` does not take, such as +//! one over its size limit), `cropTo` and `password`. `__locked` is set //! until the password is accepted: OK then unlocks the file, and with `__passwordOnly` (Place with //! Show Import Options off) places its first page at once. `__place` keeps the other `file.place` //! params (Link, Template, `at`…). The file's bytes stay out of the fields, in @@ -144,10 +147,11 @@ pub fn offer(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option Option { } /// Can the pages open linked: the file was read from a path (a linked page is read from its -/// file again) and opens without a password (`document.open`'s `linkPages` refuses one). +/// file again), `document.open`'s `linkPages` takes its size, and it opens without a password +/// (`linkPages` refuses one). fn can_link(d: &Dialog) -> bool { - d.fields.get("path").and_then(Value::as_str).is_some() && password(d).is_none() + d.fields.get("path").and_then(Value::as_str).is_some() && d.bool("__linkable") && password(d).is_none() +} + +/// Import PDF Pages as Links as checked or cleared, or, when it is `null`, as the pages picked +/// default it: on for All, off for a range. +fn link_pages(d: &Dialog) -> bool { + d.fields.get("linkPages").and_then(Value::as_bool).unwrap_or_else(|| d.bool("allPages")) } /// Import PDF Pages as Links is checked, and can be. -fn links_on(d: &Dialog) -> bool { - d.bool("linkPages") && can_link(d) +pub(super) fn links_on(d: &Dialog) -> bool { + link_pages(d) && can_link(d) +} + +/// Picks All (true) or Range. A change of pick sets Import PDF Pages as Links back to that pick's +/// default; picking the one already picked keeps the box as it is. +fn pick_all_pages(d: &mut Dialog, all: bool) { + if d.bool("allPages") != all { + d.fields.insert("allPages".into(), json!(all)); + d.fields.insert("linkPages".into(), Value::Null); + } +} + +/// Records that `ui.dialog.set` sets `field` to `value`: a change of `allPages` sets Import PDF +/// Pages as Links back to its default, as a click on All or Range does. +pub(super) fn note_set(d: &mut Dialog, field: &str, value: &Value) { + if field == "allPages" + && let Some(all) = value.as_bool() + { + pick_all_pages(d, all); + } } /// OK: unlock the file with the password, else open the pages or place the page. @@ -330,20 +360,20 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { ui.label(egui::RichText::new(tl!("Pages")).color(t.text)); let all = d.bool("allPages"); if widgets::radio(ui, tl!("All"), all, true) { - d.fields.insert("allPages".into(), json!(true)); + pick_all_pages(d, true); } ui.horizontal(|ui| { if widgets::radio(ui, tl!("Range:"), !all, true) { - d.fields.insert("allPages".into(), json!(false)); + pick_all_pages(d, false); } if super::form::text_edit_named(ui, d, "range", tl!("Range:"), 90.0).gained_focus() { - d.fields.insert("allPages".into(), json!(false)); + pick_all_pages(d, false); } }); widgets::dim_label(ui, tl!("e.g. 1-3, 5")); ui.add_space(10.0); if widgets::check(ui, tl!("Import PDF pages as links"), links_on(d), can_link(d)) { - d.fields.insert("linkPages".into(), json!(!d.bool("linkPages"))); + d.fields.insert("linkPages".into(), json!(!link_pages(d))); } } }); diff --git a/crates/ui-egui/src/dialogs/justification.rs b/crates/ui-egui/src/dialogs/justification.rs index 168f5cfda1..c10e5b00bc 100644 --- a/crates/ui-egui/src/dialogs/justification.rs +++ b/crates/ui-egui/src/dialogs/justification.rs @@ -92,8 +92,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { // While typing, the dialog acts on the paragraphs of the text being edited. let mut targets = json!({}); let mut story = None; - if let Some((id, a, b)) = crate::panels::character::text_editing(app) { - crate::panels::character::end_typing(app); + if let Some((id, a, b)) = crate::panels::character::text_editing_kept(app)? { targets = json!({"ids": [id.0], "start": a, "end": b}); // After Select All in threaded text: every paragraph of every frame ([`params`]). story = crate::panels::character::text_story(app).map(|_| id.0); diff --git a/crates/ui-egui/src/dialogs/liquify.rs b/crates/ui-egui/src/dialogs/liquify.rs index 40aa677f17..18b8e48418 100644 --- a/crates/ui-egui/src/dialogs/liquify.rs +++ b/crates/ui-egui/src/dialogs/liquify.rs @@ -12,7 +12,7 @@ use serde_json::{Map, Value, json}; use vectorcraft_tools::distort::liquify::LiquifyKind; use super::document_setup::check; -use super::{DialogSpec, form, run_and_close}; +use super::{DialogSpec, form, set_tool_options_and_close}; use crate::state::Dialog; use crate::theme::Tokens; use crate::{VectorcraftApp, widgets}; @@ -145,7 +145,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { values.insert(key.into(), json!(d.f64(key, 0.0) / 100.0)); } } - run_and_close(app, "tool.setOption", json!({ "tool": kind(d).id(), "values": values })) + set_tool_options_and_close(app, json!({ "tool": kind(d).id(), "values": values })) } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/live_paint_bucket.rs b/crates/ui-egui/src/dialogs/live_paint_bucket.rs index f515c3d904..11bdcf5c41 100644 --- a/crates/ui-egui/src/dialogs/live_paint_bucket.rs +++ b/crates/ui-egui/src/dialogs/live_paint_bucket.rs @@ -15,7 +15,7 @@ use vectorcraft_doc::LAYER_COLORS; use vectorcraft_tools::builder::LP_BUCKET_WIDTH_RANGE; use super::tile_edge_color::{checked, resolve}; -use super::{DialogSpec, form, run_and_close}; +use super::{DialogSpec, form, set_tool_options_and_close}; use crate::state::Dialog; use crate::{VectorcraftApp, widgets}; @@ -86,7 +86,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { checked(&d.str("color"))?; } let values: Map = KEYS.iter().filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone()))).collect(); - run_and_close(app, "tool.setOption", json!({ "tool": TOOL, "values": values })) + set_tool_options_and_close(app, json!({ "tool": TOOL, "values": values })) } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/live_paint_selection.rs b/crates/ui-egui/src/dialogs/live_paint_selection.rs index a1a91ad2b7..95584c2f96 100644 --- a/crates/ui-egui/src/dialogs/live_paint_selection.rs +++ b/crates/ui-egui/src/dialogs/live_paint_selection.rs @@ -13,7 +13,7 @@ use vectorcraft_doc::LAYER_COLORS; use vectorcraft_tools::builder::LP_SELECT_WIDTH_RANGE; use super::tile_edge_color::{checked, resolve}; -use super::{DialogSpec, form, run_and_close}; +use super::{DialogSpec, form, set_tool_options_and_close}; use crate::state::Dialog; use crate::{VectorcraftApp, widgets}; @@ -80,7 +80,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { checked(&d.str("color"))?; } let values: Map = KEYS.iter().filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone()))).collect(); - run_and_close(app, "tool.setOption", json!({ "tool": TOOL, "values": values })) + set_tool_options_and_close(app, json!({ "tool": TOOL, "values": values })) } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/modal.rs b/crates/ui-egui/src/dialogs/modal.rs index f72383068e..c5acd64e18 100644 --- a/crates/ui-egui/src/dialogs/modal.rs +++ b/crates/ui-egui/src/dialogs/modal.rs @@ -2,8 +2,9 @@ //! window with no title bar that opens centred and moves by dragging its heading (the band from its //! top edge down to the heading), as a title bar would, showing the arrow until it is dragged. Where //! it was moved to stays, per window, for the session, and the window never leaves the screen. Rows -//! too many for the screen's height scroll inside it ([`scrolled_rows`]), so its heading and buttons -//! stay in view. +//! too many for the screen's height scroll inside it ([`scrolled_rows`], [`body_rows`]), so its +//! heading and buttons stay in view. A window without such rows that is still too tall or too wide +//! for the screen scrolls as a whole on that axis. use egui::{Id, Rect, Vec2}; @@ -25,6 +26,8 @@ pub(crate) fn show_at(ctx: &egui::Context, title: &str, id: Id, initial: Vec2 // Not focusable (`Sense::click()` is): Tab goes through the dialog's controls, not the backdrop. ui.allocate_rect(ctx.content_rect(), egui::Sense::CLICK); }); + let pass = ctx.cumulative_pass_nr(); + ctx.data_mut(|d| d.insert_temp(drawn_pass_id(), pass)); let shown = egui::Window::new(title) .id(id) .order(egui::Order::Foreground) @@ -33,17 +36,114 @@ pub(crate) fn show_at(ctx: &egui::Context, title: &str, id: Id, initial: Vec2 .title_bar(false) .anchor(egui::Align2::CENTER_CENTER, offset(ctx, id, initial)) .frame(egui::Frame::window(&ctx.global_style()).fill(t.panel).inner_margin(egui::Margin::same(margin))) - .show(ctx, add)?; - keep_rest(ctx, id, shown.response.rect.height()); + .show(ctx, |ui| { + // Just opened: what scrolls in the window starts at its top, wherever it was left when + // the window last closed. + if opened(ctx, id) { + ctx.data_mut(|m| { + m.insert_temp(id.with(TOP_ROWS_KEY), true); + m.insert_temp(id.with(TOP_WHOLE_KEY), true); + }); + } + // A window whose contents are wider than the screen has room for, or taller without + // rows that scroll ([`scrolled_rows`], [`body_rows`]), scrolls as a whole on that axis, + // so none of it is out of reach. The contents keep their ids whether the window scrolls + // or not, so a field being edited keeps its text when that changes. + let [wide, tall] = ctx.data(|m| m.get_temp::<[bool; 2]>(id.with(WHOLE_KEY))).unwrap_or_default(); + let scope = egui::UiBuilder::new().scope_id(id.with("modal-contents")); + let (r, contents) = if wide || tall { + let room = whole_room(ctx, margin); + let mut area = egui::ScrollArea::new([wide, tall]); + if ctx.data_mut(|m| m.remove_temp::(id.with(TOP_WHOLE_KEY))).is_some() { + area = area.scroll_offset(Vec2::ZERO); + } + let out = area + .id_salt("modal-whole") + .max_width(room.x) + .max_height(room.y) + .min_scrolled_width(room.x) + .min_scrolled_height(room.y) + .show(ui, |ui| ui.scope_builder(scope, add).inner); + (out.inner, out.content_size) + } else { + let r = ui.scope_builder(scope, add).inner; + (r, ui.min_rect().size()) + }; + ctx.data_mut(|m| m.insert_temp(id.with(CONTENTS_KEY), contents)); + r + })?; + keep_rest(ctx, id, shown.response.rect.height(), margin); shown.inner } +/// Mark the modal window drawn next in this pass as opened over the one drawn in the pass before, +/// which it hides until it closes and shows that one again (Import Shortcut Set over Keyboard +/// Shortcuts). The window under it keeps where it was scrolled to. +pub(crate) fn over_parent(ctx: &egui::Context) { + let pass = ctx.cumulative_pass_nr(); + ctx.data_mut(|m| m.insert_temp(Id::unique(OVER_KEY), pass)); +} + +/// Whether modal window `id`, drawn in this pass, opened in it: it was not drawn in the pass before, +/// and none of the windows drawn in the pass before was one opened over it ([`over_parent`]). +fn opened(ctx: &egui::Context, id: Id) -> bool { + let pass = ctx.cumulative_pass_nr(); + ctx.data_mut(|m| { + // The windows drawn in this pass so far and in the pass before. + let (at, now, prev) = m.get_temp::<(u64, Vec, Vec)>(Id::unique(LAST_KEY)).unwrap_or_default(); + let (mut now, prev) = if at == pass { + (now, prev) + } else if at.saturating_add(1) == pass { + (vec![], now) + } else { + (vec![], vec![]) + }; + let before: Vec = prev.iter().copied().filter(|&other| other != id).collect(); + now.push(id); + m.insert_temp(Id::unique(LAST_KEY), (pass, now, prev)); + let last = std::mem::replace(m.get_temp_mut_or(id.with(SHOWN_KEY), u64::MAX), pass); + if last != u64::MAX && last.saturating_add(1) >= pass { + return false; + } + // Shown again as the window opened over it closed. + if before.iter().any(|over| m.get_temp::(over.with(HOLDS_KEY)) == Some(id)) { + return false; + } + // Opened over the window drawn last in the pass before, it holds that one; otherwise none. + match before.last().copied().filter(|_| m.get_temp::(Id::unique(OVER_KEY)) == Some(pass)) { + Some(under) => { + m.insert_temp(id.with(HOLDS_KEY), under); + } + None => { + m.remove::(id.with(HOLDS_KEY)); + } + } + true + }) +} + +/// The room for the contents of a modal window with `margin` inside its frame. +fn whole_room(ctx: &egui::Context, margin: i8) -> Vec2 { + (ctx.content_rect().size() - Vec2::splat(2.0 * (super::EDGE_GAP + f32::from(margin)))).max(Vec2::ZERO) +} + /// The layer of the backdrop behind a modal dialog window, which takes the clicks the rest of /// the app would get. pub(crate) fn backdrop() -> egui::LayerId { egui::LayerId::new(egui::Order::Middle, Id::unique("modal-dim")) } +/// The key of the pass in which [`show_at`] last drew a modal window. +fn drawn_pass_id() -> Id { + Id::unique("modal-drawn-pass") +} + +/// Whether [`show_at`] drew a modal window in this pass. Unlike the backdrop's visibility, which +/// also counts the last pass, it is false in the pass after the window closes. +pub(crate) fn drawn_this_pass(ctx: &egui::Context) -> bool { + ctx.data(|d| d.get_temp::(drawn_pass_id())) == Some(ctx.cumulative_pass_nr()) +} + /// The dialog's heading, which also moves the window ([`drag_band`]). pub(crate) fn heading(ui: &mut egui::Ui, text: &str) { let t = Tokens::get(ui.ctx()); @@ -73,34 +173,158 @@ pub(super) fn handle(id: Id) -> Id { id.with("modal-drag") } -/// Under a modal window's id: how tall its [`scrolled_rows`] were drawn this frame, and how tall -/// the rest of it was when last drawn. +/// Under a modal window's id: how tall its [`scrolled_rows`] (or [`body_rows`]) were drawn this +/// frame, and how tall the rest of it was when last drawn. const ROWS_KEY: &str = "modal-rows"; const REST_KEY: &str = "modal-rest"; +/// Under a modal window's id: its contents drew [`scrolled_rows`] of their own or fit themselves to +/// the screen ([`fits_itself`]) this frame (`OWN_ROWS_KEY`), or last frame (`OWN_BEFORE_KEY`). +const OWN_ROWS_KEY: &str = "modal-own-rows"; +const OWN_BEFORE_KEY: &str = "modal-own-before"; +/// Under a modal window's id: how tall its [`body_rows`] would be without scrolling, this frame. +const BODY_KEY: &str = "modal-body"; +/// Under a modal window's id: how large its contents would be without scrolling as a whole, this +/// frame. +const CONTENTS_KEY: &str = "modal-contents"; +/// Under a modal window's id, for the next frame: its [`body_rows`] scroll (`TALL_KEY`), and on +/// which axes ([wide, tall]) it scrolls as a whole (`WHOLE_KEY`). +const TALL_KEY: &str = "modal-tall"; +const WHOLE_KEY: &str = "modal-whole"; +/// Under a modal window's id: the pass it was last drawn in (`SHOWN_KEY`), and, since it opened, +/// its rows (`TOP_ROWS_KEY`) or the window as a whole (`TOP_WHOLE_KEY`) have not scrolled yet, so +/// they start at the top when they first do. +const SHOWN_KEY: &str = "modal-shown"; +const TOP_ROWS_KEY: &str = "modal-top-rows"; +const TOP_WHOLE_KEY: &str = "modal-top-whole"; +/// For all modal windows: the pass the last one was drawn in, the ids of those drawn in that pass +/// and of those drawn in the pass before it (`LAST_KEY`), and the pass +/// in which the window drawn next was marked as opened over another ([`over_parent`], `OVER_KEY`). +/// Under a modal window's id: the window it was opened over and hides (`HOLDS_KEY`). +const LAST_KEY: &str = "modal-last"; +const OVER_KEY: &str = "modal-over"; +const HOLDS_KEY: &str = "modal-holds"; /// Rows of the modal window `ui` is in (one list of them per window) that scroll if the window /// would be taller than the screen. Their height is the screen's less the rest of the window as /// last drawn (a frame late, as only the drawn window knows its height). /// Rows that fit are as tall as they are. pub(crate) fn scrolled_rows(ui: &mut egui::Ui, salt: impl egui::AsIdSalt, add: impl FnOnce(&mut egui::Ui) -> R) -> R { - let id = ui.layer_id().id; - let rest = ui.ctx().data(|m| m.get_temp::(id.with(REST_KEY))).unwrap_or(0.0); - let room = (ui.ctx().content_rect().height() - rest - 2.0 * super::EDGE_GAP).max(0.0); - // As tall as the room at once: by itself a scroll area grows a frame at a time with the window. - let rows = ui.scope(|ui| egui::ScrollArea::vertical().id_salt(salt).max_height(room).min_scrolled_height(room).show(ui, add).inner); - ui.ctx().data_mut(|m| m.insert_temp(id.with(ROWS_KEY), rows.response.rect.height())); - rows.inner + fits_itself(ui); + let (r, drawn, _) = rows(ui, salt, true, add); + ui.ctx().data_mut(|m| m.insert_temp(ui.layer_id().id.with(ROWS_KEY), drawn)); + r } -/// After modal window `id` is drawn `height` tall: keep the height of all of it but its -/// [`scrolled_rows`] for the next frame. If the rows were sized by a different one (the window just -/// opened, or what is around them changed), the next frame is drawn at once, for the rows to fit -/// without waiting for input. -fn keep_rest(ctx: &egui::Context, id: Id, height: f32) { - let Some(rows) = ctx.data_mut(|m| m.remove_temp::(id.with(ROWS_KEY))) else { return }; - let rest = (height - rows).max(0.0); - let used = ctx.data_mut(|m| std::mem::replace(m.get_temp_mut_or(id.with(REST_KEY), 0.0), rest)); - if (used - rest).abs() > 0.5 { +/// Mark the contents of the modal window `ui` is in as fitting themselves to the screen (sizing +/// what scrolls in them from the screen's height), so neither [`body_rows`] nor the window +/// scroll them again. +pub(crate) fn fits_itself(ui: &egui::Ui) { + ui.ctx().data_mut(|m| m.insert_temp(ui.layer_id().id.with(OWN_ROWS_KEY), true)); +} + +/// The body of a shared dialog window. While the window would be taller than the screen has room +/// for, the body scrolls as [`scrolled_rows`] do, so the heading and the buttons stay in view; +/// otherwise it is drawn as it is. A body that fits itself ([`fits_itself`]) is drawn as it is. +pub(crate) fn body_rows(ui: &mut egui::Ui, add: impl FnOnce(&mut egui::Ui) -> R) -> R { + let id = ui.layer_id().id; + let (r, drawn, body) = rows(ui, "dialog-body", body_scrolls(ui.ctx(), id), add); + if !ui.ctx().data(|m| m.get_temp::(id.with(OWN_ROWS_KEY))).unwrap_or(false) { + ui.ctx().data_mut(|m| { + m.insert_temp(id.with(ROWS_KEY), drawn); + m.insert_temp(id.with(BODY_KEY), body); + }); + } + r +} + +/// Whether the [`body_rows`] of modal window `id` scroll in this frame. +fn body_scrolls(ctx: &egui::Context, id: Id) -> bool { + let own = ctx.data(|m| m.get_temp::(id.with(OWN_BEFORE_KEY))).unwrap_or(false); + !own && ctx.data(|m| m.get_temp::(id.with(TALL_KEY))).unwrap_or(false) +} + +/// While the [`body_rows`] of the modal window `ui` is in scroll: how tall they are drawn. +pub(crate) fn body_view(ui: &egui::Ui) -> Option { + let id = ui.layer_id().id; + body_scrolls(ui.ctx(), id).then(|| rows_room(ui.ctx(), id)) +} + +/// How modal window `id` scrolls: while its [`body_rows`] scroll, how tall they are drawn; and on +/// which axes ([wide, tall]) the window scrolls as a whole. +#[cfg(test)] +pub(crate) fn scrolling(ctx: &egui::Context, id: Id) -> (Option, [bool; 2]) { + let body = body_scrolls(ctx, id).then(|| rows_room(ctx, id)); + (body, ctx.data(|m| m.get_temp::<[bool; 2]>(id.with(WHOLE_KEY))).unwrap_or_default()) +} + +/// The height of a list `height` tall at most, with a scroll bar of its own, in the [`body_rows`] +/// of the modal window `ui` is in: while the body scrolls, no taller than the body is drawn, so +/// the list and its bar can be scrolled into view whole. +pub(crate) fn list_height(ui: &egui::Ui, height: f32) -> f32 { + body_view(ui).map_or(height, |view| view.min(height)) +} + +/// The height rows that scroll in modal window `id` are drawn: the screen's less the rest of the +/// window as last drawn. +fn rows_room(ctx: &egui::Context, id: Id) -> f32 { + let rest = ctx.data(|m| m.get_temp::(id.with(REST_KEY))).unwrap_or(0.0); + (ctx.content_rect().height() - rest - 2.0 * super::EDGE_GAP).max(0.0) +} + +/// [`scrolled_rows`] without marking the window's body as having rows of its own or keeping their +/// height. Also returns how tall the rows were drawn and how tall they would be without scrolling. +/// Rows that do not `scroll` are as tall as they are, with no +/// scroll area (which would take the scroll requests of their fields from the window's). The rows +/// keep their ids either way, so a field being edited keeps its text when they start or stop +/// scrolling. +fn rows(ui: &mut egui::Ui, salt: impl egui::AsIdSalt, scroll: bool, add: impl FnOnce(&mut egui::Ui) -> R) -> (R, f32, f32) { + let id = ui.layer_id().id; + let room = rows_room(ui.ctx(), id); + let scope = egui::UiBuilder::new().scope_id(ui.make_persistent_id(&salt).with("modal-rows")); + if !scroll { + let rows = ui.scope_builder(scope, add); + let height = rows.response.rect.height(); + return (rows.inner, height, height); + } + // As tall as the room at once: by itself a scroll area grows a frame at a time with the window. + let mut area = egui::ScrollArea::vertical().id_salt(salt).max_height(room).min_scrolled_height(room); + if ui.ctx().data_mut(|m| m.remove_temp::(id.with(TOP_ROWS_KEY))).is_some() { + area = area.scroll_offset(Vec2::ZERO); + } + let rows = ui.scope(|ui| area.show(ui, |ui| ui.scope_builder(scope, add).inner)); + (rows.inner.inner, rows.response.rect.height(), rows.inner.content_size.y) +} + +/// After modal window `id` (with `margin` inside its frame) is drawn `height` tall: keep the height +/// of all of it but its [`scrolled_rows`] for the next frame. If the rows were sized by a different +/// one (the window just opened, or what is around them changed), the next frame is drawn at once, +/// for the rows to fit without waiting for input. From the next frame on, [`body_rows`] scroll +/// while the window would be taller than the screen has room for without them scrolling; a window +/// without rows that scroll scrolls as a whole while its contents would be taller than the room, +/// and any window scrolls sideways while its contents would be wider. +fn keep_rest(ctx: &egui::Context, id: Id, height: f32, margin: i8) { + let rows = ctx.data_mut(|m| m.remove_temp::(id.with(ROWS_KEY))); + let body = ctx.data_mut(|m| m.remove_temp::(id.with(BODY_KEY))); + let contents = ctx.data_mut(|m| m.remove_temp::(id.with(CONTENTS_KEY))).unwrap_or_default(); + let own = ctx.data_mut(|m| m.remove_temp::(id.with(OWN_ROWS_KEY))).unwrap_or(false); + ctx.data_mut(|m| m.insert_temp(id.with(OWN_BEFORE_KEY), own)); + let room = whole_room(ctx, margin); + let screen = ctx.content_rect().height() - 2.0 * super::EDGE_GAP; + let tall = match (rows, body) { + (Some(rows), Some(body)) if !own => height - rows + body > screen + 0.5, + _ => false, + }; + // A window that fits itself to the screen's height can still be too wide for it. + let whole = [contents.x > room.x + 0.5, !own && rows.is_none() && contents.y > room.y + 0.5]; + let was_tall = ctx.data_mut(|m| std::mem::replace(m.get_temp_mut_or(id.with(TALL_KEY), false), tall)); + let was_whole = ctx.data_mut(|m| std::mem::replace(m.get_temp_mut_or(id.with(WHOLE_KEY), [false; 2]), whole)); + let mut repaint = tall != was_tall || whole != was_whole; + if let Some(rows) = rows { + let rest = (height - rows).max(0.0); + let used = ctx.data_mut(|m| std::mem::replace(m.get_temp_mut_or(id.with(REST_KEY), 0.0), rest)); + repaint |= (used - rest).abs() > 0.5; + } + if repaint { ctx.request_repaint(); } } @@ -146,4 +370,159 @@ mod tests { // Larger than the screen: its top left stays in view. assert_eq!(on_screen(r(-10.0, -10.0, 900.0, 700.0), screen), r(0.0, 0.0, 900.0, 700.0)); } + + /// Draw `frames` frames of a 400×300 screen from `time`, the first with `events`, with the modal + /// windows named in `open` open, in that order: the first a heading and 60 rows, in + /// [`scrolled_rows`] when `in_rows`, and any other a short alert. A window named "over …" is + /// opened over the one before it ([`over_parent`]). Returns whether a first row could be seen in + /// the last frame (inside the screen and its clip). + fn first_row_seen(ctx: &egui::Context, open: &[&str], in_rows: bool, events: Vec, time: &mut f64, frames: usize) -> bool { + let screen = Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(400.0, 300.0)); + let add = |ui: &mut egui::Ui| { + for i in 0..60 { + ui.label(format!("Row {i}")); + } + }; + let mut events = Some(events); + let mut seen = false; + for _ in 0..frames { + *time += 1.0 / 60.0; + let input = + egui::RawInput { screen_rect: Some(screen), events: events.take().unwrap_or_default(), time: Some(*time), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| { + for (i, &name) in open.iter().enumerate() { + if name.starts_with("over ") { + over_parent(ui.ctx()); + } + show(ui.ctx(), name, Id::unique(("modal-reopen-test", name)), 0.0, 8, |ui| { + heading(ui, "Top"); + if i > 0 { + ui.label("Alert"); + } else if in_rows { + scrolled_rows(ui, "rows", add); + } else { + add(ui); + } + }); + } + }); + out.textures_delta.clear(); + seen = out.shapes.iter().any(|c| match &c.shape { + egui::Shape::Text(t) => { + let r = t.visual_bounding_rect(); + t.galley.text() == "Row 0" && screen.contains_rect(r) && c.clip_rect.contains_rect(r) + } + _ => false, + }); + } + seen + } + + /// A wheel turn far down, at the middle of the 400×300 screen. + fn wheel_down() -> Vec { + let wheel = egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, -3000.0), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Unknown, + modifiers: egui::Modifiers::NONE, + }; + vec![egui::Event::PointerMoved(egui::pos2(200.0, 200.0)), wheel] + } + + #[test] + fn a_window_that_scrolled_opens_again_at_its_top() { + for in_rows in [false, true] { + let ctx = egui::Context::default(); + crate::theme::apply(&ctx, Default::default()); + let mut time = 0.0; + assert!(first_row_seen(&ctx, &["A"], in_rows, vec![], &mut time, 4), "rows {in_rows}: the window opens at its top"); + assert!(!first_row_seen(&ctx, &["A"], in_rows, wheel_down(), &mut time, 60), "rows {in_rows}: the wheel scrolls the first row away"); + first_row_seen(&ctx, &[], in_rows, vec![], &mut time, 2); + assert!(first_row_seen(&ctx, &["A"], in_rows, vec![], &mut time, 4), "rows {in_rows}: opened again, the window starts at its top"); + } + } + + #[test] + fn a_window_hidden_under_one_opened_over_it_keeps_its_scroll() { + // As Keyboard Shortcuts is while Import Shortcut Set is open over it: it is not drawn, but it + // did not close. A window that another replaced did close. Either may have shown an alert + // of its own, drawn after it in the same passes. + let others: [(&[&str], bool); 4] = [(&["over B"], true), (&["over B", "Alert"], true), (&["C"], false), (&["C", "Alert"], false)]; + let mut wrong = vec![]; + for in_rows in [false, true] { + for (other, kept) in others { + let ctx = egui::Context::default(); + crate::theme::apply(&ctx, Default::default()); + let mut time = 0.0; + first_row_seen(&ctx, &["A"], in_rows, vec![], &mut time, 4); + if first_row_seen(&ctx, &["A"], in_rows, wheel_down(), &mut time, 60) { + wrong.push(format!("rows {in_rows}: the wheel does not scroll A")); + } + if !first_row_seen(&ctx, other, in_rows, vec![], &mut time, 4) { + wrong.push(format!("rows {in_rows}: {other:?} does not open at its top")); + } + if first_row_seen(&ctx, &["A"], in_rows, vec![], &mut time, 4) == kept { + wrong.push(format!("rows {in_rows}: after {other:?}, A {} where it was scrolled to", if kept { "is not" } else { "is still" })); + } + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); + } + + #[test] + fn a_field_keeps_its_text_and_focus_when_the_window_starts_or_stops_scrolling() { + // A field's edit state and the keyboard focus are kept under its id, so typing goes on into + // the same field when the screen's height changes whether the body or the window scrolls. + let mut wrong = vec![]; + for in_body in [false, true] { + let ctx = egui::Context::default(); + crate::theme::apply(&ctx, Default::default()); + let window = Id::unique("modal-field-id-test"); + let mut text = String::from("12"); + let mut time = 0.0; + let mut field = None; + let mut focus_given = false; + let mut seen = vec![]; + for (height, typed) in [(900.0, "3"), (300.0, "4"), (900.0, "5")] { + let screen = Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(400.0, height)); + for i in 0..4 { + time += 1.0 / 60.0; + // Typed once the window has settled at this height. + let events = if i == 3 { vec![egui::Event::Text(typed.into())] } else { vec![] }; + let input = egui::RawInput { screen_rect: Some(screen), events, time: Some(time), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| { + show(ui.ctx(), "Test", window, 0.0, 8, |ui| { + heading(ui, "Top"); + let mut add = |ui: &mut egui::Ui| { + let r = ui.text_edit_singleline(&mut text); + for i in 0..30 { + ui.label(format!("Row {i}")); + } + r.id + }; + field = Some(if in_body { body_rows(ui, add) } else { add(ui) }); + }); + }); + out.textures_delta.clear(); + // The field is given the focus once, after the first frame; a resize that took it + // away would leave the keys typed after it untaken. + if let Some(id) = field.filter(|_| !focus_given) { + ctx.memory_mut(|m| m.request_focus(id)); + focus_given = true; + } + } + let key = if in_body { window.with(TALL_KEY) } else { window.with(WHOLE_KEY) }; + let scrolls = ctx.data(|m| m.get_temp::(key).unwrap_or(false) || m.get_temp::<[bool; 2]>(key).is_some_and(|a| a[1])); + seen.push((scrolls, text.clone(), ctx.memory(|m| m.focused()) == field && field.is_some())); + } + let want = [(false, "123", true), (true, "1234", true), (false, "12345", true)]; + let want: Vec<_> = want.iter().map(|&(s, t, f)| (s, t.to_string(), f)).collect(); + if seen != want { + wrong.push((in_body, seen)); + } + } + // Only the short screen scrolls, and the field keeps its focus and takes each key. + assert_eq!(wrong, vec![], "(body, [(scrolls, text, focused)]) that went wrong"); + } } diff --git a/crates/ui-egui/src/dialogs/navigator_panel_options.rs b/crates/ui-egui/src/dialogs/navigator_panel_options.rs index c3582ae59a..c0988ec548 100644 --- a/crates/ui-egui/src/dialogs/navigator_panel_options.rs +++ b/crates/ui-egui/src/dialogs/navigator_panel_options.rs @@ -85,7 +85,7 @@ mod tests { d.fields.insert("solidDashes".into(), json!(solid)); super::super::confirm(app) }; - assert_eq!(set(&mut app, "Green", true).unwrap(), json!({"color": "#4fff4f", "solidDashes": true})); + assert_eq!(set(&mut app, "Green", true).unwrap(), json!({"color": "#4fff4f", "solidDashes": true, "viewArtboardContentsOnly": true})); assert!(app.ui.dialog.is_none()); app.run("ui.navigatorPanelOptions", json!({})).unwrap(); set(&mut app, "#0000FF", true).unwrap(); diff --git a/crates/ui-egui/src/dialogs/new_swatch.rs b/crates/ui-egui/src/dialogs/new_swatch.rs index 5b6c5b117c..ec2ab707d4 100644 --- a/crates/ui-egui/src/dialogs/new_swatch.rs +++ b/crates/ui-egui/src/dialogs/new_swatch.rs @@ -1,5 +1,5 @@ -//! New Swatch: the Swatch Options fields (name, colour type, Global, mode, sliders and hex) -//! prefilled from the active fill or stroke; a gradient, a pattern or a tint of a global colour +//! New Swatch: the Swatch Options fields (name, colour type, Global, mode, sliders, hex and the +//! colour warnings) prefilled from the active fill or stroke; a gradient, a pattern or a tint of a global colour //! (saved as a tint swatch, "Name 40%") only takes a name. OK runs `swatch.new`. //! //! Fields: `name`, `spot`, `global`, `mode` and `color` as in Swatch Options, `group` (the colour @@ -45,7 +45,7 @@ pub fn open(app: &mut VectorcraftApp, spot: bool, global: bool, group: Option<&s fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { if d.fields.contains_key("__paint") { grid(ui, |ui| name_row(ui, d)); - } else if editor(ui, d) + } else if editor(app, ui, d) && d.str("name") == d.str("__auto") && let Some(st) = app.session.active() { @@ -87,6 +87,30 @@ mod tests { assert_eq!(params(&d), json!({"name": "Dots", "pattern": "Dots"})); } + #[test] + fn a_warning_corrects_the_new_colour_only_until_ok() { + use super::super::swatch_options::tests::{click_at, context, settled, warning_rows}; + let (ctx, mut app) = (context(), VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default())); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + app.run("paint.setFill", json!({"color": "#0000fe"})).unwrap(); + let count = |app: &VectorcraftApp| app.session.active().unwrap().doc.swatches_iter().count(); + let before = count(&app); + open(&mut app, false, false, None).unwrap(); + let rows = warning_rows(&settled(&ctx, &mut app)); + assert_eq!(rows.len(), 2, "out of gamut and out of web colors"); + click_at(&ctx, &mut app, rows[1].1.center()); + let d = app.ui.dialog.clone().unwrap(); + assert_eq!((color_of(&d).to_hex(), d.str("mode")), ("#0000ff".to_string(), "rgb".to_string())); + assert_eq!(count(&app), before, "no swatch before OK"); + assert_eq!(warning_rows(&settled(&ctx, &mut app)).len(), 1, "the web warning is gone"); + let name = app.ui.dialog.as_ref().unwrap().str("name"); + super::super::confirm(&mut app).unwrap(); + assert_eq!(app.session.active().unwrap().doc.swatch(&name).and_then(|s| s.paint.color()).map(|c| c.to_hex()), Some("#0000ff".into())); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(count(&app), before, "one undo step"); + } + #[test] fn a_tint_opens_as_a_named_tint_swatch() { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); diff --git a/crates/ui-egui/src/dialogs/new_text_style.rs b/crates/ui-egui/src/dialogs/new_text_style.rs index 4978a6a1f6..82f0c7d78b 100644 --- a/crates/ui-egui/src/dialogs/new_text_style.rs +++ b/crates/ui-egui/src/dialogs/new_text_style.rs @@ -77,7 +77,7 @@ fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { }); if let Ok(attrs) = super::char_style_options::edited_attrs(d) { for (key, value) in attrs { - ui.label(format!("{}: {}", super::humanize(&key), value)); + ui.label(super::form::attribute_line(&key, &value)); } } }); diff --git a/crates/ui-egui/src/dialogs/objects_on_path_options.rs b/crates/ui-egui/src/dialogs/objects_on_path_options.rs index 4726e0762a..71aff096fb 100644 --- a/crates/ui-egui/src/dialogs/objects_on_path_options.rs +++ b/crates/ui-egui/src/dialogs/objects_on_path_options.rs @@ -11,7 +11,7 @@ use serde_json::{Map, Value, json}; use vectorcraft_doc::objects_on_path::CENTER; -use super::{DialogSpec, run_and_close}; +use super::{DialogSpec, set_tool_options_and_close}; use crate::state::Dialog; use crate::{VectorcraftApp, widgets}; @@ -73,7 +73,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { /// Save: set the tool's Pivot and Rotate. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let values: Map = ["pivot", "rotate"].iter().filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone()))).collect(); - run_and_close(app, "tool.setOption", json!({ "tool": TOOL, "values": values })) + set_tool_options_and_close(app, json!({ "tool": TOOL, "values": values })) } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/para_style_options.rs b/crates/ui-egui/src/dialogs/para_style_options.rs index d63d43be89..b64815b8dd 100644 --- a/crates/ui-egui/src/dialogs/para_style_options.rs +++ b/crates/ui-egui/src/dialogs/para_style_options.rs @@ -952,7 +952,7 @@ pub(crate) fn general_body(ui: &mut egui::Ui, d: &mut Dialog) { ui.separator(); if let Ok(attrs) = edited_attrs(d) { for (key, value) in attrs { - ui.label(format!("{}: {}", super::humanize(&key), value)); + ui.label(super::form::attribute_line(&key, &value)); } } } @@ -982,6 +982,7 @@ fn content_id(ui: &egui::Ui) -> egui::Id { /// (as drawn last frame). The section list stays put while the content scrolls. Returns whether /// the dialog asks to be canceled (never: Cancel comes from the button row in `dialogs::show`). fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + super::modal::fits_itself(ui); let window = ui.ctx().memory(|m| m.area_rect(ui.layer_id().id)).map_or(0.0, |r| r.height()); let content = ui.ctx().data(|m| m.get_temp::(content_id(ui))).unwrap_or(0.0); let rest = (window - content).max(0.0); diff --git a/crates/ui-egui/src/dialogs/path_ops.rs b/crates/ui-egui/src/dialogs/path_ops.rs index 3a62eae1f4..3ffc496dd6 100644 --- a/crates/ui-egui/src/dialogs/path_ops.rs +++ b/crates/ui-egui/src/dialogs/path_ops.rs @@ -198,7 +198,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { && let Some(counts) = d.fields.get("__counts") && let (Some(before), Some(after)) = (counts["before"].as_u64(), counts["after"].as_u64()) { - ui.label(format!("{}: {before} → {after}", tl!("Anchor Points"))); + ui.label(format!("{} {before} → {after}", crate::i18n::colon(tl!("Anchor Points")))); } } false diff --git a/crates/ui-egui/src/dialogs/png_options.rs b/crates/ui-egui/src/dialogs/png_options.rs index 8965564430..ae70d682c4 100644 --- a/crates/ui-egui/src/dialogs/png_options.rs +++ b/crates/ui-egui/src/dialogs/png_options.rs @@ -63,8 +63,13 @@ pub fn open(app: &mut VectorcraftApp, f: &Format, mut params: Value) { false => export_size(&st.doc, ¶ms), }); if let Some(o) = params.as_object_mut() { - o.insert("ppi".into(), json!(72)); - o.extend(defaults(app, f)); + let mut initial = defaults(app, f); + initial.insert("ppi".into(), json!(72)); + for (key, value) in initial { + if o.get(&key).is_none_or(Value::is_null) { + o.insert(key, value); + } + } if let Some((w, h)) = size { o.insert("__size".into(), json!([w, h])); } @@ -155,7 +160,7 @@ fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { d.fields.insert("__otherPpi".into(), json!(i == 3)); } if preset.is_none() - && let Some(v) = widgets::range_field(ui, "ro-ppi-other", ppi, 1.0..=4608.0, " ppi", 0, 80.0) + && let Some(v) = widgets::range_field(ui, "ro-ppi-other", ppi, 1.0..=4608.0, &super::ppi_suffix(), 0, 80.0) { d.fields.insert("ppi".into(), json!(v)); } diff --git a/crates/ui-egui/src/dialogs/print.rs b/crates/ui-egui/src/dialogs/print.rs index ebaad1749a..dd8db94418 100644 --- a/crates/ui-egui/src/dialogs/print.rs +++ b/crates/ui-egui/src/dialogs/print.rs @@ -251,7 +251,8 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { ui.vertical(|ui| { ui.set_width(500.0); ui.label(egui::RichText::new(tl!(section)).font(theme::semibold(14.0)).color(t.text_strong)); - egui::ScrollArea::vertical().id_salt(("print", section)).max_height(360.0).auto_shrink([false, false]).show(ui, |ui| match section { + let list_h = super::modal::list_height(ui, 360.0); + egui::ScrollArea::vertical().id_salt(("print", section)).max_height(list_h).auto_shrink([false, false]).show(ui, |ui| match section { "Marks and Bleed" => super::save_pdf::marks_and_bleeds(app, ui, d), "Output" => output(ui, d, &preview), "Graphics" => graphics(ui, d), diff --git a/crates/ui-egui/src/dialogs/psd_import.rs b/crates/ui-egui/src/dialogs/psd_import.rs index 950b15c763..c5a4c905a0 100644 --- a/crates/ui-egui/src/dialogs/psd_import.rs +++ b/crates/ui-egui/src/dialogs/psd_import.rs @@ -167,7 +167,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { let count = |k: &str| d.fields.get(k).and_then(Value::as_u64).unwrap_or(0); - widgets::dim_label(ui, &format!("{} × {} px · {}: {}", count("width"), count("height"), tl!("Layers"), count("layers"))); + widgets::dim_label(ui, &format!("{} × {} px · {} {}", count("width"), count("height"), crate::i18n::colon(tl!("Layers")), count("layers"))); // Offered only for a file with slices, with either conversion. let sliced = count("slices") > 0; ui.add_space(8.0); diff --git a/crates/ui-egui/src/dialogs/raster_effects.rs b/crates/ui-egui/src/dialogs/raster_effects.rs index cc7ed96f44..d28c30b041 100644 --- a/crates/ui-egui/src/dialogs/raster_effects.rs +++ b/crates/ui-egui/src/dialogs/raster_effects.rs @@ -59,7 +59,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { } } if preset.is_none() - && let Some(v) = widgets::plain_field(ui, "raster-ppi", ppi, " ppi", 0, 80.0) + && let Some(v) = widgets::plain_field(ui, "raster-ppi", ppi, &super::ppi_suffix(), 0, 80.0) { d.fields.insert("resolution".into(), json!(v)); } @@ -124,7 +124,7 @@ pub(super) fn effect_fields(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dia } if !document && preset.is_none() - && let Some(v) = widgets::plain_field(ui, "rasterize-ppi", ppi, " ppi", 0, 80.0) + && let Some(v) = widgets::plain_field(ui, "rasterize-ppi", ppi, &super::ppi_suffix(), 0, 80.0) { d.fields.insert("resolution".into(), json!(v)); } diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index e3829f92b5..cfa699b7b9 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -46,6 +46,22 @@ //! Opened on colours alone (the Color Guide's Edit or Apply Colors without art), OK saves the new //! colours as a colour group named `groupName`. //! +//! The Color Groups list on the right (under the tabs in a window too narrow for both; the Show +//! Color Groups button beside the tabs shows or hides it, and it opens shown) lists the document's color groups with their colors. A click on one makes it +//! the group being edited, as opening on it would: with art the art is reduced to as many rows as +//! it has colors, which become their new colors, and without art the rows are its colors. Save +//! Changes rewrites the selected group with the rows' new colors (`swatch.editGroup`, renamed by +//! `groupName`), New Color Group saves them as a new group (`swatch.newGroup`), and Delete removes +//! the selected group with its swatches (`swatch.delete`); each is a step of its own, which the +//! Swatches panel shows. When the art has colors of the group, Save Changes keeps the group's +//! swatches in order: a swatch whose color a row lists takes that row's new color (its own color +//! when the row is excluded), and every other swatch keeps its color. After a save with art the +//! rows' new colors take the Global Adjust, which goes back to 0%. When the save recolors art +//! linked to the group's global swatches, the rows are read from the art again (a color the save +//! gave the art is excluded, and a color the art had before keeps its row's new color). Until the +//! rows or the Global Adjust change, OK changes the saved group only by its name. After a Delete +//! without art, OK saves the rows as a new color group. +//! //! The Color Theme Picker button beside the tabs turns on picking from the canvas: a click on an //! object takes the palette of the object a Selection tool click takes, a drag takes the palette //! of the art inside its marquee, and Shift adds to the picks so far (`recolor.pickTheme`). The @@ -68,8 +84,11 @@ //! show hue and brightness; `hueSaturation`, unset or any other value: hue and saturation), `themePicker` (the Color Theme Picker is on), `themePicks` (its picks, as //! `recolor.pickTheme`'s `picks`; a new list recolors the rows), `weights` (one per row, as //! `recolor.weigh`'s; a new list moves the rows' current colors toward them), `findColors` (Find is -//! on; it shows the art so on the Assign tab, with art and rows selected). Changing `colors`, a -//! preserve flag or `limitTo` reduces the rows again (and drops `weights`). +//! on; it shows the art so on the Assign tab, with art and rows selected), `groupStorage` (the +//! Color Groups list is shown), `groupAction` (`save`, `new` or `delete`: the list's buttons, +//! checked as the field is set and run by the next frame, or by OK first). Setting `group` to a color group's name selects it in the list, and null +//! selects none. Changing `colors`, a preserve flag or `limitTo` reduces the rows again (and drops +//! `weights`). use egui::{Rect, Sense, Ui, pos2, vec2}; use serde_json::{Value, json}; @@ -96,10 +115,25 @@ pub(super) const SPEC: DialogSpec = DialogSpec { confirm, preview: true, min_width: 540.0, - max_width: Some(560.0), + max_width: Some(MAIN_W + STORAGE_GAP + STORAGE_W), + inputs: |_| &[GROUP_ACTION], ..DialogSpec::FORM }; +/// Widths of the dialog's main part (the tabs), of the Color Groups list and of the gap between +/// them; the height of a group's row in the list. +const MAIN_W: f32 = 560.0; +const STORAGE_W: f32 = 170.0; +const STORAGE_GAP: f32 = 12.0; +const GROUP_ROW_H: f32 = 34.0; +/// The fields of the Color Groups list: whether it is shown, a request from its buttons, and the +/// group whose colors the rows were last given. +const GROUP_STORAGE: &str = "groupStorage"; +const GROUP_ACTION: &str = "groupAction"; +const GROUP_LOADED: &str = "__groupLoaded"; +/// The `recolor.reduce` parameters the art's rows were last reduced with. +const REDUCED: &str = "__reduced"; + const CMD: &str = "recolor.apply"; /// Width of the current colours of a row. const CURRENT_W: f32 = 250.0; @@ -182,6 +216,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { "preserveGrays": kept("preserveGrays", false), "limitTo": limit, "group": group, "groupName": if new_group { Some(NEW_GROUP) } else { group }, "tab": "assign", "rule": Harmony::Complementary.id(), "linked": true, "preview": true, THEME_PICKER: false, THEME_PICKS: [], WEIGHTS: null, FIND: false, "__art": art, "__assign": assign, "__newGroup": new_group, + GROUP_STORAGE: true, GROUP_LOADED: group, }); let mut d = Dialog::new(KIND, fields); // Without art the rows are there from the start: limit them now (art's rows snap as they reduce). @@ -215,7 +250,7 @@ fn reduce_params(d: &Dialog) -> Value { /// Reduce the art's colours into rows again when the count, preserve flags or library changed /// (assigning a group's colours or the opener's colours as the new colours). fn sync(app: &mut VectorcraftApp, d: &mut Dialog) { - const DONE: &str = "__reduced"; + const DONE: &str = REDUCED; let sig = reduce_params(d); if !d.bool("__art") || d.fields.get(DONE) == Some(&sig) { return; @@ -357,7 +392,8 @@ fn prominent_bar(ui: &mut Ui, d: &mut Dialog, rows: &[Value]) { let c = to_color(&rows[*i]).or_else(|| from_colors(&rows[*i]).first().copied()).unwrap_or_default(); chip(ui, r, c, false); let share = (widths[n] * 100.0).round(); - ui.interact(r, egui::Id::unique((PROMINENT_PART, n)), Sense::hover()).on_hover_text(format!("{} {}: {share}%", tl!("Color"), i + 1)); + ui.interact(r, egui::Id::unique((PROMINENT_PART, n)), Sense::hover()) + .on_hover_text(format!("{} {share}%", crate::i18n::colon(&format!("{} {}", tl!("Color"), i + 1)))); left = right; } let mut ended = false; @@ -397,7 +433,7 @@ fn group_colors<'a>(app: &VectorcraftApp, d: &Dialog, rs: impl Iterator from_colors(r).first().map(key), - Some(_) if adjust.is_identity() => Some(r["to"].clone()), + Some(_) if adjust.is_identity() && palette.is_none() => Some(r["to"].clone()), Some(c) => { let c = adjust.apply(c); Some(key(&palette.as_ref().map_or(c, |p| p.nearest(c)))) @@ -410,7 +446,7 @@ fn group_colors<'a>(app: &VectorcraftApp, d: &Dialog, rs: impl Iterator Result<(), String> { let rs = rows(d); let order: Vec = match which { "prominent" => prominent_parts(d, &rs).into_iter().map(|p| p.0).collect(), @@ -418,12 +454,483 @@ fn save_group(app: &mut VectorcraftApp, d: &mut Dialog, which: &str) { }; let colors = group_colors(app, d, order.iter().filter_map(|&i| rs.get(i))); if colors.is_empty() { - return; + return Ok(()); } // The group is added to the document itself, not to the preview, which runs again afterwards. cancel_preview(app, d); - if let Err(e) = app.run("swatch.newGroup", json!({"colors": colors, "keepModel": true})) { - app.status(e); + app.run("swatch.newGroup", json!({"colors": colors, "keepModel": true})).map(|_| ()) +} + +/// The colors of the document's color groups, by name, in the Swatches panel's order. +fn doc_groups(app: &VectorcraftApp) -> Vec<(String, Vec)> { + let Some(st) = app.session.active() else { return vec![] }; + st.doc.swatch_groups.iter().map(|g| (g.name.clone(), g.swatches.iter().filter_map(|w| w.paint.color()).collect())).collect() +} + +/// Make the `group` field's color group (none when it is null) the group being edited, when its +/// colors aren't the rows' yet: with art the art is reduced again to as many rows as the group has +/// colors, which become their new colors (as [`open`] does); without art the rows are its colors. +/// A name no color group has is refused, and the field goes back to the group being edited. +fn select_group(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { + let want = d.fields.get("group").cloned().unwrap_or(Value::Null); + let loaded = d.fields.get(GROUP_LOADED).cloned().unwrap_or(Value::Null); + if want == loaded { + return Ok(()); + } + // The preview gives the group being edited the name in `groupName`, which the list shows: unless + // the document (without the preview) has another group of that name, it is the same group. + if let Value::String(n) = &want + && loaded.is_string() + && *n == d.str("groupName") + && d.fields.contains_key(super::form::PREVIEWED) + { + cancel_preview(app, d); + if !doc_groups(app).iter().any(|(g, _)| g == n) { + d.fields.insert("group".into(), loaded); + return Ok(()); + } + } + let art = d.bool("__art"); + let name = match &want { + Value::Null => { + // No group: without art OK saves the rows as a new color group. + d.fields.insert(GROUP_LOADED.into(), Value::Null); + if !art { + d.fields.insert("__newGroup".into(), json!(true)); + d.fields.insert("groupName".into(), json!(NEW_GROUP)); + } + return Ok(()); + } + Value::String(n) => n.clone(), + v => { + d.fields.insert("group".into(), loaded); + return Err(format!("`group` must be a color group name, not {v}")); + } + }; + // The group's own colors, not those the preview (which rewrites the group being edited) shows. + if doc_groups(app).iter().any(|(n, _)| *n == name) { + cancel_preview(app, d); + } + let Some((_, colors)) = doc_groups(app).into_iter().find(|(n, _)| *n == name) else { + d.fields.insert("group".into(), loaded); + return Err(format!("no colour group `{name}`")); + }; + let assign: Vec = colors.iter().map(key).collect(); + d.fields.insert(GROUP_LOADED.into(), json!(name)); + d.fields.insert("groupName".into(), json!(name)); + d.fields.insert("__newGroup".into(), json!(false)); + // The group's colors take the place of colors picked with the Color Theme Picker, and the same + // picks made again apply to its rows. + d.fields.insert(THEME_PICKS.into(), json!([])); + d.fields.remove(THEME_DONE); + d.fields.remove(SAVED_ROWS); + d.fields.remove(SAVED_COLORS); + d.fields.remove(SWATCH_ROWS); + if art { + // The art is reduced again (`sync`) into a row per color of the group. + d.fields.insert("colors".into(), json!(assign.len().max(1))); + d.fields.remove(REDUCED); + } else { + let mut rs: Vec = assign.iter().map(|k| json!({"from": [k], "to": k})).collect(); + snap(app, d, &mut rs); + d.fields.insert("rows".into(), Value::Array(rs)); + d.fields.insert("__sel".into(), json!([])); + d.fields.remove(COMPS); + } + d.fields.insert("__assign".into(), Value::Array(assign)); + Ok(()) +} + +/// Run a button of the Color Groups list: `save` rewrites the selected group with the rows' new +/// colors as OK gives them to it (with art, followed by the group's colors no row took) and the +/// name in `groupName`; `new` saves the new colors of the rows that aren't excluded as a new group; +/// `delete` removes the selected group and its swatches. Each is an undo step of its own on the +/// document, not on the preview, which runs again afterwards. +fn group_action(app: &mut VectorcraftApp, d: &mut Dialog, action: &Value) -> Result<(), String> { + check_group_action(app, d, action)?; + let group = d.fields.get("group").and_then(Value::as_str).map(str::to_owned); + // The rows as OK reads them (a group just selected reduces the art again). + sync(app, d); + sync_theme(app, d); + sync_weights(app, d); + match action.as_str() { + Some("new") => save_group(app, d, "all"), + Some("save") if unchanged_since_save(d) => { + // Nothing changed since the last save but perhaps the name. + let name = d.str("groupName"); + if name.trim().is_empty() || group.as_deref() == Some(name.as_str()) { + return Ok(()); + } + cancel_preview(app, d); + let colors: Vec = doc_groups(app) + .into_iter() + .find(|(n, _)| group.as_deref() == Some(n.as_str())) + .map(|g| g.1.iter().map(key).collect()) + .unwrap_or_default(); + let r = app.run("swatch.editGroup", json!({"group": group, "colors": colors, "rename": name}))?; + let name = r["name"].clone(); + d.fields.insert("group".into(), name.clone()); + d.fields.insert(GROUP_LOADED.into(), name.clone()); + d.fields.insert("groupName".into(), name); + Ok(()) + } + Some("save") => { + let rs = rows(d); + let p = apply_params(d); + // With art, the group's colors no row took follow, adjusted and snapped as OK gives them, + // then the colors added on the Edit tab; a row made with New Row that holds no current + // colors gives the group no color. + cancel_preview(app, d); + let own: Vec = doc_groups(app) + .into_iter() + .find(|(n, _)| group.as_deref() == Some(n.as_str())) + .map(|g| g.1.iter().map(key).collect()) + .unwrap_or_default(); + // An excluded row leaves its swatch the color it has now, as OK's `"keep"` does: with + // art, the swatch's color in `__assign`; without art, the swatch's color in the group, + // which an earlier Save Changes may have changed. + let filled: Vec<&Value> = rs.iter().filter(|r| !no_current(r)).collect(); + let rest: Vec = + p["groupColors"].as_array().map(|a| a.iter().skip(filled.len()).map(|k| json!({"from": [k], "to": k})).collect()).unwrap_or_default(); + let assign: Vec = + if d.bool("__art") { d.fields.get("__assign").and_then(Value::as_array).cloned().unwrap_or_default() } else { own.clone() }; + let mut colors: Vec = filled + .iter() + .enumerate() + .filter_map(|(i, r)| if excluded(r) { Some(kept_color(&assign, i)) } else { saved_color(app, d, r) }) + .chain(group_colors(app, d, rest.iter())) + .collect(); + // With art in a color of the group, the group keeps its swatch order: a swatch whose row + // ([`swatch_row`]) is found takes that row's new color (its own color when the row is + // excluded), so the art linked to it takes the color its row shows, and every other + // swatch keeps its color. The colors added on the Edit tab follow. + let found: Vec> = (0..own.len()).map(|i| swatch_row(d, &rs, &own, i)).collect(); + let mut links = None; + if d.bool("__art") && found.iter().any(Option::is_some) { + let added = rs.iter().filter(|r| no_current(r) && is_added(r) && !excluded(r) && !r["to"].is_null()); + let mut saved_links = vec![]; + colors = vec![]; + for (k, f) in own.iter().zip(&found) { + let c = match f { + Some((_, r)) if !excluded(r) => saved_color(app, d, r).unwrap_or_else(|| k.clone()), + _ => k.clone(), + }; + // A removed swatch leaves the saved group. + if !c.is_null() { + saved_links.push(f.as_ref().map_or(Value::Null, |f| f.0.clone())); + } + colors.push(c); + } + let added = group_colors(app, d, added); + saved_links.extend(added.iter().map(|_| Value::Null)); + colors.extend(added); + links = Some(saved_links); + } + let before = art_colors(app); + let r = app.run("swatch.editGroup", json!({"group": group, "colors": colors, "keepModel": true, "rename": p["rename"]}))?; + let name = r["name"].clone(); + d.fields.insert("group".into(), name.clone()); + d.fields.insert(GROUP_LOADED.into(), name.clone()); + d.fields.insert("groupName".into(), name); + // The rows follow the saved group, so a later edit or OK does not remove or add a color + // again: a removed color's row goes (its art keeps its colors). Without art, a color added + // on the Edit tab becomes a row of its own color, after the rows of the group's other + // colors; with art, its row goes and the color is one of the group's colors no row takes. + let art = d.bool("__art"); + let joins = |r: &Value| no_current(r) && is_added(r) && !excluded(r) && !r["to"].is_null(); + let gone: Vec = + rows(d).iter().filter(|r| color_removed(r)).flat_map(|r| r["from"].as_array().cloned().unwrap_or_default()).collect(); + let (mut joined, mut rs): (Vec, Vec) = rows(d).into_iter().filter(|r| !color_removed(r)).partition(|r| joins(r)); + if art { + joined.clear(); + } + for r in &mut joined { + r["from"] = json!([r["to"].clone()]); + if let Some(o) = r.as_object_mut() { + o.remove("added"); + } + } + // The save added them after the group's other colors, whatever the rows' order. + rs.extend(joined); + if rs != rows(d) { + d.fields.insert("__sel".into(), json!([])); + } + d.fields.insert("rows".into(), Value::Array(rs)); + if art { + // The group's colors no row takes are those of the saved group. + let saved: Vec = doc_groups(app) + .into_iter() + .find(|(n, _)| Some(n.as_str()) == r["name"].as_str()) + .map(|g| g.1.iter().map(key).collect()) + .unwrap_or_default(); + d.fields.insert("__assign".into(), Value::Array(saved)); + match links { + Some(l) => d.fields.insert(SWATCH_ROWS.into(), Value::Array(l)), + None => d.fields.remove(SWATCH_ROWS), + }; + // The saved group holds the Global Adjust: the rows' new colors take it, and it goes + // back to 0%, so neither the preview nor OK applies it again. + bake_adjust(app, d); + let rs = rows(d); + if art_colors(app) == before { + mark_saved(app, d); + } else { + reread_rows(app, d, &rs, &before, &gone); + } + } + Ok(()) + } + Some("delete") => { + cancel_preview(app, d); + app.run("swatch.delete", json!({"names": [group]}))?; + d.fields.insert("group".into(), Value::Null); + select_group(app, d) + } + _ => Ok(()), + } +} + +/// The color Save Changes gives the group's swatch for `row`: `null` when the row's color was +/// removed, which removes the swatch as OK does, otherwise its new color as OK gives it. +fn saved_color(app: &VectorcraftApp, d: &Dialog, row: &Value) -> Option { + if color_removed(row) { Some(Value::Null) } else { group_colors(app, d, std::iter::once(row)).into_iter().next() } +} + +/// After Save Changes recolored the art linked to the group's global swatches, read the rows from +/// the art again. A row that lists a color the save gave the art (a paint of a selected object +/// that differs from `before`, [`art_colors`] before the save) is excluded with its first color, +/// so the art keeps it, also when other art has that color: `recolor.apply` recolors every use +/// of a color alike, so the row cannot keep that art's earlier new color without undoing the save. Any other row whose first current color one of the `old` rows listed takes +/// that row's new color and exclusion (art the save left as it was keeps its recolor); the rest +/// are excluded too. A row that lists only `gone` colors (those of swatches the save removed) is +/// left out: its art keeps its colors, and the row gives the group no color. +fn reread_rows(app: &mut VectorcraftApp, d: &mut Dialog, old: &[Value], before: &[Vec], gone: &[Value]) { + let given: Vec = + art_colors(app).iter().zip(before).flat_map(|(now, was)| now.iter().zip(was).filter(|(n, w)| n != w).map(|(n, _)| n.clone())).collect(); + // A swatch whose color the save gave the art is found by that color again: the row its old + // color found lists other art now. + let group = d.fields.get("group").and_then(Value::as_str).map(str::to_owned); + let saved: Vec = + doc_groups(app).into_iter().find(|(n, _)| group.as_deref() == Some(n.as_str())).map(|g| g.1.iter().map(key).collect()).unwrap_or_default(); + if let Some(Value::Array(links)) = d.fields.get_mut(SWATCH_ROWS) { + for (l, c) in links.iter_mut().zip(&saved) { + if given.contains(c) { + *l = Value::Null; + } + } + } + d.fields.insert(THEME_PICKS.into(), json!([])); + d.fields.remove(REDUCED); + sync(app, d); + let mut rs = rows(d); + for r in &mut rs { + let Some(first) = r["from"].as_array().and_then(|f| f.first()).cloned() else { continue }; + let from_save = r["from"].as_array().is_some_and(|f| f.iter().any(|c| given.contains(c))); + match row_listing(old, &first).filter(|_| !from_save) { + Some(o) => { + r["to"] = o["to"].clone(); + r["exclude"] = json!(excluded(o)); + } + None => { + r["to"] = first; + r["exclude"] = json!(true); + } + } + } + rs.retain(|r| r["from"].as_array().is_none_or(|f| f.is_empty() || !f.iter().all(|c| gone.contains(c)))); + d.fields.insert("rows".into(), Value::Array(rs)); + mark_saved(app, d); +} + +/// Give each row's new color the Global Adjust (and Limit to Library) as OK would, and set the +/// Global Adjust back to 0%; nothing changes when it is 0%. +fn bake_adjust(app: &VectorcraftApp, d: &mut Dialog) { + if global_adjust(adjust_values(d)).is_identity() { + return; + } + let mut rs = rows(d); + for r in &mut rs { + if to_color(r).is_some() + && let Some(c) = group_colors(app, d, std::iter::once(&*r)).into_iter().next() + { + r["to"] = c; + } + } + d.fields.insert("rows".into(), Value::Array(rs)); + d.fields.insert("globalAdjust".into(), Value::Object(ADJUSTS.iter().map(|k| (k.to_string(), json!(0.0))).collect())); +} + +/// After Save Changes with art: until the rows or the Global Adjust change, OK and the preview +/// leave the selected group's colors as they were saved. +fn mark_saved(app: &VectorcraftApp, d: &mut Dialog) { + let group = d.fields.get("group").and_then(Value::as_str).map(str::to_owned); + let saved: Vec = + doc_groups(app).into_iter().find(|(n, _)| group.as_deref() == Some(n.as_str())).map(|g| g.1.iter().map(key).collect()).unwrap_or_default(); + d.fields.insert(SAVED_COLORS.into(), Value::Array(saved)); + d.fields.insert(SAVED_ROWS.into(), Value::Array(rows(d))); + d.fields.insert(SAVED_ADJUST.into(), json!(adjust_values(d))); +} + +/// Whether the rows and the Global Adjust are as [`mark_saved`] recorded them. +fn unchanged_since_save(d: &Dialog) -> bool { + d.fields.get(SAVED_ROWS).and_then(Value::as_array).is_some_and(|s| *s == rows(d)) + && d.fields.get(SAVED_ADJUST).is_some_and(|a| *a == json!(adjust_values(d))) +} + +/// The Global Adjust amounts [`mark_saved`] recorded. +const SAVED_ADJUST: &str = "__savedAdjust"; + +/// The colors of each selected object and what is inside it, as row keys, in paint order. +fn art_colors(app: &VectorcraftApp) -> Vec> { + let Some(st) = app.session.active() else { return vec![] }; + st.selection + .objects + .iter() + .map(|id| { + let mut cs = vec![]; + if let Some(n) = st.doc.node(*id) { + vectorcraft_doc::swatches::node_colors(n, &mut |c, _| cs.push(key(c))); + } + cs + }) + .collect() +} + +/// The rows [`mark_saved`] recorded after Save Changes; while the rows are these, OK and the preview +/// leave the group's colors as saved ([`SAVED_COLORS`]) and change only its name. +const SAVED_ROWS: &str = "__savedRows"; + +/// The selected group's colors after Save Changes. OK with a new name keeps the color of each of +/// those swatches (`"keep"`). +const SAVED_COLORS: &str = "__savedColors"; + +/// With art, for each swatch of the selected group after Save Changes, the color that found the row +/// that gave it its new color (`null` for a swatch no row gave one), so a later Save Changes or OK +/// finds that row again when the row still lists its old current color. +const SWATCH_ROWS: &str = "__swatchRows"; + +/// The row that gives the swatch at place `i` of `own` (the group's colors) its new color, with the +/// color that finds it: the row listing the color [`SWATCH_ROWS`] holds for that swatch, else the +/// first row listing the swatch's own color. +fn swatch_row<'a>(d: &Dialog, rs: &'a [Value], own: &[Value], i: usize) -> Option<(Value, &'a Value)> { + let links = d.fields.get(SWATCH_ROWS).and_then(Value::as_array).filter(|l| l.len() == own.len()); + let link = links.and_then(|l| l.get(i)).filter(|l| !l.is_null()); + link.and_then(|l| row_listing(rs, l).map(|r| (l.clone(), r))).or_else(|| own.get(i).and_then(|k| row_listing(rs, k).map(|r| (k.clone(), r)))) +} + +/// The color an excluded row leaves its swatch, the row being the `i`th of the rows with current +/// colors: the swatch's own color in `assign` (the group's colors), else `null`, which adds no +/// swatch past the group's, as OK's `"keep"` does. +fn kept_color(assign: &[Value], i: usize) -> Value { + assign.get(i).cloned().unwrap_or(Value::Null) +} + +/// Refuse a `groupAction` other than `save`, `new` or `delete`, `save` or `delete` with no group +/// selected, and `save` on a group with a swatch that is not a color (a gradient, pattern or None +/// swatch): the rows hold only the group's colors, so the save would replace or remove it. +fn check_group_action(app: &VectorcraftApp, d: &Dialog, action: &Value) -> Result<(), String> { + let group = d.fields.get("group").and_then(Value::as_str); + match (action.as_str(), group) { + (Some("new"), _) => Ok(()), + (Some("save"), Some(g)) if holds_other_paints(app, g) => { + Err(format!("color group `{g}` holds swatches that are not colors, which Save Changes can't keep")) + } + (Some("save" | "delete"), Some(_)) => Ok(()), + (Some("save" | "delete"), None) => Err("missing `group`".into()), + _ => Err(format!("`{GROUP_ACTION}` must be \"save\", \"new\" or \"delete\", not {action}")), + } +} + +/// Whether color group `group` has a swatch that is not a color, in the document as it is without +/// the preview (which can rewrite or rename the group). +fn holds_other_paints(app: &VectorcraftApp, group: &str) -> bool { + let Some(st) = app.session.active() else { return false }; + let doc = st.interaction.as_ref().map_or(&st.doc, |it| &it.doc); + doc.swatch_groups.iter().any(|g| g.name == group && g.swatches.iter().any(|w| w.paint.color().is_none())) +} + +/// Run the button of the Color Groups list that `groupAction` holds, if any. +fn run_group_action(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { + match d.fields.remove(GROUP_ACTION) { + Some(a) => group_action(app, d, &a), + None => Ok(()), + } +} + +/// `ui.dialog.set` of `group`, `groupStorage` or `groupAction`: select the group, or check the +/// button, which the next frame (or OK) runs. +pub(super) fn field_set(app: &mut VectorcraftApp, field: &str) -> Result<(), String> { + let Some(mut d) = app.ui.dialog.take() else { return Ok(()) }; + let r = match field { + "group" => select_group(app, &mut d), + GROUP_ACTION => match d.fields.get(GROUP_ACTION).cloned() { + Some(a) => check_group_action(app, &d, &a), + None => Ok(()), + }, + GROUP_STORAGE if !d.fields.get(GROUP_STORAGE).is_some_and(Value::is_boolean) => Err(format!("`{GROUP_STORAGE}` must be true or false")), + _ => Ok(()), + }; + app.ui.dialog = Some(d); + r +} + +/// The Color Groups list: a row per color group of the document with its name and colors (a click +/// selects it), and the Save Changes, New Color Group and Delete buttons under it. +fn group_storage(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog, max_h: f32) { + let t = Tokens::get(ui.ctx()); + let groups = doc_groups(app); + let mut current = d.fields.get("group").and_then(Value::as_str).map(str::to_owned); + // While the art previews, the group being edited shows under its new name. + if current.is_some() && d.fields.contains_key(super::form::PREVIEWED) && !groups.iter().any(|(n, _)| Some(n) == current.as_ref()) { + current = Some(d.str("groupName")); + } + let mut picked = None; + egui::ScrollArea::vertical().id_salt("recolor-groups").max_height(max_h).auto_shrink([false, true]).show(ui, |ui| { + for (name, colors) in &groups { + let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), GROUP_ROW_H), Sense::click()); + let on = current.as_deref() == Some(name.as_str()); + if on { + ui.painter().rect_filled(r, 2.0, t.row_selected); + } else if resp.hovered() { + ui.painter().rect_filled(r, 2.0, t.hover); + } + let inner = r.shrink2(vec2(4.0, 3.0)); + ui.painter().text(inner.left_top(), egui::Align2::LEFT_TOP, name, egui::FontId::proportional(12.0), t.text); + let fit = ((inner.width() + 2.0) / 12.0).floor().max(0.0) as usize; + for (n, c) in colors.iter().take(fit).enumerate() { + let x = inner.left() + n as f32 * 12.0; + chip(ui, Rect::from_min_size(pos2(x, inner.bottom() - 10.0), vec2(10.0, 10.0)), *c, false); + } + let resp = resp.on_hover_text(name); + resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, ui.is_enabled(), on, name)); + if resp.clicked() { + picked = Some(name.clone()); + } + } + }); + if let Some(name) = picked { + d.fields.insert("group".into(), json!(name)); + if let Err(e) = select_group(app, d) { + app.status(e); + } + } + ui.add_space(4.0); + let selected = current.is_some(); + let any = rows(d).iter().any(|r| !excluded(r)); + let mut action = None; + ui.horizontal(|ui| { + if widgets::icon_button_enabled(ui, "save", tl!("Save Changes"), false, selected, 24.0).clicked() { + action = Some("save"); + } + if widgets::icon_button_enabled(ui, "dc-folder", tl!("New Color Group"), false, any, 24.0).clicked() { + action = Some("new"); + } + if widgets::icon_button_enabled(ui, "trash-2", tl!("Delete"), false, selected, 24.0).clicked() { + action = Some("delete"); + } + }); + if let Some(a) = action { + d.fields.insert(GROUP_ACTION.into(), json!(a)); } } @@ -580,6 +1087,12 @@ fn no_current(row: &Value) -> bool { row["from"].as_array().is_none_or(Vec::is_empty) } +/// Whether `row` holds current colors and its new color was removed (`to: null`) and isn't excluded: +/// its swatch in the color group is removed. +fn color_removed(row: &Value) -> bool { + !excluded(row) && !no_current(row) && row["to"].is_null() +} + /// Whether `row` is a color added on the Edit tab (`added`), which joins the color group. fn is_added(row: &Value) -> bool { row["added"].as_bool().unwrap_or(false) @@ -609,21 +1122,47 @@ fn selection(d: &Dialog) -> Vec { /// `recolor.apply` parameters: the rows, method, library and the group with its new name and /// colors: the new colors of the rows with current colors, each in its swatch's place (`null` -/// for a row whose new color was removed, which removes its swatch), then (with art) the group's -/// colors no row took, then the colors added on the Edit tab. +/// for a row whose new color was removed, which removes its swatch, and `"keep"` for an excluded +/// row, which leaves its swatch its color), then (with art) the group's colors no row took, then the +/// colors added on the Edit tab. With art in a color of the group, each swatch whose row +/// ([`swatch_row`]) is found takes that row's new color instead, and every other swatch keeps its +/// color, as Save Changes gives them. fn apply_params(d: &Dialog) -> Value { let rs = rows(d); - let group = d.fields.get("group").and_then(Value::as_str).map(|g| { - // A row made with New Row that holds no current colors gives the group no color; a color - // added on the Edit tab (`added`) joins it after the others. - let took: Vec<&Value> = rs.iter().filter(|r| !no_current(r)).map(|r| &r["to"]).collect(); - let assign = d.fields.get("__assign").and_then(Value::as_array).filter(|_| d.bool("__art")); - let rest = assign.map_or(&[][..], |a| a.get(took.len()..).unwrap_or_default()); - let added = rs.iter().filter(|r| no_current(r) && is_added(r) && !excluded(r)).map(|r| &r["to"]).filter(|c| !c.is_null()); - let colors: Vec<&Value> = took.into_iter().chain(rest).chain(added).collect(); + // The rows and Global Adjust unchanged since Save Changes: the group keeps its saved colors. + let saved = unchanged_since_save(d); + let assign = d.fields.get("__assign").and_then(Value::as_array).filter(|_| d.bool("__art")).map_or(&[][..], Vec::as_slice); + let found: Vec> = (0..assign.len()).map(|i| swatch_row(d, &rs, assign, i)).collect(); + let keep = json!("keep"); + let group = d.fields.get("group").and_then(Value::as_str).and_then(|g| { let name = d.str("groupName"); let rename = (!name.trim().is_empty() && name != g).then_some(name); - json!({"group": g, "groupColors": colors, "rename": rename}) + let colors: Vec<&Value> = if saved { + // Only a new name changes the group: each swatch keeps its exact color. + rename.as_ref()?; + d.fields.get(SAVED_COLORS).and_then(Value::as_array).map(|a| a.iter().map(|_| &keep).collect())? + } else { + // A row made with New Row that holds no current colors gives the group no color; a color + // added on the Edit tab (`added`) joins it after the others. + let added = rs.iter().filter(|r| no_current(r) && is_added(r) && !excluded(r)).map(|r| &r["to"]).filter(|c| !c.is_null()); + // A swatch that keeps its color takes no Global Adjust. + if found.iter().any(Option::is_some) { + found + .iter() + .map(|f| match f { + Some((_, r)) if !excluded(r) => &r["to"], + _ => &keep, + }) + .chain(added) + .collect() + } else { + let filled: Vec<&Value> = rs.iter().filter(|r| !no_current(r)).collect(); + let rest = assign.get(filled.len()..).unwrap_or_default(); + let took = filled.iter().map(|r| if excluded(r) { &keep } else { &r["to"] }); + took.chain(rest).chain(added).collect() + } + }; + Some(json!({"group": g, "groupColors": colors, "rename": rename})) }); // A row edited with the sliders carries `model: "new"`: its art takes the mode they showed. let mut p = json!({"map": rs, "method": d.str("method"), "limitTo": d.str("limitTo")}); @@ -661,6 +1200,26 @@ fn find_entry(k: &Value) -> Option { } } +/// The first of `rows` that lists the color entry `k`, as `recolor.apply` reads entries: rows that +/// list it as an exact color (by key, whatever its case or spacing) come before rows whose +/// "#rrggbb" entry matches it by its hex. Rows that give the color a new color (not excluded, `to` +/// not `null`) come first, since `recolor.apply` maps the color with them; an excluded row or one +/// that removes the color is found only when no such row lists it. +fn row_listing<'a>(rows: &'a [Value], k: &Value) -> Option<&'a Value> { + let want = find_entry(k)?; + let hex = |e: &FindEntry| e.as_ref().map_or_else(Clone::clone, |k| k.color().to_hex()); + let lists = |r: &Value, by_hex: bool| { + r["from"].as_array().is_some_and(|f| { + f.iter().filter_map(find_entry).any(|e| match (&e, &want) { + (Ok(a), Ok(b)) => !by_hex && a == b, + _ => by_hex && hex(&e) == hex(&want), + }) + }) + }; + let find = |live: bool, by_hex: bool| rows.iter().filter(|r| !live || (!excluded(r) && !r["to"].is_null())).find(|r| lists(r, by_hex)); + find(true, false).or_else(|| find(true, true)).or_else(|| find(false, false)).or_else(|| find(false, true)) +} + /// While Find is on, on the Assign tab with art and rows selected: what the art previews instead of /// [`apply_params`], as `command.batch` parameters. A first `recolor.apply` gives each current color /// of the rows that aren't selected, and each preserved color, its [`FIND_DIM`] tint, or the nearest lighter one when that is a @@ -734,10 +1293,57 @@ fn find_params(d: &Dialog) -> Option { (!commands.is_empty()).then(|| json!({"commands": commands})) } +/// The tabs, and the Color Groups list on their right while it is shown. fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { + if let Err(e) = select_group(app, d) { + app.status(e); + } + let room = ui.available_width(); + // Without the room for both side by side (a narrow window), the list goes under the tabs. + let beside = room >= SPEC.min_width + STORAGE_GAP + STORAGE_W; + // The Color Picker that a double-click on a new color or Pick from Swatches asks for opens over + // the dialog after the list is drawn, so the window keeps its size while the picker is open. + let mut picker = None; + if !d.bool(GROUP_STORAGE) || !beside { + ui.vertical(|ui| { + ui.set_width(room.min(MAIN_W)); + picker = main(app, ui, d); + if d.bool(GROUP_STORAGE) { + ui.add_space(6.0); + group_storage(app, ui, d, 3.0 * GROUP_ROW_H); + } + }); + } else { + ui.horizontal_top(|ui| { + ui.vertical(|ui| { + ui.set_width((room - STORAGE_GAP - STORAGE_W).clamp(0.0, MAIN_W)); + picker = main(app, ui, d); + }); + ui.add_space(STORAGE_GAP); + ui.vertical(|ui| { + ui.set_width(STORAGE_W); + group_storage(app, ui, d, TAB_H - 30.0); + }); + }); + } + if let Some((i, swatches)) = picker + && let Some(row) = rows(d).get(i) + { + let c = to_color(row).or_else(|| from_colors(row).first().copied()).unwrap_or_default(); + *d = super::color_picker::over_recolor(d, c, i, swatches); + } + false +} + +/// The tabs and the controls under them. Returns the row whose new color a double-click or Pick +/// from Swatches asked to pick in the Color Picker, with `true` for Pick from Swatches. +fn main(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> Option<(usize, bool)> { sync(app, d); sync_theme(app, d); sync_weights(app, d); + if let Err(e) = run_group_action(app, d) { + app.status(e); + } let t = Tokens::get(ui.ctx()); let picking = d.bool(THEME_PICKER); ui.horizontal(|ui| { @@ -751,6 +1357,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { if widgets::icon_button(ui, "pipette", tl!("Color Theme Picker"), picking, 24.0).clicked() { d.fields.insert(THEME_PICKER.into(), json!(!picking)); } + let storage = d.bool(GROUP_STORAGE); + if widgets::icon_button(ui, "library", tl!("Show Color Groups"), storage, 24.0).clicked() { + d.fields.insert(GROUP_STORAGE.into(), json!(!storage)); + } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { // The label is drawn after the menu (right-to-left), so it cannot name it by adjacency. if let Some(i) = widgets::dropdown_named(ui, "recolor-preset", Some(tl!("Preset:")), PRESETS[preset_of(d)], &PRESETS, 130.0) { @@ -782,8 +1392,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { d.fields.insert("rows".into(), Value::Array(rs)); } sync_weights(app, d); - if let Some(which) = d.fields.remove(SAVE_GROUP) { - save_group(app, d, which.as_str().unwrap_or_default()); + if let Some(which) = d.fields.remove(SAVE_GROUP) + && let Err(e) = save_group(app, d, which.as_str().unwrap_or_default()) + { + app.status(e); } if d.fields.get("group").is_some_and(Value::is_string) || d.bool("__newGroup") { ui.add_space(6.0); @@ -804,13 +1416,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { None => form::preview(app, ui, d, "Recolor Artwork", CMD, apply_params(d)), } } - if let Some((i, swatches)) = pick - && let Some(row) = rows(d).get(i) - { - let c = to_color(row).or_else(|| from_colors(row).first().copied()).unwrap_or_default(); - *d = super::color_picker::over_recolor(d, c, i, swatches); - } - false + pick } /// `d` with row `i`'s new colour set to `c` (the Color Picker's OK), snapped to Limit to Library. @@ -829,9 +1435,19 @@ pub(super) fn with_new_color(app: &VectorcraftApp, mut d: Dialog, i: usize, c: C /// save colours opened alone as a new colour group). fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let mut d = d.clone(); + select_group(app, &mut d)?; sync(app, &mut d); sync_theme(app, &mut d); sync_weights(app, &mut d); + // A Color Groups button set with OK in one request runs first, once: the open dialog takes + // its result, so an OK that fails afterwards does not run it again. + if d.fields.contains_key(GROUP_ACTION) { + let r = run_group_action(app, &mut d); + if let Some(live) = app.ui.dialog.as_mut().filter(|x| x.kind == KIND) { + *live = d.clone(); + } + r?; + } if d.bool("__newGroup") { let colors = group_colors(app, &d, rows(&d).iter().filter(|r| in_group(r))); return form::commit_preview(app, "swatch.newGroup", json!({"name": d.str("groupName"), "colors": colors, "keepModel": true})); @@ -1334,7 +1950,7 @@ fn global_sliders(ui: &mut Ui, d: &mut Dialog, sample: Color) { /// and its number field, showing `shown` with `suffix`. Returns the whole number in `shown`'s /// range that a drag, a key or the field sets. #[allow(clippy::too_many_arguments)] -fn slider_cell( +pub(crate) fn slider_cell( ui: &mut Ui, id: impl std::hash::Hash + Copy, label: &str, @@ -2000,14 +2616,14 @@ mod tests { } /// Opened on a color group, OK rewrites it with the new colors of the rows that hold current - /// colors, then the group's colors no such row took: an empty row gives it no color. + /// colors, and the group's color no such row lists keeps its color: an empty row gives it no color. #[test] fn an_empty_row_gives_the_group_no_color() { let mut r = rows(); new_row(&mut r, &[]); let fields = json!({"rows": r, "group": "Trio", "__art": true, "__assign": ["rgb 255 0 0", "rgb 0 0 255", "rgb 0 255 0", "rgb 9 9 9"]}); let p = apply_params(&Dialog::new("recolor", fields)); - assert_eq!(p["groupColors"], json!(["rgb 255 0 0", "rgb 0 0 255", "rgb 0 255 0", "rgb 9 9 9"])); + assert_eq!(p["groupColors"], json!(["rgb 255 0 0", "rgb 0 0 255", "rgb 0 255 0", "keep"])); } /// Opened on colors alone, OK saves the new colors of the rows that hold current colors as the @@ -2032,6 +2648,37 @@ mod tests { } /// Randomize after a seed past `u64::MAX` keeps the largest seed. + /// A row that lists a color exactly comes before an earlier row whose "#rrggbb" entry matches + /// it, as `recolor.apply` reads them; a hex entry matches a key of the same hex. + #[test] + fn a_row_listing_a_color_exactly_comes_before_a_hex_match() { + let rs = + [json!({"from": ["#0000ff"], "to": "rgb 0 255 0"}), json!({"from": ["RGB 0 0 255"], "to": "rgb 255 0 0"}), json!({"from": ["#ff0000"]})]; + assert_eq!(row_listing(&rs, &json!("rgb 0 0 255")), Some(&rs[1])); + assert_eq!(row_listing(&rs, &json!("rgb 255 0 0")), Some(&rs[2])); + assert_eq!(row_listing(&rs, &json!("#ff0000")), Some(&rs[2])); + assert_eq!(row_listing(&rs, &json!("rgb 0 255 0")), None); + assert_eq!(row_listing(&rs, &json!("cmyk 0 0 0 0")), None); + } + + /// A row that gives a color a new color comes before an earlier row that removes it or is + /// excluded, exact or by hex, as `recolor.apply` maps the color with it; those rows are found + /// only when no such row lists the color. + #[test] + fn a_row_giving_a_color_a_new_color_comes_before_one_removing_it() { + let rs = [ + json!({"from": ["rgb 0 0 255"], "to": null}), + json!({"from": ["rgb 0 0 255"], "to": "rgb 0 0 0", "exclude": true}), + json!({"from": ["#0000ff"], "to": "rgb 0 255 0"}), + json!({"from": ["rgb 0 0 255"], "to": "rgb 255 0 0"}), + json!({"from": ["rgb 255 255 0"], "to": null}), + ]; + assert_eq!(row_listing(&rs, &json!("rgb 0 0 255")), Some(&rs[3])); + assert_eq!(row_listing(&rs[..3], &json!("rgb 0 0 255")), Some(&rs[2]), "by hex"); + assert_eq!(row_listing(&rs[..2], &json!("rgb 0 0 255")), Some(&rs[0])); + assert_eq!(row_listing(&rs, &json!("rgb 255 255 0")), Some(&rs[4])); + } + #[test] fn next_seed_holds_at_the_largest() { assert_eq!(next_seed(&Dialog::new("recolor", json!({}))), 1); @@ -2801,4 +3448,844 @@ mod tests { let g = app.session.doc().unwrap().doc.swatch_groups.last().expect("a new color group"); assert_eq!(g.swatches.iter().filter_map(|w| w.paint.color()).collect::>(), [Color::rgb8(255, 128, 0)]); } + + /// Sets `field` of the open dialog to `value` as `ui.dialog.set` does: a refused value leaves + /// the dialog as it was. + fn set(app: &mut VectorcraftApp, field: &str, value: Value) -> Result<(), String> { + let before = app.ui.dialog.clone(); + let old = app.ui.dialog.as_ref().and_then(|d| d.fields.get(field).cloned()); + if let Some(d) = app.ui.dialog.as_mut() { + crate::dialogs::set_field(d, field.into(), value); + } + let r = crate::dialogs::field_set(app, field, old.as_ref()); + if r.is_err() { + app.ui.dialog = before; + } + r + } + + fn group_hex(app: &VectorcraftApp, name: &str) -> Option> { + let doc = &app.session.doc().unwrap().doc; + doc.swatch_groups.iter().find(|g| g.name == name).map(|g| g.swatches.iter().filter_map(|w| w.paint.color()).map(|c| c.to_hex()).collect()) + } + + fn undo_len(app: &VectorcraftApp) -> usize { + app.session.doc().unwrap().history.undo.len() + } + + /// Sets `groupAction` to `a` as `ui.dialog.set` does and draws the frame that runs it. + fn act(app: &mut VectorcraftApp, ctx: &egui::Context, t: f64, a: &str) -> Result<(), String> { + set(app, GROUP_ACTION, json!(a))?; + frame(app, ctx, t, vec![], 0); + Ok(()) + } + + /// Without art: a group picked in the Color Groups list (the `group` field) gives the rows its + /// colors, and a name no group has is refused. Save Changes rewrites the selected group with the + /// rows' new colors and the name field, as one step, and records none when nothing changes; + /// Delete removes it, after which OK saves the rows as a new group; New Color Group adds one. + #[test] + fn the_color_groups_list_selects_saves_and_deletes_groups() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "A", "colors": ["#ff0000", "#00ff00"], "keepModel": true})).unwrap(); + app.run("swatch.newGroup", json!({"name": "B", "colors": ["#0000ff", "#ffff00", "#ffffff"], "keepModel": true})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "A"})).unwrap(); + assert_eq!(new_colors(&app), [json!("rgb 255 0 0"), json!("rgb 0 255 0")]); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields[GROUP_STORAGE], true, "the list opens shown"); + + set(&mut app, "group", json!("B")).unwrap(); + assert_eq!(new_colors(&app), [json!("rgb 0 0 255"), json!("rgb 255 255 0"), json!("rgb 255 255 255")]); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("groupName"), "B"); + assert_eq!(set(&mut app, "group", json!("Nope")), Err("no colour group `Nope`".into())); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["group"], "B", "a refused name leaves B selected"); + assert!(set(&mut app, GROUP_STORAGE, json!("yes")).is_err()); + assert!(set(&mut app, GROUP_ACTION, json!("rename")).is_err()); + + let undo = undo_len(&app); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + rs[0]["to"] = json!("rgb 0 0 0"); + d.fields.insert("rows".into(), Value::Array(rs)); + d.fields.insert("groupName".into(), json!("Night")); + act(&mut app, &ctx, 0.1, "save").unwrap(); + assert_eq!(group_hex(&app, "Night"), Some(vec!["#000000".into(), "#ffff00".into(), "#ffffff".into()])); + assert_eq!(group_hex(&app, "B"), None, "renamed"); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["group"], "Night"); + assert_eq!(undo_len(&app), undo + 1, "one step"); + act(&mut app, &ctx, 0.2, "save").unwrap(); + assert_eq!(undo_len(&app), undo + 1, "saving the same colors again records no step"); + + act(&mut app, &ctx, 0.3, "delete").unwrap(); + assert_eq!(group_hex(&app, "Night"), None); + assert_eq!(undo_len(&app), undo + 2); + let d = app.ui.dialog.as_ref().unwrap(); + assert!(d.fields["group"].is_null() && d.bool("__newGroup"), "{:?}", d.fields); + assert_eq!(act(&mut app, &ctx, 0.4, "delete"), Err("missing `group`".into())); + assert_eq!(act(&mut app, &ctx, 0.5, "save"), Err("missing `group`".into())); + assert_eq!(undo_len(&app), undo + 2, "a refused button records no step"); + + let n = app.session.doc().unwrap().doc.swatch_groups.len(); + act(&mut app, &ctx, 0.6, "new").unwrap(); + let doc = &app.session.doc().unwrap().doc; + assert_eq!(doc.swatch_groups.len(), n + 1); + let last: Vec = doc.swatch_groups.last().unwrap().swatches.iter().filter_map(|w| w.paint.color()).map(|c| c.to_hex()).collect(); + assert_eq!(last, ["#000000", "#ffff00", "#ffffff"]); + assert_eq!(group_hex(&app, "A"), Some(vec!["#ff0000".into(), "#00ff00".into()]), "other groups are left as they are"); + } + + /// Without art: after a group is picked in the list, the same Color Theme Picker picks that gave + /// the group before it its colors give the new group's rows the palette of the art picked too. + #[test] + fn theme_picks_apply_again_after_another_group_is_picked() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + square(&mut app, 100.0, "#00ff00"); + app.run("select.set", json!({"ids": []})).unwrap(); + app.run("swatch.newGroup", json!({"name": "A", "colors": ["#ff0000", "#0000ff"], "keepModel": true})).unwrap(); + app.run("swatch.newGroup", json!({"name": "B", "colors": ["#0000ff", "#ffff00", "#ffffff"], "keepModel": true})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "A"})).unwrap(); + frame(&mut app, &ctx, 0.0, vec![], 0); + let picks = json!([{"at": [107, 17]}]); + app.ui.dialog.as_mut().unwrap().fields.insert(THEME_PICKS.into(), picks.clone()); + frame(&mut app, &ctx, 0.1, vec![], 0); + assert_eq!(new_colors(&app), [json!("rgb 0 255 0"), json!("rgb 0 255 0")]); + set(&mut app, "group", json!("B")).unwrap(); + frame(&mut app, &ctx, 0.2, vec![], 0); + assert_eq!(new_colors(&app), [json!("rgb 0 0 255"), json!("rgb 255 255 0"), json!("rgb 255 255 255")]); + app.ui.dialog.as_mut().unwrap().fields.insert(THEME_PICKS.into(), picks); + frame(&mut app, &ctx, 0.3, vec![], 0); + assert_eq!(new_colors(&app), [json!("rgb 0 255 0"), json!("rgb 0 255 0"), json!("rgb 0 255 0")], "the picks apply to B's rows"); + } + + /// Save Changes on a group with a swatch that is not a color is refused, renamed or not, and + /// leaves the group as it is: the rows hold only its colors. + #[test] + fn saving_a_group_with_a_swatch_that_is_not_a_color_is_refused() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Mixed", "colors": ["#ff0000", "#00ff00"], "keepModel": true})).unwrap(); + let doc = std::sync::Arc::make_mut(&mut app.session.doc_mut().unwrap().doc); + let g = doc.swatch_groups.iter_mut().find(|g| g.name == "Mixed").unwrap(); + g.swatches.insert(1, fade_swatch()); + app.run("ui.recolorDialog", json!({"group": "Mixed"})).unwrap(); + assert_eq!(new_colors(&app), [json!("rgb 255 0 0"), json!("rgb 0 255 0")]); + let undo = undo_len(&app); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + rs[0]["to"] = json!("rgb 0 0 0"); + d.fields.insert("rows".into(), Value::Array(rs)); + let refused: Result<(), String> = Err("color group `Mixed` holds swatches that are not colors, which Save Changes can't keep".into()); + assert_eq!(act(&mut app, &ctx, 0.1, "save"), refused); + app.ui.dialog.as_mut().unwrap().fields.insert("groupName".into(), json!("Renamed")); + assert_eq!(act(&mut app, &ctx, 0.2, "save"), refused); + // OK first runs a save set together with it, and the dialog stays open. + app.ui.dialog.as_mut().unwrap().fields.insert(GROUP_ACTION.into(), json!("save")); + assert!(crate::dialogs::confirm(&mut app).is_err()); + assert!(app.ui.dialog.is_some()); + let g = app.session.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Mixed").unwrap(); + assert_eq!(g.swatches[1], fade_swatch(), "the swatch is kept"); + assert_eq!(group_hex(&app, "Mixed"), Some(vec!["#ff0000".into(), "#00ff00".into()])); + assert_eq!(undo_len(&app), undo, "no step"); + } + + /// A gradient swatch, for a color group. + fn fade_swatch() -> vectorcraft_color::Swatch { + let paint = vectorcraft_color::Paint::Gradient(Box::new(vectorcraft_color::GradientPaint::new(Default::default()))); + vectorcraft_color::Swatch { name: "Fade".into(), paint, global: false, spot: false } + } + + /// With art, the preview rewrites the group being edited, its other swatch included; Save + /// Changes is still refused, as the group is without the preview, and Cancel leaves it as it was. + #[test] + fn saving_a_group_with_a_swatch_that_is_not_a_color_is_refused_while_previewing() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Mixed", "colors": ["#ff0000", "#0000ff"], "keepModel": true})).unwrap(); + let doc = std::sync::Arc::make_mut(&mut app.session.doc_mut().unwrap().doc); + let g = doc.swatch_groups.iter_mut().find(|g| g.name == "Mixed").unwrap(); + g.swatches.push(fade_swatch()); + let (red, blue) = (square(&mut app, 10.0, "#ff0000"), square(&mut app, 40.0, "#0000ff")); + app.run("select.set", json!({"ids": [red, blue]})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Mixed"})).unwrap(); + frame(&mut app, &ctx, 0.0, vec![], 0); + let undo = undo_len(&app); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + rs[0]["to"] = json!("rgb 0 0 0"); + d.fields.insert("rows".into(), Value::Array(rs)); + frame(&mut app, &ctx, 0.1, vec![], 0); + assert!(app.session.in_interaction(), "the art previews"); + let previewed = app.session.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Mixed").map(|g| g.swatches.len()); + assert_eq!(previewed, Some(2), "the preview's rewrite of the group leaves out its other swatch"); + let refused: Result<(), String> = Err("color group `Mixed` holds swatches that are not colors, which Save Changes can't keep".into()); + assert_eq!(act(&mut app, &ctx, 0.2, "save"), refused); + crate::dialogs::cancel(&mut app); + let g = app.session.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Mixed").unwrap(); + assert_eq!(g.swatches.last(), Some(&fade_swatch()), "the swatch is kept"); + assert_eq!(group_hex(&app, "Mixed"), Some(vec!["#ff0000".into(), "#0000ff".into()])); + assert_eq!(undo_len(&app), undo, "no step"); + } + + /// Save Changes on a group whose global swatches the selected art is linked to: the art takes + /// the group's new colors, and the rows are read from the art again, so they list its colors as + /// they are now. A color the art had before keeps its row's new color; a color the save gave + /// it stays as it is. + #[test] + fn saving_a_group_the_art_links_to_reads_the_rows_again() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + let (red, blue) = (square(&mut app, 10.0, "#ff0000"), square(&mut app, 40.0, "#0000ff")); + app.run("select.set", json!({"ids": [red, blue]})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Linked", "fromArtwork": true, "toGlobal": true})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Linked"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + if r["from"].as_array().is_some_and(|f| f.contains(&json!("rgb 255 0 0"))) { + r["to"] = json!("rgb 0 128 0"); + } + } + d.fields.insert("rows".into(), Value::Array(rs)); + act(&mut app, &ctx, 0.1, "save").unwrap(); + frame(&mut app, &ctx, 0.2, vec![], 0); + // The rows took the group's colors in their order, so one of the swatches is now green. + let saved = group_hex(&app, "Linked").unwrap(); + assert!(saved.len() == 2 && saved.contains(&"#008000".to_string()), "{saved:?}"); + let mut want = saved.clone(); + want.sort(); + assert_eq!(fill_hex(&app, red), "#008000", "the red square keeps the new color its row gave it"); + for r in super::rows(app.ui.dialog.as_ref().unwrap()) { + if !from_colors(&r).iter().any(|c| ["#ff0000", "#0000ff"].contains(&c.to_hex().as_str())) { + assert!(excluded(&r) && r["to"] == r["from"][0], "a color the save gave the art stays: {r}"); + } + } + let mut froms: Vec = super::rows(app.ui.dialog.as_ref().unwrap()).iter().flat_map(from_colors).map(|c| c.to_hex()).collect(); + froms.sort(); + assert_eq!(froms, want, "the rows list the art's colors as they are now"); + assert!(apply_params(app.ui.dialog.as_ref().unwrap()).get("group").is_none(), "OK leaves the saved group as it is"); + // OK with only a new name keeps the preview as one step and renames the group, keeping its + // saved colors. + let undo = undo_len(&app); + let mut d = app.ui.dialog.clone().unwrap(); + d.fields.insert("groupName".into(), json!("Renamed")); + confirm(&mut app, &d).unwrap(); + assert_eq!(group_hex(&app, "Renamed"), Some(saved)); + assert_eq!(group_hex(&app, "Linked"), None); + assert_eq!(fill_hex(&app, red), "#008000"); + assert_eq!(undo_len(&app), undo + 1); + } + + /// OK with only a new name after Save Changes leaves every swatch of the group its exact color: + /// a CMYK swatch no row lists keeps components finer than a hundredth of a percent. + #[test] + fn renaming_a_saved_group_keeps_its_exact_colors() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + let (red, blue) = (square(&mut app, 10.0, "#ff0000"), square(&mut app, 40.0, "#0000ff")); + app.run("select.set", json!({"ids": [red, blue]})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Linked", "fromArtwork": true, "toGlobal": true})).unwrap(); + let fine = Color::cmyk(0.123_456, 0.654_321, 0.0, 0.010_101); + let doc = std::sync::Arc::make_mut(&mut app.session.doc_mut().unwrap().doc); + let g = doc.swatch_groups.iter_mut().find(|g| g.name == "Linked").unwrap(); + g.swatches.push(vectorcraft_color::Swatch { name: "Fine".into(), paint: vectorcraft_color::Paint::solid(fine), global: false, spot: false }); + app.run("ui.recolorDialog", json!({"group": "Linked"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + if r["from"].as_array().is_some_and(|f| f.contains(&json!("rgb 255 0 0"))) { + r["to"] = json!("rgb 0 128 0"); + } + } + d.fields.insert("rows".into(), Value::Array(rs)); + act(&mut app, &ctx, 0.1, "save").unwrap(); + frame(&mut app, &ctx, 0.2, vec![], 0); + let swatches = |app: &VectorcraftApp, name: &str| { + let doc = &app.session.doc().unwrap().doc; + doc.swatch_groups.iter().find(|g| g.name == name).map(|g| g.swatches.iter().map(|w| w.paint.color()).collect::>()) + }; + let saved = swatches(&app, "Linked").unwrap(); + assert_eq!(saved.last(), Some(&Some(fine)), "Save Changes keeps the swatch no row lists"); + let mut d = app.ui.dialog.clone().unwrap(); + d.fields.insert("groupName".into(), json!("Renamed")); + confirm(&mut app, &d).unwrap(); + assert_eq!(swatches(&app, "Renamed"), Some(saved), "the rename keeps every color exactly"); + } + + /// Save Changes where one row's new color is another row's current color: the art linked to the + /// group keeps the colors the save gave it, and is not recolored again by the other row; a + /// Global Adjust set afterwards gives OK the group again. + #[test] + fn saving_a_group_keeps_the_colors_it_gave_the_linked_art() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + let (red, blue) = (square(&mut app, 10.0, "#ff0000"), square(&mut app, 40.0, "#0000ff")); + app.run("select.set", json!({"ids": [red, blue]})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Linked", "fromArtwork": true, "toGlobal": true})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Linked"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + let from = from_colors(r).first().map(|c| c.to_hex()); + r["to"] = match from.as_deref() { + Some("#ff0000") => json!("rgb 0 0 255"), + _ => json!("rgb 0 128 0"), + }; + } + d.fields.insert("rows".into(), Value::Array(rs)); + act(&mut app, &ctx, 0.1, "save").unwrap(); + frame(&mut app, &ctx, 0.2, vec![], 0); + let mut group = group_hex(&app, "Linked").unwrap(); + group.sort(); + let mut fills = vec![fill_hex(&app, red), fill_hex(&app, blue)]; + fills.sort(); + assert_eq!(fills, group, "the art shows the saved group's colors, not a second recolor"); + assert!(apply_params(app.ui.dialog.as_ref().unwrap()).get("group").is_none()); + app.ui.dialog.as_mut().unwrap().fields.insert("globalAdjust".into(), json!({"brightness": -50.0})); + assert!(apply_params(app.ui.dialog.as_ref().unwrap()).get("group").is_some(), "a new Global Adjust rewrites the group at OK"); + } + + /// Save Changes with art in only some colors of the group: the swatches keep their order, and a + /// swatch no row lists keeps its color. + #[test] + fn saving_a_group_keeps_the_swatches_the_art_does_not_use() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + let red = square(&mut app, 10.0, "#ff0000"); + let blue = square(&mut app, 40.0, "#0000ff"); + let yellow = square(&mut app, 70.0, "#ffff00"); + app.run("select.set", json!({"ids": [red, blue, yellow]})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Linked", "fromArtwork": true, "toGlobal": true})).unwrap(); + let order = group_hex(&app, "Linked").unwrap(); + app.run("select.set", json!({"ids": [blue, yellow]})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Linked"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + let to = match from_colors(r).first().map(|c| c.to_hex()).as_deref() { + Some("#0000ff") => json!("rgb 0 128 0"), + _ => r["from"][0].clone(), + }; + r["to"] = to; + } + d.fields.insert("rows".into(), Value::Array(rs)); + act(&mut app, &ctx, 0.1, "save").unwrap(); + let want: Vec = order.iter().map(|h| if h == "#0000ff" { "#008000".into() } else { h.clone() }).collect(); + assert_eq!(group_hex(&app, "Linked"), Some(want), "the swatches keep their order and the red one its color"); + assert_eq!(fill_hex(&app, red), "#ff0000", "art linked to a swatch no row lists is left as it is"); + } + + /// Save Changes with art in colors of the group keeps the Edit tab's changes: a removed color's + /// swatch is removed, and a color added on the Edit tab joins the group after the others. + #[test] + fn saving_a_group_keeps_added_and_removed_colors() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + let red = square(&mut app, 10.0, "#ff0000"); + let blue = square(&mut app, 40.0, "#0000ff"); + let yellow = square(&mut app, 70.0, "#ffff00"); + app.run("select.set", json!({"ids": [red, blue, yellow]})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Linked", "fromArtwork": true, "toGlobal": true})).unwrap(); + let order = group_hex(&app, "Linked").unwrap(); + app.run("ui.recolorDialog", json!({"group": "Linked"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + let to = match from_colors(r).first().map(|c| c.to_hex()).as_deref() { + Some("#0000ff") => Value::Null, + _ => r["from"][0].clone(), + }; + r["to"] = to; + } + rs.push(json!({"from": [], "to": "rgb 0 128 0", "added": true})); + d.fields.insert("rows".into(), Value::Array(rs)); + act(&mut app, &ctx, 0.1, "save").unwrap(); + let mut want: Vec = order.into_iter().filter(|h| h != "#0000ff").collect(); + want.push("#008000".into()); + assert_eq!(group_hex(&app, "Linked"), Some(want.clone()), "the removed swatch goes and the added color follows the others"); + assert_eq!(fill_hex(&app, blue), "#0000ff", "art linked to a removed swatch keeps its color"); + let rs = super::rows(app.ui.dialog.as_ref().unwrap()); + assert!(rs.iter().all(|r| !r["to"].is_null() && !is_added(r)), "the rows follow the saved group: {rs:?}"); + let assign = app.ui.dialog.as_ref().unwrap().fields["__assign"].clone(); + let assign: Vec = assign.as_array().unwrap().iter().filter_map(color_value).map(|c| c.to_hex()).collect(); + assert_eq!(Some(assign), group_hex(&app, "Linked"), "a later edit gives the group no removed swatch back"); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(group_hex(&app, "Linked"), Some(want), "OK removes and adds nothing more"); + } + + /// Save Changes that recolors linked art reads the rows from the art again; a color added on the + /// Edit tab stays one of the group's colors and a removed one does not come back, so OK after a + /// further edit keeps them as saved. + #[test] + fn saving_a_group_that_reads_the_rows_again_keeps_an_added_color() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + let red = square(&mut app, 10.0, "#ff0000"); + let blue = square(&mut app, 40.0, "#0000ff"); + let lime = square(&mut app, 70.0, "#00ff00"); + app.run("select.set", json!({"ids": [red, blue, lime]})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Linked", "fromArtwork": true, "toGlobal": true})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Linked"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + let to = match from_colors(r).first().map(|c| c.to_hex()).as_deref() { + Some("#ff0000") => json!("rgb 0 128 0"), + Some("#00ff00") => Value::Null, + _ => r["from"][0].clone(), + }; + r["to"] = to; + } + rs.push(json!({"from": [], "to": "rgb 255 255 0", "added": true})); + d.fields.insert("rows".into(), Value::Array(rs)); + act(&mut app, &ctx, 0.1, "save").unwrap(); + assert_eq!(fill_hex(&app, red), "#008000", "the save recolored the linked art"); + assert_eq!(fill_hex(&app, lime), "#00ff00", "art linked to the removed swatch keeps its color"); + let group = group_hex(&app, "Linked").unwrap(); + assert!(group.contains(&"#ffff00".to_string()) && !group.contains(&"#00ff00".to_string()), "{group:?}"); + let mut d = app.ui.dialog.clone().unwrap(); + let mut rs = super::rows(&d); + assert!(rs.iter().all(|r| !is_added(r)), "{rs:?}"); + if let Some(r) = rs.last_mut() { + r["to"] = json!("rgb 10 10 10"); + } + d.fields.insert("rows".into(), Value::Array(rs)); + let colors = sent_by(&app, &d); + assert_eq!(colors.iter().filter(|c| *c == "#ffff00").count(), 1, "OK after a further edit keeps the added color once: {colors:?}"); + assert!(!colors.contains(&"#00ff00".to_string()), "nor brings the removed color back: {colors:?}"); + } + + /// Save Changes where the rows list their current colors as "#rrggbb": a row matches the swatch + /// of the same color, so the swatches keep their order and the one a row lists takes its new + /// color; read again afterwards, a row whose old entry was a hex keeps its new color. + #[test] + fn saving_a_group_matches_rows_that_list_hex_colors() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + let red = square(&mut app, 10.0, "#ff0000"); + let blue = square(&mut app, 40.0, "#0000ff"); + let yellow = square(&mut app, 70.0, "#ffff00"); + app.run("select.set", json!({"ids": [red, blue, yellow]})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Linked", "fromArtwork": true, "toGlobal": true})).unwrap(); + let order = group_hex(&app, "Linked").unwrap(); + let orange = square(&mut app, 100.0, "#ff8000"); + app.run("select.set", json!({"ids": [blue, yellow, orange]})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Linked"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + let hex: Vec = from_colors(r).iter().map(|c| c.to_hex()).collect(); + r["to"] = match hex.first().map(String::as_str) { + Some("#0000ff") => json!("rgb 0 128 0"), + Some("#ff8000") => json!("rgb 128 0 128"), + _ => r["from"][0].clone(), + }; + r["from"] = json!(hex); + } + d.fields.insert("rows".into(), Value::Array(rs)); + act(&mut app, &ctx, 0.1, "save").unwrap(); + let want: Vec = order.iter().map(|h| if h == "#0000ff" { "#008000".into() } else { h.clone() }).collect(); + assert_eq!(group_hex(&app, "Linked"), Some(want), "the blue swatch takes the green, the red one keeps its color"); + assert_eq!((fill_hex(&app, red), fill_hex(&app, blue)), ("#ff0000".into(), "#008000".into())); + let rs = super::rows(app.ui.dialog.as_ref().unwrap()); + let o = rs.iter().find(|r| from_colors(r).iter().any(|c| c.to_hex() == "#ff8000")).unwrap(); + assert!(!excluded(o) && o["to"] == json!("rgb 128 0 128"), "the orange row keeps its new color: {o}"); + } + + /// Save Changes with art in the group's colors that is not linked to its swatches: the art is + /// left to the preview, and OK leaves the saved group as it is until the rows change. + #[test] + fn saving_a_group_with_unlinked_art_keeps_the_saved_group_at_ok() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Plain", "colors": ["#ff0000", "#0000ff"], "keepModel": true})).unwrap(); + let (red, blue) = (square(&mut app, 10.0, "#ff0000"), square(&mut app, 40.0, "#0000ff")); + app.run("select.set", json!({"ids": [red, blue]})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Plain"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + let to = match from_colors(r).first().map(|c| c.to_hex()).as_deref() { + Some("#0000ff") => json!("rgb 0 128 0"), + _ => r["from"][0].clone(), + }; + r["to"] = to; + } + d.fields.insert("rows".into(), Value::Array(rs)); + act(&mut app, &ctx, 0.1, "save").unwrap(); + assert_eq!(group_hex(&app, "Plain"), Some(vec!["#ff0000".into(), "#008000".into()])); + frame(&mut app, &ctx, 0.2, vec![], 0); + assert_eq!(fill_hex(&app, blue), "#008000", "the art previews its row's new color"); + assert!(apply_params(app.ui.dialog.as_ref().unwrap()).get("group").is_none(), "OK leaves the saved group as it is"); + } + + /// The colors `d`'s OK gives the selected group, as hex, `"keep"` read as the color the swatch + /// at its place has. + fn sent_by(app: &VectorcraftApp, d: &Dialog) -> Vec { + let own = group_hex(app, &d.str("group")).unwrap_or_default(); + let p = apply_params(d); + let hex = |(i, k): (usize, &Value)| if *k == json!("keep") { own.get(i).cloned() } else { color_value(k).map(|c| c.to_hex()) }; + p["groupColors"].as_array().unwrap().iter().enumerate().filter_map(hex).collect() + } + + /// The colors OK gives the selected group, as [`sent_by`] reads them. + fn sent_hex(app: &VectorcraftApp) -> Vec { + sent_by(app, app.ui.dialog.as_ref().unwrap()) + } + + /// Sets the new color of the rows whose first current color is `hex` to `to`. + fn set_row(app: &mut VectorcraftApp, hex: &str, to: Value) { + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + if from_colors(r).first().map(|c| c.to_hex()).as_deref() == Some(hex) { + r["to"] = to.clone(); + } + } + d.fields.insert("rows".into(), Value::Array(rs)); + } + + /// With unlinked art in some of the group's colors, a second Save Changes after a further edit of + /// a row gives the swatch the first save gave that row's color the row's new color, and OK does + /// too; the swatch no row lists keeps its color both times. + #[test] + fn saving_a_group_twice_with_unlinked_art_gives_a_row_its_swatch_again() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Plain", "colors": ["#ff0000", "#0000ff", "#ffff00"], "keepModel": true})).unwrap(); + let (blue, yellow) = (square(&mut app, 10.0, "#0000ff"), square(&mut app, 40.0, "#ffff00")); + app.run("select.set", json!({"ids": [blue, yellow]})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Plain"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + set_row(&mut app, "#0000ff", json!("rgb 0 128 0")); + set_row(&mut app, "#ffff00", json!("rgb 255 255 0")); + act(&mut app, &ctx, 0.1, "save").unwrap(); + assert_eq!(group_hex(&app, "Plain"), Some(vec!["#ff0000".into(), "#008000".into(), "#ffff00".into()])); + frame(&mut app, &ctx, 0.2, vec![], 0); + set_row(&mut app, "#0000ff", json!("rgb 128 0 128")); + let sent = sent_hex(&app); + assert_eq!(sent, ["#ff0000", "#800080", "#ffff00"], "OK gives the blue row's swatch its new color"); + act(&mut app, &ctx, 0.3, "save").unwrap(); + assert_eq!(group_hex(&app, "Plain"), Some(vec!["#ff0000".into(), "#800080".into(), "#ffff00".into()]), "the second save does too"); + } + + /// Without art, an excluded row leaves its swatch its own color at Save Changes and at OK, even + /// when its new color was changed before it was excluded. + #[test] + fn saving_a_group_without_art_keeps_an_excluded_rows_color() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Plain", "colors": ["#ff0000", "#0000ff"], "keepModel": true})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Plain"})).unwrap(); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + if from_colors(r).first().map(|c| c.to_hex()).as_deref() == Some("#ff0000") { + r["to"] = json!("rgb 0 128 0"); + r["exclude"] = json!(true); + } + } + d.fields.insert("rows".into(), Value::Array(rs)); + let sent = sent_hex(&app); + assert_eq!(sent, ["#ff0000", "#0000ff"], "OK keeps the excluded row's swatch"); + let p = apply_params(app.ui.dialog.as_ref().unwrap()); + assert_eq!(p["groupColors"][0], "keep", "so the Global Adjust leaves it as it is too: {p}"); + act(&mut app, &ctx, 0.1, "save").unwrap(); + assert_eq!(group_hex(&app, "Plain"), Some(vec!["#ff0000".into(), "#0000ff".into()]), "so does Save Changes"); + } + + /// With art in more colors than the group has swatches, an excluded row past the swatches adds + /// no color at Save Changes, as at OK. + #[test] + fn saving_a_group_with_art_adds_no_color_for_an_excluded_row_past_its_swatches() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Plain", "colors": ["#ff0000"], "keepModel": true})).unwrap(); + let (blue, yellow) = (square(&mut app, 10.0, "#0000ff"), square(&mut app, 40.0, "#ffff00")); + app.run("select.set", json!({"ids": [blue, yellow]})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Plain"})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("method".into(), json!(Method::Exact.id())); + d.fields.insert("colors".into(), json!(2)); + d.fields.remove(REDUCED); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + assert_eq!(rs.len(), 2, "a row for each color of the art: {rs:?}"); + for r in &mut rs { + r["exclude"] = json!(true); + } + d.fields.insert("rows".into(), Value::Array(rs)); + // `recolor.apply` adds nothing for a "keep" past the group's swatches. + assert_eq!(apply_params(app.ui.dialog.as_ref().unwrap())["groupColors"], json!(["keep", "keep"]), "OK adds no color"); + act(&mut app, &ctx, 0.1, "save").unwrap(); + assert_eq!(group_hex(&app, "Plain"), Some(vec!["#ff0000".into()]), "Save Changes adds none either"); + } + + /// Without art, a row excluded after Save Changes gave its swatch a new color leaves the swatch + /// that saved color at a second Save Changes, as OK does. + #[test] + fn saving_a_group_without_art_keeps_a_saved_color_when_its_row_is_excluded() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Plain", "colors": ["#ff0000", "#0000ff"], "keepModel": true})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Plain"})).unwrap(); + frame(&mut app, &ctx, 0.0, vec![], 0); + set_row(&mut app, "#ff0000", json!("rgb 0 128 0")); + act(&mut app, &ctx, 0.1, "save").unwrap(); + assert_eq!(group_hex(&app, "Plain"), Some(vec!["#008000".into(), "#0000ff".into()])); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + if r["to"] == json!("rgb 0 128 0") { + r["exclude"] = json!(true); + } + } + d.fields.insert("rows".into(), Value::Array(rs)); + assert_eq!(sent_hex(&app), ["#008000", "#0000ff"], "OK keeps the saved color"); + act(&mut app, &ctx, 0.2, "save").unwrap(); + assert_eq!(group_hex(&app, "Plain"), Some(vec!["#008000".into(), "#0000ff".into()]), "so does a second Save Changes"); + } + + /// Save Changes that recolors linked art so that one swatch takes another swatch's old color: + /// read again, the row of the second swatch's new color gives that swatch a later new color. + #[test] + fn saving_a_group_twice_with_linked_art_finds_the_row_of_a_swatchs_new_color() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + let (red, blue) = (square(&mut app, 10.0, "#ff0000"), square(&mut app, 40.0, "#0000ff")); + app.run("select.set", json!({"ids": [red, blue]})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Linked", "fromArtwork": true, "toGlobal": true})).unwrap(); + assert_eq!(group_hex(&app, "Linked"), Some(vec!["#ff0000".into(), "#0000ff".into()])); + app.run("ui.recolorDialog", json!({"group": "Linked"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + set_row(&mut app, "#ff0000", json!("rgb 0 0 255")); + set_row(&mut app, "#0000ff", json!("rgb 0 128 0")); + act(&mut app, &ctx, 0.1, "save").unwrap(); + frame(&mut app, &ctx, 0.2, vec![], 0); + assert_eq!(group_hex(&app, "Linked"), Some(vec!["#0000ff".into(), "#008000".into()])); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + if from_colors(r).first().map(|c| c.to_hex()).as_deref() == Some("#008000") { + r["to"] = json!("rgb 128 0 128"); + r["exclude"] = json!(false); + } + } + d.fields.insert("rows".into(), Value::Array(rs)); + assert_eq!(sent_hex(&app), ["#0000ff", "#800080"], "OK gives the green swatch the green row's new color"); + act(&mut app, &ctx, 0.3, "save").unwrap(); + assert_eq!(group_hex(&app, "Linked"), Some(vec!["#0000ff".into(), "#800080".into()]), "so does Save Changes"); + } + + /// Save Changes with a Global Adjust: the saved group holds it, the rows' new colors take it and + /// it goes back to 0%, so OK with a new name renames the group without adjusting it again. + #[test] + fn saving_a_group_with_a_global_adjust_applies_it_once() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Plain", "colors": ["#ff0000", "#0000ff"], "keepModel": true})).unwrap(); + let (red, blue) = (square(&mut app, 10.0, "#ff0000"), square(&mut app, 40.0, "#0000ff")); + app.run("select.set", json!({"ids": [red, blue]})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Plain"})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("method".into(), json!(Method::Exact.id())); + d.fields.insert("globalAdjust".into(), json!({"brightness": -50.0})); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + act(&mut app, &ctx, 0.1, "save").unwrap(); + let saved = group_hex(&app, "Plain").unwrap(); + assert!(!saved.contains(&"#ff0000".to_string()), "the save darkened the group: {saved:?}"); + frame(&mut app, &ctx, 0.2, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + assert_eq!(adjust_values(d), [0.0; 4]); + d.fields.insert("groupName".into(), json!("Dark")); + let p = apply_params(app.ui.dialog.as_ref().unwrap()); + assert!(p.get("globalAdjust").is_none(), "{p}"); + assert_eq!(p["groupColors"], json!(vec!["keep"; saved.len()]), "OK keeps each saved color"); + let d = app.ui.dialog.clone().unwrap(); + confirm(&mut app, &d).unwrap(); + assert_eq!(group_hex(&app, "Dark"), Some(saved), "OK renames the group with its saved colors"); + } + + /// Without art, Save Changes with a Global Adjust gives the group the rows' new colors with the + /// adjustment, and OK gives it the same colors again: the adjustment applies to the rows' new + /// colors, not to the saved group. + #[test] + fn saving_a_group_without_art_with_a_global_adjust_applies_it_once() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Plain", "colors": ["#ff0000", "#0000ff"], "keepModel": true})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Plain"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("globalAdjust".into(), json!({"brightness": -50.0})); + frame(&mut app, &ctx, 0.0, vec![], 0); + act(&mut app, &ctx, 0.1, "save").unwrap(); + let saved = group_hex(&app, "Plain").unwrap(); + assert!(!saved.contains(&"#ff0000".to_string()), "the save darkened the group: {saved:?}"); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(group_hex(&app, "Plain").unwrap(), saved, "OK does not darken the group again"); + } + + /// With Limit to Library, Save Changes gives the group the library's nearest color to a row's + /// new color, as OK does, also when the rows were set without being snapped. + #[test] + fn saving_a_group_snaps_its_colors_to_the_library() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + let doc = &app.session.doc().unwrap().doc; + let names: Vec<_> = doc + .swatches + .iter() + .filter(|s| !s.is_reserved()) + .map(|s| s.name.clone()) + .chain(doc.swatch_groups.iter().map(|g| g.name.clone())) + .collect(); + app.run("swatch.delete", json!({"names": names})).unwrap(); + app.run("swatch.new", json!({"name": "Only Yellow", "color": "#ffff00"})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Plain", "colors": ["#ffff00"], "keepModel": true})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Plain"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("limitTo".into(), json!("document")); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + rs[0]["to"] = json!("rgb 250 250 10"); + d.fields.insert("rows".into(), Value::Array(rs)); + act(&mut app, &ctx, 0.1, "save").unwrap(); + assert_eq!(group_hex(&app, "Plain"), Some(vec!["#ffff00".into()]), "the saved color is the library's"); + } + + /// Without art, Save Changes removes a removed color's swatch and adds a color added on the Edit + /// tab, and OK afterwards gives the group the same colors: it removes and adds nothing more. + #[test] + fn saving_a_group_without_art_with_added_and_removed_colors_keeps_them_at_ok() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Plain", "colors": ["#ff0000", "#00ff00", "#0000ff"], "keepModel": true})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Plain"})).unwrap(); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + if from_colors(r).first().map(|c| c.to_hex()).as_deref() == Some("#00ff00") { + r["to"] = Value::Null; + } + } + // The added color's row was moved ahead of the others. + rs.insert(0, json!({"from": [], "to": "rgb 255 255 0", "added": true})); + d.fields.insert("rows".into(), Value::Array(rs)); + act(&mut app, &ctx, 0.1, "save").unwrap(); + let want: Vec = ["#ff0000", "#0000ff", "#ffff00"].map(String::from).to_vec(); + assert_eq!(group_hex(&app, "Plain"), Some(want.clone()), "the save removes green and adds yellow"); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(group_hex(&app, "Plain"), Some(want), "OK gives the group the same colors"); + } + + /// With art: a group picked in the list reduces the art to a row per color of the group, which + /// become the rows' new colors, and the art previews them; the list draws beside the tabs and + /// hides with `groupStorage`. + #[test] + fn a_group_picked_in_the_list_recolors_the_art() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Warm", "colors": ["#ffff00", "#00ff00"], "keepModel": true})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Cool", "colors": ["#0000ff"], "keepModel": true})).unwrap(); + let (red, blue) = (square(&mut app, 10.0, "#ff0000"), square(&mut app, 40.0, "#0000ff")); + app.run("select.set", json!({"ids": [red, blue]})).unwrap(); + app.run("ui.recolorDialog", json!({})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + assert_eq!(fill_hex(&app, red), "#ff0000"); + // A button set with the group, before a frame, saves the rows the group gives the art. + let n = app.session.doc().unwrap().doc.swatch_groups.len(); + set(&mut app, "group", json!("Warm")).unwrap(); + act(&mut app, &ctx, 0.1, "new").unwrap(); + let doc = &app.session.doc().unwrap().doc; + let mut saved: Vec = doc.swatch_groups.last().unwrap().swatches.iter().filter_map(|w| w.paint.color()).map(|c| c.to_hex()).collect(); + saved.sort(); + assert_eq!((doc.swatch_groups.len(), saved), (n + 1, vec!["#00ff00".to_string(), "#ffff00".to_string()])); + frame(&mut app, &ctx, 0.2, vec![], 0); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(super::rows(d).len(), 2); + assert_eq!(d.str("groupName"), "Warm"); + let mut shown = [fill_hex(&app, red), fill_hex(&app, blue)]; + shown.sort(); + assert_eq!(shown, ["#00ff00", "#ffff00"], "the art previews the group's colors"); + // The name the preview gives the group being edited picks that group in the list. + app.ui.dialog.as_mut().unwrap().fields.insert("groupName".into(), json!("Sunny")); + frame(&mut app, &ctx, 0.21, vec![], 0); + set(&mut app, "group", json!("Sunny")).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((&d.fields["group"], &d.fields[GROUP_LOADED], d.str("groupName")), (&json!("Warm"), &json!("Warm"), "Sunny".into())); + // A group the document has under that name is picked instead. + app.ui.dialog.as_mut().unwrap().fields.insert("groupName".into(), json!("Cool")); + frame(&mut app, &ctx, 0.22, vec![], 0); + set(&mut app, "group", json!("Cool")).unwrap(); + frame(&mut app, &ctx, 0.23, vec![], 0); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((&d.fields[GROUP_LOADED], super::rows(d).len()), (&json!("Cool"), 1)); + set(&mut app, GROUP_STORAGE, json!(false)).unwrap(); + frame(&mut app, &ctx, 0.3, vec![], 0); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields[GROUP_STORAGE], false); + } } diff --git a/crates/ui-egui/src/dialogs/revolve.rs b/crates/ui-egui/src/dialogs/revolve.rs index 77c5980ec0..c7c98a5de0 100644 --- a/crates/ui-egui/src/dialogs/revolve.rs +++ b/crates/ui-egui/src/dialogs/revolve.rs @@ -733,7 +733,7 @@ pub(super) fn reset_dot(ui: &mut egui::Ui, key: &str, changed: bool, default: &s ui.painter().rect_filled(r, 3.0, Tokens::get(ui.ctx()).hover); } dot(ui, r.center(), changed); - response.on_hover_text(format!("{}: {default}", tl!("Reset to default"))).clicked() + response.on_hover_text(format!("{} {default}", crate::i18n::colon(tl!("Reset to default")))).clicked() } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/revolve_lights.rs b/crates/ui-egui/src/dialogs/revolve_lights.rs index 3d522b624a..dadab71c70 100644 --- a/crates/ui-egui/src/dialogs/revolve_lights.rs +++ b/crates/ui-egui/src/dialogs/revolve_lights.rs @@ -75,7 +75,8 @@ impl Light { /// The name screen readers give the light at `index`: its number, Rotation, Height and side. fn name(self, index: usize) -> String { let side = if self.behind { format!(", {}", tl!("Light behind the object")) } else { String::new() }; - format!("{} {}: {} {:.1}°, {} {:.1}°{side}", c3("Light"), index + 1, tl!("Rotation"), self.rotation, tl!("Height"), self.height) + let light = crate::i18n::colon(&format!("{} {}", c3("Light"), index + 1)); + format!("{light} {} {:.1}°, {} {:.1}°{side}", tl!("Rotation"), self.rotation, tl!("Height"), self.height) } } diff --git a/crates/ui-egui/src/dialogs/save_for_web.rs b/crates/ui-egui/src/dialogs/save_for_web.rs index 589d1dfdce..c412bc2dcb 100644 --- a/crates/ui-egui/src/dialogs/save_for_web.rs +++ b/crates/ui-egui/src/dialogs/save_for_web.rs @@ -2,13 +2,16 @@ //! as the web image Save writes, beside the original (Original, Optimized, 2-Up and 4-Up views, //! each with its file size and download time), and the settings: format (GIF, JPEG, PNG-8, //! PNG-24), colour reduction, colours, dither, transparency and matte, interlacing, web snap, -//! lossy, JPEG quality, the colour table (lock, map to transparent, web shift, sort), image size -//! and anti-aliasing, Clip to Artboard, sRGB, metadata, slices and HTML output, and presets. +//! lossy, JPEG quality, the colour table (lock, map to transparent, web shift, sort, Delete Color +//! and Restore Generated Table), image size and anti-aliasing, Clip to Artboard, sRGB, metadata, +//! slices and HTML output, and presets. //! //! Fields are the `document.exportForWeb` settings (`webExport.settings` gives them; set one with //! `ui.dialog.set`, or `preset` to load a preset), plus the dialog's own: `__view` (`original`, //! `optimized`, `2up`, `4up`), `__zoom` (`fit` or a percentage), `__kbps` (connection speed), -//! `__color` (the colour table's selected colour, by source), `__presetName` (shown while saving a +//! `__color` (the colour table's selected colour, by source: the one Lock, Transparent and Web +//! Shift edit, and where a Shift-click range starts), `__colors` (every selected color, by source, +//! which Delete Color deletes; when it is empty, `__color` alone), `__presetName` (shown while saving a //! preset) and `__hasSlices`. Optimize to File Size… (`__optimizeOpen: true`) shows `__optimizeK` (the desired size in K), //! `__optimizeStart` (`current`, `auto`) and with slices `__optimizeUse` (`allSlices`, //! `eachSlice`, `currentSlice`); `__optimizeGo: true` runs `webExport.optimizeToFileSize` and @@ -52,6 +55,8 @@ pub(super) const SPEC: DialogSpec = DialogSpec { /// The preview area (panes and their captions) and the settings column. const PREVIEW_W: f32 = 620.0; +/// The narrowest the panes get in a narrow window. +const MIN_PREVIEW_W: f32 = 240.0; const PREVIEW_H: f32 = 470.0; const SIDE_W: f32 = 296.0; const GAP: f32 = 16.0; @@ -107,10 +112,10 @@ fn remembered(app: &VectorcraftApp) -> WebSettings { /// Reset (Cancel with Alt or Option held, or `ui.dialogReset`): the settings go back to the /// remembered ones on the document's active artboard ([`remembered`]), and a pending `preset`, a /// pending Done (`discard`, which a failed Done leaves), the preset name being typed and the -/// selected color table entry are dropped. The view, zoom, connection speed and `path` stay, +/// selected color table entries are dropped. The view, zoom, connection speed and `path` stay, /// nothing is remembered or written, and the dialog stays open. fn reset(app: &VectorcraftApp, d: &mut Dialog) -> Result<(), String> { - for key in ["preset", "discard", "__presetName", "__color"] { + for key in ["preset", "discard", "__presetName", "__color", "__colors"] { d.fields.remove(key); } d.fields.extend(settings_fields(&remembered(app))); @@ -532,10 +537,19 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { } let settings = settings_of(app, d); let mut browser = false; - ui.horizontal_top(|ui| { + // In a window too narrow for both, the panes are narrower, so the settings beside them and the + // buttons below stay in view. The room is the screen's (the window's own width follows what it + // drew last), less a column for the bar of the body while it scrolls; the settings column is as + // wide as it was drawn last. + let bar = if super::modal::body_view(ui).is_some() { ui.spacing().scroll.allocated_width() } else { 0.0 }; + let room = ui.ctx().content_rect().width() - 2.0 * (f32::from(super::MARGIN) + super::EDGE_GAP) - bar; + let rest_id = egui::Id::unique("save-for-web-beside-panes"); + let rest = ui.ctx().data(|m| m.get_temp::(rest_id)).unwrap_or(ui.spacing().item_spacing.x + GAP + SIDE_W); + let preview_w = (room.min(ui.available_width()) - rest).clamp(MIN_PREVIEW_W, PREVIEW_W); + let row = ui.horizontal_top(|ui| { ui.vertical(|ui| { - ui.set_width(PREVIEW_W); - browser = preview_area(app, ui, d, &settings); + ui.set_width(preview_w); + browser = preview_area(app, ui, d, &settings, preview_w); }); ui.add_space(GAP); ui.vertical(|ui| { @@ -543,6 +557,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { side(app, ui, d, settings.as_ref().ok()); }); }); + let drawn = row.response.rect.width() - preview_w; + if (ui.ctx().data_mut(|m| std::mem::replace(m.get_temp_mut_or(rest_id, rest), drawn)) - drawn).abs() > 0.5 { + ui.ctx().request_repaint(); + } optimize_on_enter(ui.ctx(), d); if browser && let Err(e) = app.run("file.saveForWeb.browser", params(d)) { app.status(e); @@ -550,16 +568,16 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { false } -/// The view tabs, the panes and the zoom and speed row. Returns whether Preview in Browser was -/// clicked. -fn preview_area(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, settings: &Result) -> bool { +/// The view tabs, the panes (`width` wide) and the zoom and speed row. Returns whether Preview in +/// Browser was clicked. +fn preview_area(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, settings: &Result, width: f32) -> bool { let t = Tokens::get(ui.ctx()); let view = VIEWS.iter().position(|v| *v == d.str("__view")).unwrap_or(2); if let Some(i) = widgets::tab_bar(ui, &VIEW_LABELS, view) { d.fields.insert("__view".into(), json!(VIEWS[i])); } ui.add_space(4.0); - let (area, resp) = ui.allocate_exact_size(egui::vec2(PREVIEW_W, PREVIEW_H), egui::Sense::click_and_drag()); + let (area, resp) = ui.allocate_exact_size(egui::vec2(width, PREVIEW_H), egui::Sense::click_and_drag()); let pan_id = egui::Id::unique("save-for-web-pan"); let mut pan: egui::Vec2 = ui.ctx().data(|m| m.get_temp(pan_id)).unwrap_or_default(); if resp.dragged() { @@ -604,6 +622,17 @@ fn preview_area(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, set } ui.add_space(6.0); let mut browser = false; + // Preview in Browser goes on a row of its own when the panes are too narrow for it beside the + // two lists (its width as `widgets::secondary_button` draws it). + let label = tl!("Preview in Browser"); + let button_w = (ui.painter().layout_no_wrap(label.to_string(), crate::theme::semibold(12.5), t.text).size().x + 32.0).max(72.0); + let mut beside = false; + let mut button = |ui: &mut egui::Ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let b = ui.add_enabled(!io::is_web(app), |ui: &mut egui::Ui| widgets::secondary_button(ui, label)); + browser = b.on_disabled_hover_text(tl!("Needs the desktop app")).clicked(); + }); + }; ui.horizontal(|ui| { let z = ZOOMS.iter().position(|z| *z == d.str("__zoom")).unwrap_or(2); let zoom = ui.name_inputs(tl!("Zoom"), |ui| widgets::dropdown(ui, "sfw-zoom", ZOOM_LABELS[z], &ZOOM_LABELS, 110.0)); @@ -620,11 +649,15 @@ fn preview_area(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, set { d.fields.insert("__kbps".into(), json!(s)); } - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - let b = ui.add_enabled(!io::is_web(app), |ui: &mut egui::Ui| widgets::secondary_button(ui, tl!("Preview in Browser"))); - browser = b.on_disabled_hover_text(tl!("Needs the desktop app")).clicked(); - }); + beside = ui.available_width() >= button_w; + if beside { + button(ui); + } }); + if !beside { + ui.add_space(4.0); + ui.horizontal(button); + } browser } @@ -729,7 +762,8 @@ fn side(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, s: Option<& presets_row(app, ui, d, s); optimize_rows(ui, d, s, &art_key(app)); widgets::divider(ui); - egui::ScrollArea::vertical().id_salt("sfw-settings").max_height(PREVIEW_H - 40.0).auto_shrink([false, true]).show(ui, |ui| { + let list_h = super::modal::list_height(ui, PREVIEW_H - 40.0); + egui::ScrollArea::vertical().id_salt("sfw-settings").max_height(list_h).auto_shrink([false, true]).show(ui, |ui| { let choice = |ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str, options: &[(&str, &str)]| { form::choice(ui, d, key, label, (LABEL_W, FIELD_W), options); }; @@ -737,7 +771,12 @@ fn side(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, s: Option<& let format = s.map_or(WebFormat::Gif, |s| s.format); match format { WebFormat::Gif | WebFormat::Png8 => { + let reduction = d.str("reduction"); choice(ui, d, "reduction", tl!("Reduction:"), &pairs(&Reduction::ALL, Reduction::id, Reduction::label)); + // Another reduction makes a new palette. + if d.str("reduction") != reduction { + restore_table(d); + } colors_row(ui, d); choice(ui, d, "dither", tl!("Dither:"), &pairs(&Dither::ALL, Dither::id, Dither::label)); if Dither::from_id(&d.str("dither")).is_some_and(|x| x != Dither::None) { @@ -765,7 +804,9 @@ fn side(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, s: Option<& choice(ui, d, "metadata", tl!("Metadata:"), &pairs(&WebMetadata::ALL, WebMetadata::key, WebMetadata::label)); if format.palette() { widgets::divider(ui); - color_table(ui, d, s); + if let Err(e) = color_table(ui, d, s) { + app.status(e); + } } widgets::divider(ui); image_size(app, ui, d, s); @@ -1043,10 +1084,13 @@ fn matte_row(ui: &mut egui::Ui, d: &mut Dialog) { }); } -/// The colour table of the current settings' preview: swatches (the selected one ringed; locked -/// ones with a square, web-safe ones with a diamond, transparent ones over the grid) and the -/// buttons that edit the selected colour, plus the sort order. -fn color_table(ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>) { +/// The colour table of the current settings' preview: swatches (the selected ones ringed; locked +/// ones with a square, web-safe ones with a diamond, transparent ones over the grid), the buttons +/// that edit the selected colour, Delete Color and the table's menu, plus the sort order. A click +/// selects one color, a Shift-click the colors from the anchor, and a Ctrl-click +/// (Command-click on macOS) adds or removes one. Returns an error for a deletion that would leave +/// no color. +fn color_table(ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>) -> Result<(), String> { let t = Tokens::get(ui.ctx()); let cache: Option = ui.ctx().data(|m| m.get_temp(cache_id())); let key = s.map(|s| s.to_json().to_string()); @@ -1054,10 +1098,20 @@ fn color_table(ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>) { let Some(shot) = shot else { widgets::subheader(ui, tl!("Color Table")); widgets::dim_label(ui, tl!("Shown with the optimised preview.")); - return; + // A Custom table the preview can't use (a deletion that left only colors mapped to + // transparent) can still go back to the generated palette. + if s.is_some_and(|s| s.color_table.is_custom()) && widgets::flat_button_fit(ui, tl!("Restore Generated Table"), 88.0).clicked() { + restore_table(d); + } + return Ok(()); }; + let table = s.map(|s| s.color_table.clone()).unwrap_or_default(); widgets::subheader(ui, &crate::i18n::tn(shot.colors.len() as u64, "Color Table ({n} color)", "Color Table ({n} colors)")); + if table.is_custom() { + widgets::dim_label(ui, tl!("Custom")); + } let selected = d.str("__color"); + let picked = selection(d); // (colour shown, source, transparent, locked, web-safe, mapped by hand) let rows: Vec<(TableColor, bool)> = shot .colors @@ -1069,6 +1123,9 @@ fn color_table(ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>) { let per_row = ((SIDE_W - 8.0) / (CELL + 2.0)).floor().max(1.0) as usize; let lines = rows.len().div_ceil(per_row).max(1); let (area, resp) = ui.allocate_exact_size(egui::vec2(SIDE_W - 8.0, lines as f32 * (CELL + 2.0)), egui::Sense::click()); + // The colors that can be selected, in table order (for Shift-click ranges). + let order: Vec = rows.iter().filter(|(c, mapped)| !c.transparent || *mapped).map(|(c, _)| hex(c.source)).collect(); + let mut clicked = None; let p = ui.painter(); for (i, (c, mapped)) in rows.iter().enumerate() { let r = egui::Rect::from_min_size( @@ -1102,14 +1159,17 @@ fn color_table(ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>) { } // The transparent entry itself isn't a colour to edit. let pickable = !c.transparent || *mapped; - let picked = pickable && hex(c.source) == selected; - p.rect_stroke(r, 0.0, egui::Stroke::new(if picked { 2.0 } else { 1.0 }, if picked { t.accent } else { t.border }), egui::StrokeKind::Outside); + let ringed = pickable && picked.iter().any(|h| h.eq_ignore_ascii_case(&hex(c.source))); + p.rect_stroke(r, 0.0, egui::Stroke::new(if ringed { 2.0 } else { 1.0 }, if ringed { t.accent } else { t.border }), egui::StrokeKind::Outside); if pickable && resp.clicked() && resp.interact_pointer_pos().is_some_and(|pos| r.contains(pos)) { - d.fields.insert("__color".into(), json!(hex(c.source))); + clicked = Some(hex(c.source)); } } + if let Some(c) = clicked { + let m = ui.input(|i| i.modifiers); + pick(d, &order, &c, m.shift, m.command); + } ui.add_space(4.0); - let table = s.map(|s| s.color_table.clone()).unwrap_or_default(); let on = |list: &[String]| list.iter().any(|h| h.eq_ignore_ascii_case(&selected)); ui.horizontal(|ui| { ui.add_enabled_ui(!selected.is_empty(), |ui| { @@ -1130,6 +1190,23 @@ fn color_table(ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>) { } }); }); + // Delete Color (the button and the table's menu) and Restore Generated Table. + let (mut delete, mut restore) = (false, false); + ui.horizontal(|ui| { + delete |= widgets::icon_button_enabled(ui, "trash-2", tl!("Delete Color"), false, !picked.is_empty(), 24.0).clicked(); + let menu = widgets::icon_button(ui, "menu", tl!("Color Table"), false, 24.0); + let open = menu.clicked(); + let _ = widgets::popover(&menu, open, |ui| { + if widgets::menu_item(ui, tl!("Delete Color"), !picked.is_empty(), false) { + delete = true; + ui.close(); + } + if widgets::menu_item(ui, tl!("Restore Generated Table"), table.is_custom(), false) { + restore = true; + ui.close(); + } + }); + }); let sort = table.sort; widgets::label_row(ui, tl!("Order:"), LABEL_W, |ui| { let labels = ColorSort::ALL.map(ColorSort::label); @@ -1139,6 +1216,118 @@ fn color_table(ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>) { set_table(d, "sort", json!(o.id())); } }); + if restore { + restore_table(d); + } + if delete { + let palette: Vec = + shot.colors.iter().filter(|c| !c.transparent).map(|c| hex(c.source)).chain(shot.mapped.iter().map(|c| hex(*c))).collect(); + delete_colors(d, &palette)?; + } + Ok(()) +} + +/// The colour table's selected colors, by source: `__colors`, else `__color`. +pub(super) fn selection(d: &Dialog) -> Vec { + let many: Vec = + d.fields.get("__colors").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).map(str::to_ascii_lowercase).collect(); + if !many.is_empty() { + return many; + } + let one = d.str("__color"); + if one.is_empty() { vec![] } else { vec![one.to_ascii_lowercase()] } +} + +/// A click on the table's color `color`: it alone is selected and becomes the anchor (`__color`); +/// with `shift`, the colors from the anchor to it in table order (`order`), the anchor unchanged; +/// with `command` (Ctrl, or Command on macOS), it is added to the selection and becomes the anchor, +/// or taken out, and the anchor moves to the last color left in the selection. +pub(super) fn pick(d: &mut Dialog, order: &[String], color: &str, shift: bool, command: bool) { + let color = color.to_ascii_lowercase(); + let at = |c: &str| order.iter().position(|o| o.eq_ignore_ascii_case(c)); + if shift && let (Some(a), Some(b)) = (at(&d.str("__color")), at(&color)) { + let range: Vec = order[a.min(b)..=a.max(b)].iter().map(|c| c.to_ascii_lowercase()).collect(); + d.fields.insert("__colors".into(), json!(range)); + return; + } + let mut set = selection(d); + let anchor = if command { + match set.iter().position(|c| *c == color) { + Some(i) => { + set.remove(i); + set.last().cloned() + } + None => { + set.push(color.clone()); + Some(color) + } + } + } else { + set = vec![color.clone()]; + Some(color) + }; + d.fields.insert("__colors".into(), json!(set)); + match anchor { + Some(c) => d.fields.insert("__color".into(), json!(c)), + None => d.fields.remove("__color"), + }; +} + +/// Delete Color: the selected colors join the color table's `deleted` list and leave its other +/// lists. The first deletion fixes the palette (`customPalette`) to `palette`, the table's colors +/// (by source) with the deleted ones, so the colors left do not change. A deletion that leaves no +/// color, or only colors mapped to transparent, is refused with nothing changed. The selection is +/// cleared. +pub(super) fn delete_colors(d: &mut Dialog, palette: &[String]) -> Result<(), String> { + let picked = selection(d); + if picked.is_empty() { + return Ok(()); + } + let list = |d: &Dialog, key: &str| -> Vec { + d.fields + .get("colorTable") + .and_then(|t| t.get(key)) + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(Value::as_str) + .map(str::to_ascii_lowercase) + .collect() + }; + let mut custom = list(d, "customPalette"); + if custom.is_empty() { + custom = palette.iter().map(|c| c.to_ascii_lowercase()).collect(); + } + let mut deleted = list(d, "deleted"); + for c in &picked { + if !deleted.contains(c) { + deleted.push(c.clone()); + } + } + // A color has to stay that is neither deleted nor mapped to transparent. + let clear: Vec = list(d, "transparent").into_iter().filter(|c| !picked.contains(c)).collect(); + if custom.iter().all(|c| deleted.contains(c) || clear.contains(c)) { + return Err(webexport::KEEP_ONE.into()); + } + for key in ["locked", "transparent", "webShift"] { + if list(d, key).iter().any(|c| picked.contains(c)) { + for c in &picked { + toggle(d, key, c, false); + } + } + } + set_table(d, "customPalette", json!(custom)); + set_table(d, "deleted", json!(deleted)); + d.fields.remove("__colors"); + d.fields.remove("__color"); + Ok(()) +} + +/// Restore Generated Table: no deleted colors and no fixed palette; the reduction makes the +/// palette again. +pub(super) fn restore_table(d: &mut Dialog) { + set_table(d, "deleted", json!([])); + set_table(d, "customPalette", json!([])); } /// Add `color` to the colour table's `list`, or take it out. diff --git a/crates/ui-egui/src/dialogs/save_pdf.rs b/crates/ui-egui/src/dialogs/save_pdf.rs index af047a4cc2..edfb66e7f4 100644 --- a/crates/ui-egui/src/dialogs/save_pdf.rs +++ b/crates/ui-egui/src/dialogs/save_pdf.rs @@ -152,10 +152,31 @@ fn params(d: &Dialog) -> Value { p } -/// Save PDF: write the file (a PDF copy, or the PDF a Save As / Save a Copy asked for, `__save`); -/// the dialog stays open when that fails (bad range, cancelled save…). While Save Preset… asks for -/// a name, OK (and Enter) saves the preset instead. +/// The field that holds why the last Save PDF failed, shown in the dialog (the status bar sits +/// behind it, #6861). +const ERROR: &str = "__error"; + +/// Save PDF: write the file (see [`write`]). When that fails the dialog stays open and says why, +/// under its sections, as well as in the status bar the dialog covers. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let r = write(app, d); + if let Some(open) = app.ui.dialog.as_mut().filter(|o| o.kind == d.kind) { + match &r { + Err(e) => { + open.fields.insert(ERROR.into(), json!(e)); + } + Ok(_) => { + open.fields.remove(ERROR); + } + } + } + r +} + +/// Write the file (a PDF copy, or the PDF a Save As / Save a Copy asked for, `__save`); the +/// dialog stays open when that fails (bad range, cancelled save…). While Save Preset… asks for a +/// name, OK (and Enter) saves the preset instead. +fn write(app: &mut VectorcraftApp, d: &Dialog) -> Result { if d.fields.contains_key(SAVE_AS) { let mut d = d.clone(); let r = save_preset(app, &mut d); @@ -408,7 +429,8 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { ui.vertical(|ui| { ui.set_width(500.0); ui.label(egui::RichText::new(tl!(section)).font(theme::semibold(14.0)).color(t.text_strong)); - egui::ScrollArea::vertical().id_salt(("save-pdf", section)).max_height(360.0).auto_shrink([false, false]).show(ui, |ui| match section { + let list_h = super::modal::list_height(ui, 360.0); + egui::ScrollArea::vertical().id_salt(("save-pdf", section)).max_height(list_h).auto_shrink([false, false]).show(ui, |ui| match section { "Compression" => compression(ui, d), "Marks and Bleeds" => marks_and_bleeds(app, ui, d), "Output" => output(ui, d), @@ -417,6 +439,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { "Summary" => summary(app, ui, d), _ => general(ui, d, editor), }); + if let Some(e) = d.fields.get(ERROR).and_then(Value::as_str) { + ui.add_space(6.0); + ui.label(egui::RichText::new(crate::i18n::message(crate::i18n::current(), e)).color(t.error)); + } }); }); false @@ -452,7 +478,8 @@ pub(super) fn section_list(ui: &mut egui::Ui, d: &mut Dialog, sections: &[&str], /// What choosing `standard` changes: the compatibility, to its version unless it allows the one /// chosen, and off what files of a standard can't have (editing data, passwords; layers in PDF/X-1a -/// and PDF/X-3). +/// and PDF/X-3). In PDF/X-3 and PDF/X-4, Profile inclusion goes back to unset: the picker is +/// disabled there, and `none` would write every CMYK color as DeviceCMYK. fn standard_chosen(d: &mut Dialog, standard: Standard) { if choice::(d, "compatibility").is_some_and(|c| !standard.allows(c)) { set(d, "compatibility", json!(standard.version().id())); @@ -466,6 +493,9 @@ fn standard_chosen(d: &mut Dialog, standard: Standard) { if !standard.allows_layers() { set(d, "createLayers", json!(false)); } + if standard.is_pdfx() && !standard.cmyk_only() { + set(d, "output.profiles", json!(vectorcraft_pdf::UNSET_CHOICE)); + } } /// The Preset row (the presets, built-in and saved, and Save Preset…) and, while Save Preset… @@ -590,9 +620,10 @@ fn image_rows(ui: &mut egui::Ui, d: &mut Dialog, key: &str, title: &str) { ui.horizontal(|ui| { pick::(ui, d, &format!("{base}.downsample"), 150.0, |_| true); ui.label(tl!("to")); - number(ui, d, &format!("{base}.ppi"), " ppi", on); + let ppi = super::ppi_suffix(); + number(ui, d, &format!("{base}.ppi"), &ppi, on); ui.label(tl!("above")); - number(ui, d, &format!("{base}.abovePpi"), " ppi", on); + number(ui, d, &format!("{base}.abovePpi"), &ppi, on); }); ui.horizontal(|ui| { ui.label(tl!("Compression:")); @@ -711,6 +742,22 @@ fn output(ui: &mut egui::Ui, d: &mut Dialog) { }); if standard.cmyk_only() { note(ui, tl!("PDF/X-1a files are CMYK: every colour is converted to the destination (blank: the output intent's CMYK profile), untagged.")); + } else if standard.is_pdfx() { + note( + ui, + tl!( + "Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK." + ), + ); + // A preset or the dialog's params can bring `none` with the standard; the picker can't change it. + if choice::(d, "output.profiles") == Some(ProfileInclusion::None) { + note( + ui, + tl!( + "With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile." + ), + ); + } } else if standard != Standard::None { note(ui, tl!("Files of this standard tag their colours with ICC profiles.")); } @@ -911,7 +958,7 @@ pub(super) fn option_rows<'a>(ui: &mut egui::Ui, changed: impl IntoIterator s.clone(), other => other.to_string(), }; - ui.label(egui::RichText::new(format!("{}: {value}", label(c["option"].as_str().unwrap_or_default()))).color(t.text)); + ui.label(egui::RichText::new(format!("{} {value}", crate::i18n::colon(&label(c["option"].as_str().unwrap_or_default())))).color(t.text)); } } diff --git a/crates/ui-egui/src/dialogs/save_pdf/tests.rs b/crates/ui-egui/src/dialogs/save_pdf/tests.rs index 91442f111c..6e02006cac 100644 --- a/crates/ui-egui/src/dialogs/save_pdf/tests.rs +++ b/crates/ui-egui/src/dialogs/save_pdf/tests.rs @@ -92,6 +92,27 @@ fn confirm_runs_export_pdf_with_the_dialog_options() { assert!(app.ui.status.starts_with("Saved /tmp/out.pdf"), "{}", app.ui.status); } +/// A Save PDF that fails keeps the dialog open and says why inside it (#6861): the status bar is +/// behind the dialog. Saving again, once it works, clears the message. +#[test] +fn a_failed_save_says_why_in_the_dialog() { + let (mut app, written, _) = app(); + app.run("ui.savePdfDialog", json!({"path": "/tmp/out.pdf"})).unwrap(); + set_field(&mut app, "__allArtboards", json!(false)); + set_field(&mut app, "range", json!("9")); + let e = super::super::confirm(&mut app).unwrap_err(); + assert!(written.borrow().is_empty(), "nothing was written"); + let d = app.ui.dialog.as_ref().expect("the dialog stays open"); + assert_eq!(d.str(ERROR), e, "the dialog holds the reason"); + assert!(!e.is_empty()); + assert!(params(d).get(ERROR).is_none(), "the message is not an option of the export"); + frame(&mut app); + set_field(&mut app, "range", json!("1")); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(written.borrow().len(), 1); +} + /// Opened for a page of the art's bounds (Export As with Use Artboards off), the dialog has no /// Artboards section, and OK writes one page of the art's bounds with its options, a saved preset /// and View PDF after Saving included. @@ -537,6 +558,39 @@ fn choosing_a_pdfx_standard_sets_its_version_and_writes_the_standard() { assert_eq!((get(d, "compatibility"), get(d, "createLayers")), (&json!("1.6"), &json!(true))); } +/// Profile inclusion is disabled with a standard, so choosing PDF/X-3 or PDF/X-4 sets it back to +/// unset: a `none` chosen before would write every CMYK color as DeviceCMYK. +#[test] +fn choosing_pdfx3_or_pdfx4_unsets_profile_inclusion() { + let (mut app, _, _) = app(); + for standard in [Standard::PdfX3, Standard::PdfX4] { + app.run("ui.savePdfDialog", json!({"path": "/tmp/x.pdf", "output": {"profiles": "none"}})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + assert_eq!(get(d, "output.profiles"), &json!("none")); + set(d, "standard", json!(standard.id())); + standard_chosen(d, standard); + assert_eq!(get(d, "output.profiles"), &json!(vectorcraft_pdf::UNSET_CHOICE), "{}", standard.id()); + } +} + +/// Opened with PDF/X-3 or PDF/X-4 and `none` (params or a preset, without choosing the standard), +/// the dialog keeps `none` and its Output note says every CMYK color is written as DeviceCMYK. +#[test] +fn a_loaded_pdfx_standard_with_no_profiles_says_cmyk_is_device_cmyk() { + const NOTE: &str = "every CMYK color is written as DeviceCMYK"; + let (mut app, _, _) = app(); + for (standard, profiles, shown) in + [(Standard::PdfX4, "none", true), (Standard::PdfX3, "none", true), (Standard::PdfX4, "all", false), (Standard::PdfX1a, "none", false)] + { + let params = json!({"path": "/tmp/x.pdf", "standard": standard.id(), "output": {"profiles": profiles}}); + app.run("ui.savePdfDialog", params).unwrap(); + set_field(&mut app, "__section", json!("Output")); + assert_eq!(get(app.ui.dialog.as_ref().unwrap(), "output.profiles"), &json!(profiles)); + let text = crate::tests_labels::painted_text(&mut app, |app, ui| super::super::show(app, ui.ctx())); + assert_eq!(text.contains(NOTE), shown, "{} {profiles}: {text}", standard.id()); + } +} + /// "Write pages longer than 200 in at full size in points" is enabled only without a standard, at /// PDF 1.5 and later: PDF/X files and PDF 1.3 and 1.4 files write long pages in points anyway, and /// PDF/A files keep the `UserUnit`. diff --git a/crates/ui-egui/src/dialogs/script_check.rs b/crates/ui-egui/src/dialogs/script_check.rs index 257227cc6f..e134cf1b39 100644 --- a/crates/ui-egui/src/dialogs/script_check.rs +++ b/crates/ui-egui/src/dialogs/script_check.rs @@ -271,7 +271,7 @@ fn report(ui: &mut egui::Ui, r: &Value, t: &Tokens) { for p in problems { let Some(label) = p["code"].as_str().and_then(problem_label) else { continue }; let label = match p["detail"].as_str() { - Some(detail) => format!("{label}: {detail}"), + Some(detail) => format!("{} {detail}", crate::i18n::colon(label)), None => label.to_string(), }; row(ui, t, &label, false, &place(p)); diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index 8f5e3b1093..f8baa7b7de 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -13,10 +13,22 @@ //! `stop`. OK, Enter or `ui.dialog.confirm` without an `answer` gives the default button's answer. //! Escape or `ui.dialog.cancel` gives Cancel for a prompt, No for a confirm and Stop for an alert. //! Stop ends the run and puts back everything it did. +//! +//! A script's file dialog (kind `scriptFiles`: `File.openDialog`, `File.saveDialog`, +//! `Folder.selectDialog` and the objects' `openDlg`, `saveDlg` and `selectDlg`) has the fields +//! `kind` (open, save or folder), `prompt` and `canAlways`, and takes `answer`: `once`, `always` +//! (only with `canAlways`), `deny` or `stop`. Only the person at the keyboard answers `once` or +//! `always`: from `ui.dialog.set`, `ui.dialog.confirm` or synthetic input they are refused, and the +//! dialog stays open; `deny` and `stop` are taken from automation too. The paths it allows are the +//! ones Choose… picked in the host's file dialog, at most 2,048; `ui.dialog.set` cannot set them, +//! and the dialog's own fields change neither what it allows nor what it says it allows. Escape, +//! `ui.dialog.cancel`, Enter, and OK or `ui.dialog.confirm` without an `answer` give Deny. +//! `selectDlg` opens the host's folder picker in its own folder. use serde_json::{Value, json}; use vectorcraft_engine::cmd::scripts::{RUN_EXTS, TOO_LARGE, runs}; use vectorcraft_engine::script::dialogs::{MAX_PROMPT_BYTES, cut_to, shown_text}; +use vectorcraft_engine::script::files::{MAX_ENTRIES, PickAnswer, PickerKind, ScriptPicker}; use vectorcraft_engine::script::{DialogAnswer, ScriptDialog}; use super::{DialogAction, DialogSpec}; @@ -32,6 +44,19 @@ pub const GROWTH_KIND: &str = "scriptGrowth"; pub const CLOSE_KIND: &str = "scriptClose"; /// The dialog kind of a script's `alert`, `confirm` and `prompt`. pub const NOTICE_KIND: &str = "scriptDialog"; +/// The dialog kind of a script's file dialogs. +pub const PICKER_KIND: &str = "scriptFiles"; + +pub(super) const PICKER_SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("Script File Access").into(), + body_with_actions: Some(picker_body), + confirm: picker_confirm, + ok: None, + inputs: |_| &["answer"], + min_width: 420.0, + max_width: Some(560.0), + ..DialogSpec::FORM +}; pub(super) const NOTICE_SPEC: DialogSpec = DialogSpec { heading: notice_heading, @@ -171,7 +196,7 @@ fn close_confirm(app: &mut VectorcraftApp, _: &Dialog) -> Result /// Quitting while a script runs asks whether to stop it, also over the script's own dialog, which /// Cancel shows again as it was. Any other open dialog stays, and quitting asks nothing yet. pub(crate) fn ask_to_close(app: &mut VectorcraftApp) { - let notice = app.ui.dialog.take_if(|d| d.kind == NOTICE_KIND); + let notice = app.ui.dialog.take_if(|d| d.kind == NOTICE_KIND || d.kind == PICKER_KIND); if app.ui.dialog.is_some() { return; } @@ -192,6 +217,7 @@ pub(crate) fn settle_close(app: &mut VectorcraftApp) { if !app.session.script_running() { app.ui.dialog = None; } else if app.session.script_dialog().is_none() + && app.session.script_picker().is_none() && let Some(d) = app.ui.dialog.as_mut() { d.fields.remove(super::PARENT); @@ -327,6 +353,192 @@ fn give(app: &mut VectorcraftApp, d: &Dialog, answer: &str) -> Result = match p.kind { + PickerKind::Open if several => crate::picks::open_files(app, &pick), + PickerKind::Open => crate::picks::open(app, &pick).into_iter().collect(), + PickerKind::Save => crate::picks::save(app, &pick).into_iter().collect(), + // `selectDlg` starts in its folder; `Folder.selectDialog` gives none. + PickerKind::Folder => match p.start.clone() { + Some(start) => crate::picks::folder_at(app, &start).into_iter().collect(), + None => crate::picks::folder(app).into_iter().collect(), + }, + }; + if !chosen.is_empty() { + let mut paths = if several { std::mem::take(&mut app.script_picked) } else { Vec::new() }; + let mut seen: std::collections::HashSet = paths.iter().cloned().collect(); + for path in chosen { + if seen.contains(&path) { + continue; + } + if paths.len() >= MAX_ENTRIES { + app.script_picked_left_out = true; + break; + } + seen.insert(path.clone()); + paths.push(path); + } + app.script_picked = paths; + } + Ok(()) + }); + // Picking a path doesn't fail. + let _ = r; +} + +/// The dialog's prompt and the access it describes come from the request the run waits at, not +/// from the dialog's fields, so `ui.dialog.set` cannot change what the person reads. +fn picker_body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAction { + let t = Tokens::get(ui.ctx()); + let Some((kind, prompt)) = app.session.script_picker().map(|p| (p.kind, shown_text(&p.prompt, true))) else { return DialogAction::None }; + if !prompt.is_empty() { + egui::ScrollArea::vertical().max_height(160.0).show(ui, |ui| ui.label(&prompt)); + ui.add_space(8.0); + } + ui.label(picker_request(kind)); + ui.add_space(8.0); + let paths = app.script_picked.clone(); + ui.horizontal(|ui| { + if widgets::secondary_button(ui, tl!("Choose…")).clicked() { + choose(app, d); + } + ui.add_space(8.0); + if let [path] = paths.as_slice() { + ui.label(egui::RichText::new(shown_text(path, false)).color(t.text_strong)); + } + }); + if paths.len() > 1 { + ui.add_space(4.0); + egui::ScrollArea::vertical().id_salt("script-picked").max_height(120.0).show(ui, |ui| { + for path in &paths { + ui.label(egui::RichText::new(shown_text(path, false)).color(t.text_strong)); + } + }); + } + if app.script_picked_left_out { + ui.add_space(4.0); + ui.colored_label(t.error, crate::i18n::msg(PICKED_LEFT_OUT)); + } + ui.add_space(16.0); + let chosen = !app.script_picked.is_empty(); + let can_always = app.session.script_picker().is_some_and(|p| p.can_always); + let mut answer = None; + let row = egui::vec2(ui.min_rect().width(), ui.spacing().interact_size.y); + ui.allocate_ui_with_layout(row, egui::Layout::right_to_left(egui::Align::Center), |ui| { + if widgets::primary_button_enabled(ui, tl!("Allow Once"), chosen).clicked() { + answer = Some("once"); + } + ui.add_space(8.0); + if can_always { + if ui.add_enabled_ui(chosen, |ui| widgets::secondary_button(ui, tl!("Always Allow This Script"))).inner.clicked() { + answer = Some("always"); + } + ui.add_space(8.0); + } + if widgets::secondary_button(ui, tl!("Deny")).clicked() { + answer = Some("deny"); + } + // The row runs right to left: Stop goes at its left end. + ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { + if widgets::secondary_button(ui, tl!("Stop")).clicked() { + answer = Some("stop"); + } + }); + }); + // Enter gives the dialog's default answer, Deny, as `ui.dialog.confirm` without an answer does, + // unless it goes to the button that has the keyboard focus (Choose…). + let unfocused = ui.ctx().memory(|m| m.focused().is_none()); + if answer.is_none() && unfocused && crate::shortcuts::pressed_anew(ui.ctx(), egui::Key::Enter) { + answer = Some("deny"); + } + let Some(answer) = answer else { return DialogAction::None }; + d.fields.insert("answer".into(), json!(answer)); + DialogAction::Confirm +} + +/// What the file dialog of `kind` asks the person to allow. +fn picker_request(kind: PickerKind) -> &'static str { + match kind { + PickerKind::Open => tl!("The script asks to read a file you choose."), + PickerKind::Save => tl!("The script asks to read and write a file you choose."), + PickerKind::Folder => tl!("The script asks to read and write a folder you choose, with everything in it."), + } +} + +/// The note the file dialog shows when the person picked more files than a script is given. +const PICKED_LEFT_OUT: &str = "A script is given at most 2,048 files: the files picked after them were left out"; + +/// Gives the running script the file dialog's `answer`, or Deny. +fn picker_confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let answer = d.fields.get("answer").and_then(Value::as_str).unwrap_or("deny"); + give_pick(app, answer) +} + +/// Escape or Cancel: Deny. +pub(super) fn picker_cancel(app: &mut VectorcraftApp, _: &Dialog) { + let _ = give_pick(app, "deny"); +} + +/// Gives the running script `answer` with the paths Choose… picked. Only the person at the keyboard +/// allows access: Allow Once and Always Allow are refused, and the dialog stays open, while +/// automation sends the answer (a control or MCP request, or synthetic input) or opened the host's +/// file dialog; Deny and Stop are taken from anyone. +fn give_pick(app: &mut VectorcraftApp, answer: &str) -> Result { + let paths = app.script_picked.clone(); + let can_always = app.session.script_picker().is_some_and(|p| p.can_always); + let given = match answer { + "stop" => None, + "deny" => Some(PickAnswer::Deny), + "once" | "always" if app.automation_asked() => return Err("Only the person at the keyboard can allow a script's file access".into()), + "once" | "always" if paths.is_empty() => return Err("choose a file or folder first, or deny".into()), + "always" if !can_always => return Err("this script's file access can be allowed only once".into()), + "once" => Some(PickAnswer::Allow { paths, always: false }), + "always" => Some(PickAnswer::Allow { paths, always: true }), + _ => return Err("`answer` for a script's file dialog must be one of: once, always, deny, stop".into()), + }; + app.script_picked.clear(); + app.script_picked_left_out = false; + match given { + None => { + app.session.script_request_stop(); + } + Some(a) => { + app.session.script_pick(a); + } + } + if app.ui.dialog.as_ref().is_some_and(|open| open.kind == PICKER_KIND) { + app.ui.dialog = None; + } + Ok(Value::Null) +} + fn answers_for(kind: &str) -> &'static str { match kind { "confirm" => "yes, no, stop", diff --git a/crates/ui-egui/src/dialogs/shape_builder_options.rs b/crates/ui-egui/src/dialogs/shape_builder_options.rs index 9393e0707e..d4edbad1f9 100644 --- a/crates/ui-egui/src/dialogs/shape_builder_options.rs +++ b/crates/ui-egui/src/dialogs/shape_builder_options.rs @@ -14,7 +14,7 @@ use vectorcraft_color::Color; use vectorcraft_doc::LAYER_COLORS; use super::tile_edge_color::{checked, resolve}; -use super::{DialogSpec, form, run_and_close}; +use super::{DialogSpec, form, set_tool_options_and_close}; use crate::state::Dialog; use crate::{VectorcraftApp, widgets}; @@ -124,7 +124,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { checked(&d.str("highlightColor"))?; } let values: Map = KEYS.iter().filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone()))).collect(); - run_and_close(app, "tool.setOption", json!({ "tool": "shapeBuilder", "values": values })) + set_tool_options_and_close(app, json!({ "tool": "shapeBuilder", "values": values })) } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/shapes.rs b/crates/ui-egui/src/dialogs/shapes.rs index 3040097a25..c77b9a080e 100644 --- a/crates/ui-egui/src/dialogs/shapes.rs +++ b/crates/ui-egui/src/dialogs/shapes.rs @@ -102,8 +102,8 @@ fn line_length_angle(d: &Dialog) -> (f64, f64) { fn arc_options(d: &Dialog) -> Value { json!({ "closed": d.str("arcType").eq_ignore_ascii_case("closed"), - "lengthX": d.f64("lengthX", 100.0), - "lengthY": d.f64("lengthY", 100.0), + "lengthX": d.f64("lengthX", 100.0).abs(), + "lengthY": d.f64("lengthY", 100.0).abs(), "reference": arc_reference(d), "baseAlong": d.str("baseAlong"), "slope": d.f64("slope", 50.0), @@ -270,8 +270,8 @@ fn arc_form(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit) { const ARC_PREVIEW: egui::Vec2 = egui::vec2(160.0, 120.0); const ARC_PREVIEW_MARGIN: f32 = 12.0; -/// The arc the Arc tool draws with the options OK sets from `d` ([`arc_options`], kept as the tool -/// keeps them: a slope from -100 to 100, a Base Along of Y or else X), as `shape.arc` draws it +/// The arc the Arc tool draws with the options OK sets from `d` ([`arc_options`]; a slope past -100 +/// or 100, which OK refuses, is drawn at that end, and a Base Along other than Y along X), as `shape.arc` draws it /// with its reference point at the origin and General › Constrain Angle `constrain` (degrees) /// turning it about that point. `None` when a length or the slope is not finite. fn arc_preview_path(d: &Dialog, constrain: f64) -> Option { @@ -554,13 +554,11 @@ fn box_origin(d: &Dialog) -> (f64, f64) { fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { // Tool Options: the options the tool's next drag and click use; nothing is drawn. if d.bool(TOOL_OPTIONS) { - let r = app.run("tool.setOption", json!({"tool": d.kind, "values": tool_options(d)})); - app.ui.dialog = None; - return r; + return super::set_tool_options_and_close(app, json!({"tool": d.kind, "values": tool_options(d)})); } let count = match d.kind.as_str() { "polygon" => Some(("sides", 6.0, 3.0)), - "star" => Some(("points", 5.0, 2.0)), + "star" => Some(("points", 5.0, 3.0)), _ => None, }; let options = count @@ -590,7 +588,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { "cx": x, "cy": y, "radius": d.f64("radius", 50.0).max(0.01), - "decay": d.f64("decay", 80.0).clamp(5.0, 150.0), + "decay": d.f64("decay", 80.0).clamp(5.0, 99.99), "segments": (d.f64("segments", 10.0) as u64).clamp(2, 1000), "clockwise": d.bool("clockwise"), }), @@ -648,7 +646,13 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { // On the active plane while the perspective grid shows, sized in plane units from the click; // else along General › Constrain Angle, turned about the point the dialog places at the click // (a grid's reference point, the other shapes' top-left corner or centre). - let options = options.or_else(|| (d.kind == "spiral").then(|| params.clone())); + let options = options.or_else(|| { + (d.kind == "spiral").then(|| json!({"decay": params["decay"], "segments": params["segments"], "clockwise": params["clockwise"]})) + }); + // Options the tool would refuse leave the dialog open, before anything is drawn. + if let Some(Value::Object(o)) = &options { + vectorcraft_tools::option_check::check_values(vectorcraft_tools::create(&d.kind).as_ref(), o)?; + } let result = match vectorcraft_engine::perspective_click(&app.session, id, ¶ms, vectorcraft_geom::Point::new(x, y)) { Some((id, params)) => run_and_close(app, &id, params), None => { @@ -707,6 +711,15 @@ mod tests { assert!(app.ui.dialog.is_none()); assert_eq!(app.session.doc().unwrap().doc.layers[0].children().unwrap().len(), 1); assert_eq!(app.session.tool_options_of("spiral"), json!({"decay": 65.0, "segments": 12, "clockwise": true})); + + // A decay typed past 99.99 % draws the spiral at 99.99 %, the most a spiral draws, and + // keeps that decay. + super::super::open_tool_dialog(&mut app, "spiral", json!({"x": 40.0, "y": 60.0})); + app.ui.dialog.as_mut().unwrap().fields.insert("decay".into(), json!(120.0)); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.doc().unwrap().doc.layers[0].children().unwrap().len(), 2); + assert_eq!(app.session.tool_options_of("spiral")["decay"], json!(99.99)); } /// With General › Constrain Angle at 90°, the Spiral dialog's spiral starts straight up from the @@ -812,21 +825,27 @@ mod tests { } } - /// For values the Arc tool does not keep as typed, the picture shows the arc of the options OK - /// sets: the same picture as a dialog holding those options. + /// For values the dialog reads as other values, the picture shows the arc of the options OK + /// sets: the same picture as a dialog holding those options. A slope outside -100 to 100 or a + /// Base Along other than X or Y is refused: OK leaves the dialog open and keeps the options. #[test] fn the_arc_preview_shows_the_options_ok_sets() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); - for typed in [ - json!({"slope": 140.0}), - json!({"slope": -250.0}), - json!({"slope": "steep"}), - json!({"lengthX": "wide"}), - json!({"lengthY": null}), - json!({"baseAlong": "z"}), - json!({"reference": 12}), + for (typed, error) in [ + (json!({"slope": 140.0}), "`slope` must be a number from -100 to 100"), + (json!({"slope": -250.0}), "`slope` must be a number from -100 to 100"), + (json!({"baseAlong": "z"}), "`baseAlong` must be one of"), ] { + let before = app.session.tool_options_of("arc"); + app.ui.dialog = Some(arc_dialog(typed.clone())); + let r = super::super::confirm(&mut app); + assert!(r.as_ref().is_err_and(|e| e.contains(error)), "{typed}: {r:?}"); + assert!(app.ui.dialog.is_some(), "{typed}"); + assert_eq!(app.session.tool_options_of("arc"), before, "{typed}"); + app.ui.dialog = None; + } + for typed in [json!({"slope": "steep"}), json!({"lengthX": "wide"}), json!({"lengthY": null}), json!({"reference": 12})] { let d = arc_dialog(typed.clone()); let shown = arc_preview_path(&d, 0.0).expect("an arc"); app.ui.dialog = Some(d); @@ -1112,9 +1131,11 @@ mod tests { super::super::open_tool_dialog(&mut app, "ellipse", json!({"x": 10.0, "y": 150.0})); assert_eq!(app.ui.dialog.as_ref().unwrap().f64("anchors", 0.0), 6.0); app.ui.dialog = None; - // `tool.setOption` keeps it from 2 to 1000, and the dialog opens on what it keeps. - for (set, want) in [(json!(1), 2.0), (json!(2000), 1000.0), (json!(7), 7.0)] { - app.run("tool.setOption", json!({"tool": "ellipse", "values": {"anchors": set}})).unwrap(); + // `tool.setOption` takes it from 2 to 1000 and refuses other counts, and the dialog opens on + // what it keeps. + for (set, want) in [(json!(1), 6.0), (json!(2000), 6.0), (json!(2), 2.0), (json!(1000), 1000.0), (json!(7), 7.0)] { + let r = app.run("tool.setOption", json!({"tool": "ellipse", "values": {"anchors": set}})); + assert_eq!(r.is_ok(), set.as_u64().is_some_and(|n| (2..=1000).contains(&n)), "{set}: {r:?}"); super::super::open_tool_dialog(&mut app, "ellipse", json!({"x": 10.0, "y": 150.0})); assert_eq!(app.ui.dialog.as_ref().unwrap().f64("anchors", 0.0), want, "{set}"); app.ui.dialog = None; diff --git a/crates/ui-egui/src/dialogs/shortcut_import.rs b/crates/ui-egui/src/dialogs/shortcut_import.rs index 0516695233..e6c9a6ee0a 100644 --- a/crates/ui-egui/src/dialogs/shortcut_import.rs +++ b/crates/ui-egui/src/dialogs/shortcut_import.rs @@ -670,6 +670,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let (keys_h, rows_h) = list_heights(ctx.content_rect().height() - rest, keys_open); let (mut apply, mut cancel, mut copy, mut lists) = (false, false, false, 0.0); crate::dialogs::modal::show(ctx, tl!("Import Shortcut Set"), id, -20.0, 20, |ui| { + crate::dialogs::modal::fits_itself(ui); ui.set_width(NAME_W + TARGET_W + CHORD_W + 220.0); crate::dialogs::modal::heading(ui, tl!("Import Shortcut Set")); ui.add_space(10.0); diff --git a/crates/ui-egui/src/dialogs/simplify_slider.rs b/crates/ui-egui/src/dialogs/simplify_slider.rs index 88838585ee..4257c15177 100644 --- a/crates/ui-egui/src/dialogs/simplify_slider.rs +++ b/crates/ui-egui/src/dialogs/simplify_slider.rs @@ -87,7 +87,7 @@ impl Strip { /// The open strip `d` moves to the level `cmd {auto: true}` picks for the selection, and the /// canvas previews it → {level}. pub fn auto(&self, app: &mut VectorcraftApp, mut d: Dialog) -> Result { - let _ = app.session.begin_interaction(self.label); + app.begin_interaction(self.label)?; let r = app.session.preview(self.cmd, &json!({ "auto": true })).map_err(|e| e.to_string())?; let level = r["level"].as_f64().unwrap_or(self.default_level); d.fields.insert("level".into(), json!(level)); diff --git a/crates/ui-egui/src/dialogs/smart_punctuation.rs b/crates/ui-egui/src/dialogs/smart_punctuation.rs index 1ebe084e02..ce6f62c6a2 100644 --- a/crates/ui-egui/src/dialogs/smart_punctuation.rs +++ b/crates/ui-egui/src/dialogs/smart_punctuation.rs @@ -98,7 +98,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { let lines: Vec = options() .into_iter() .filter(|(key, ..)| d.bool(key)) - .map(|(_, count, label)| format!("{label}: {}", r["replaced"][count].as_u64().unwrap_or(0))) + .map(|(_, count, label)| format!("{} {}", crate::i18n::colon(label), r["replaced"][count].as_u64().unwrap_or(0))) .collect(); super::confirm::tell(app, tl!("Smart Punctuation"), &lines.join("\n")); } diff --git a/crates/ui-egui/src/dialogs/swatch_options.rs b/crates/ui-egui/src/dialogs/swatch_options.rs index 9583b893ef..044453d0a8 100644 --- a/crates/ui-egui/src/dialogs/swatch_options.rs +++ b/crates/ui-egui/src/dialogs/swatch_options.rs @@ -1,7 +1,10 @@ //! Swatch Options: name, colour type (process or spot), Global, colour mode with sliders and hex, -//! previewed live on the canvas (Cancel rolls the preview back). Double-clicking a swatch opens it -//! for a solid colour; for a gradient it shows the name and the gradient; patterns open pattern -//! editing ([`open`]). +//! and the out-of-gamut and out-of-web-color warnings under the colour, previewed live on the canvas +//! (Cancel rolls the preview back). A click on a warning's icon or colour corrects the colour +//! (https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf, +//! Swatch options; https://helpx.adobe.com/illustrator/using/adjusting-colors.html). +//! Double-clicking a swatch opens it for a solid colour; for a gradient it shows the name and the +//! gradient; patterns open pattern editing ([`open`]). //! //! Fields: `__swatch` (the swatch being edited), `name`, `spot`, `global`, `mode` (`gray`, `rgb`, //! `hsb`, `lab`, `cmyk` or `web`), `color` (`"#rrggbb"` or a colour object such as @@ -14,7 +17,9 @@ use vectorcraft_color::{Color, Paint}; use super::{DialogSpec, form, run_and_close}; use crate::VectorcraftApp; -use crate::panels::color::{Mode, components, from_components, parse_hex, track_color, web_safe}; +use crate::panels::color::{ + GAMUT_WARNING, Mode, WEB_WARNING, components, from_components, gamut_fix, is_web_safe, parse_hex, track_color, warning_chip, web_safe, +}; use crate::state::Dialog; use crate::theme::Tokens; use crate::widgets; @@ -113,7 +118,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { widgets::gradient_chip(ui, r, &g); changed } - None => editor(ui, d), + None => editor(app, ui, d), }; ui.add_space(8.0); let mut pv = d.bool("preview"); @@ -123,8 +128,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { d.fields.insert("preview".into(), json!(pv)); } if pv && (changed || pv_changed || !app.session.in_interaction()) { - let _ = app.session.begin_interaction("Swatch Options"); - if let Err(e) = app.session.preview("swatch.edit", &edit_params(d)) { + // A failure to begin (typing that can't be kept) shows, and nothing previews. + if let Err(e) = app.begin_interaction("Swatch Options") { + app.status(e); + } else if let Err(e) = app.session.preview("swatch.edit", &edit_params(d)) { app.status(e.to_string()); } } else if !pv && pv_changed { @@ -157,9 +164,9 @@ pub(super) fn name_row(ui: &mut egui::Ui, d: &mut Dialog) -> bool { changed } -/// The shared fields of Swatch Options and New Swatch: name, colour type, Global, mode, sliders and -/// hex. Returns true when anything changed. -pub(super) fn editor(ui: &mut egui::Ui, d: &mut Dialog) -> bool { +/// The shared fields of Swatch Options and New Swatch: name, colour type, Global, mode, sliders, +/// hex and the colour warnings. Returns true when anything changed. +pub(super) fn editor(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { let mut changed = false; grid(ui, |ui| { changed |= name_row(ui, d); @@ -191,15 +198,46 @@ pub(super) fn editor(ui: &mut egui::Ui, d: &mut Dialog) -> bool { ui.end_row(); }); ui.add_space(6.0); - changed | sliders(ui, d) + changed | sliders(app, ui, d) } -/// One slider and value field per component of the dialog's mode, the hex field (RGB, HSB and Web) -/// and a chip of the colour. Returns true when the colour changed. -fn sliders(ui: &mut egui::Ui, d: &mut Dialog) -> bool { +/// A warning under the colour of the swatch dialogs. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Warning { + Gamut, + Web, +} + +/// The warnings the swatch dialogs show in `mode`: out of gamut in RGB, HSB and Lab, and out of web +/// colors in every mode but Web Safe RGB. +fn shown_warnings(mode: Mode) -> (bool, bool) { + (matches!(mode, Mode::Rgb | Mode::Hsb | Mode::Lab), mode != Mode::WebSafe) +} + +/// The colour and mode a click on `warning` gives `c`, edited in `mode`: the nearest web-safe colour +/// (in RGB unless the mode is RGB or HSB), or the colour's CMYK equivalent in the active CMYK space +/// (in CMYK). `None` when the conversion returns no CMYK values. +fn corrected(app: &mut VectorcraftApp, warning: Warning, mode: Mode, c: &Color) -> Result, String> { + match warning { + Warning::Web => Ok(Some((web_safe(c), if matches!(mode, Mode::Rgb | Mode::Hsb) { mode } else { Mode::Rgb }))), + Warning::Gamut => { + let r = app.run("color.convert", json!({"color": crate::panels::color_json(c), "to": "cmyk"}))?; + let v = |i: usize| r["values"][i].as_f64().map(|v| v as f32); + Ok(v(0).zip(v(1)).zip(v(2)).zip(v(3)).map(|(((c, m), y), k)| (Color::cmyk(c, m, y, k), Mode::Cmyk))) + } + } +} + +/// One slider and value field per component of the dialog's mode, the hex field (RGB, HSB and Web), +/// a chip of the colour and under it the mode's warnings. Returns true when the colour changed. +fn sliders(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { let t = Tokens::get(ui.ctx()); let mode = mode_of(d); let color = color_of(d); + let (shows_gamut, shows_web) = shown_warnings(mode); + let gamut = if shows_gamut { gamut_fix(app, ui.ctx(), "swatch-gamut", &color) } else { None }; + let web = (shows_web && !is_web_safe(&color)).then(|| web_safe(&color)); + let mut clicked: Option = None; // Keep the displayed components while the colour is unchanged (hue survives S = 0 etc.). let key = format!("{}|{}", mode_id(mode), serde_json::to_string(&color).unwrap_or_default()); let comps: Vec = match d.fields.get("__comps") { @@ -239,13 +277,47 @@ fn sliders(ui: &mut egui::Ui, d: &mut Dialog) -> bool { }); } }); - let (r, _) = ui.allocate_exact_size(vec2(44.0, 44.0), egui::Sense::hover()); - widgets::swatch_tile(ui, r, &Paint::solid(color), false, false); + ui.vertical(|ui| { + let (r, _) = ui.allocate_exact_size(vec2(44.0, 44.0), egui::Sense::hover()); + widgets::swatch_tile(ui, r, &Paint::solid(color), false, false); + let warnings: Vec<_> = [(Warning::Gamut, GAMUT_WARNING, gamut), (Warning::Web, WEB_WARNING, web)] + .into_iter() + .filter_map(|(w, chip, fix)| Some((w, chip, fix?))) + .collect(); + for (w, chip, fix) in &warnings { + ui.add_space(4.0); + if warning_chip(ui, *chip, fix) { + clicked = Some(*w); + } + } + // Room for the mode's other warnings, so the dialog keeps its height as the colour changes. + for _ in warnings.len()..usize::from(shows_gamut) + usize::from(shows_web) { + ui.add_space(4.0); + ui.scope(|ui| { + ui.set_invisible(); + warning_chip(ui, WEB_WARNING, &Color::WHITE) + }); + } + }); }); + let mut mode = mode; + if let Some(w) = clicked { + match corrected(app, w, mode, &color) { + Ok(Some((c, m))) => { + mode = m; + d.fields.insert("mode".into(), json!(mode_id(m))); + new = Some((c, components(m, &c))); + } + Ok(None) => {} + Err(e) => app.status(e), + } + } let Some((c, comps)) = new else { return false }; set_color(d, c); d.fields.insert("__compsKey".into(), json!(format!("{}|{}", mode_id(mode), serde_json::to_string(&c).unwrap_or_default()))); d.fields.insert("__comps".into(), json!(comps)); + // The warnings above were drawn for the colour before the change. + ui.ctx().request_repaint(); true } @@ -277,9 +349,122 @@ fn hex_field(ui: &mut egui::Ui, hex: &str) -> Option { } #[cfg(test)] -mod tests { +pub(super) mod tests { use super::*; + /// A test context with the application's fonts and default theme. + pub(crate) fn context() -> egui::Context { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, Default::default()); + ctx + } + + /// Runs one frame of the open dialog with `events` and returns the rectangles it paints. + pub(crate) fn draw(ctx: &egui::Context, app: &mut VectorcraftApp, events: Vec) -> Vec { + fn collect(s: &egui::Shape, out: &mut Vec) { + match s { + egui::Shape::Rect(r) => out.push(r.rect), + egui::Shape::Vec(v) => v.iter().for_each(|s| collect(s, out)), + _ => {} + } + } + let input = + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(1280.0, 900.0))), events, ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| super::super::show(app, ui.ctx())); + out.textures_delta.clear(); + let mut boxes = vec![]; + out.shapes.iter().for_each(|c| collect(&c.shape, &mut boxes)); + boxes + } + + /// Lets the auto-sized dialog settle and returns the rectangles of the next frame. + pub(crate) fn settled(ctx: &egui::Context, app: &mut VectorcraftApp) -> Vec { + for _ in 0..6 { + draw(ctx, app, vec![]); + } + draw(ctx, app, vec![]) + } + + /// A primary-button press and release at `at`, in two frames. + pub(crate) fn click_at(ctx: &egui::Context, app: &mut VectorcraftApp, at: egui::Pos2) { + for pressed in [true, false] { + let button = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + draw(ctx, app, vec![egui::Event::PointerMoved(at), button]); + } + } + + /// The warning rows under the dialog's 44-point colour chip, top first: the centre of each + /// row's icon and the rectangle of its corrected colour. + pub(crate) fn warning_rows(boxes: &[egui::Rect]) -> Vec<(egui::Pos2, egui::Rect)> { + let near = |a: f32, b: f32| (a - b).abs() < 0.5; + let chip = boxes.iter().find(|r| near(r.width(), 44.0) && near(r.height(), 44.0)).copied().unwrap(); + let mut rows: Vec = boxes + .iter() + .filter(|r| near(r.width(), 16.0) && near(r.height(), 16.0)) + .filter(|r| r.top() >= chip.bottom() && r.left() >= chip.left() - 1.0 && r.right() <= chip.right() + 1.0) + .copied() + .collect(); + rows.sort_by(|a, b| a.top().total_cmp(&b.top())); + rows.dedup_by(|a, b| near(a.top(), b.top())); // The tile's fill and border share one rectangle. + rows.into_iter().map(|r| (r.center() - vec2(19.0, 0.0), r)).collect() + } + + fn dialog(app: &VectorcraftApp) -> &Dialog { + app.ui.dialog.as_ref().unwrap() + } + + #[test] + fn swatch_options_shows_and_corrects_both_warnings() { + let (ctx, mut app) = (context(), VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default())); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("swatch.new", json!({"name": "Sky", "color": "#0000fe", "spot": true})).unwrap(); + app.run("ui.swatchOptions", json!({"name": "Sky"})).unwrap(); + let rows = warning_rows(&settled(&ctx, &mut app)); + assert_eq!(rows.len(), 2, "out of gamut and out of web colors"); + // The cube's icon shifts to the nearest web-safe colour, in the same mode. + click_at(&ctx, &mut app, rows[1].0); + assert_eq!((color_of(dialog(&app)).to_hex(), dialog(&app).str("mode")), ("#0000ff".to_string(), "rgb".to_string())); + let rows = warning_rows(&settled(&ctx, &mut app)); + assert_eq!(rows.len(), 1, "web-safe blue is still out of gamut"); + // The triangle's colour shifts to the CMYK equivalent, edited in CMYK. + let ink = corrected(&mut app, Warning::Gamut, Mode::Rgb, &Color::rgb8(0, 0, 255)).unwrap().unwrap().0; + click_at(&ctx, &mut app, rows[0].1.center()); + assert_eq!((color_of(dialog(&app)), dialog(&app).str("mode")), (ink, "cmyk".to_string())); + assert!(app.ui.dialog.is_some(), "a correction only edits the fields"); + super::super::confirm(&mut app).unwrap(); + let sw = app.session.active().unwrap().doc.swatch("Sky").cloned().unwrap(); + assert_eq!((sw.paint.color(), sw.spot, sw.global), (Some(ink), true, true), "still a spot colour"); + app.run("edit.undo", json!({})).unwrap(); + let sw = app.session.active().unwrap().doc.swatch("Sky").cloned().unwrap(); + assert_eq!(sw.paint.color().map(|c| c.to_hex()), Some("#0000fe".into()), "one undo step"); + } + + #[test] + fn swatch_warnings_follow_the_mode() { + let (ctx, mut app) = (context(), VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default())); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("swatch.new", json!({"name": "Mid", "color": "#808080"})).unwrap(); + app.run("ui.swatchOptions", json!({"name": "Mid"})).unwrap(); + let mut rows_in = |mode: &str, c: Color| { + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("mode".into(), json!(mode)); + set_color(d, c); + warning_rows(&settled(&ctx, &mut app)).len() + }; + assert_eq!(rows_in("gray", Color::gray(0.5)), 1, "a gray off the web palette, never out of gamut"); + let cyan = Color::cmyk(1.0, 0.0, 0.0, 0.0); + assert_eq!(rows_in("cmyk", cyan), usize::from(!is_web_safe(&cyan)), "CMYK is never out of gamut"); + assert_eq!(rows_in("web", Color::rgb8(0, 0, 255)), 0, "Web Safe RGB shows no warning"); + assert_eq!(rows_in("rgb", Color::rgb8(0, 0, 255)), 1, "RGB blue is out of gamut"); + assert_eq!(rows_in("lab", Color::lab(30.0, 60.0, -100.0)), 2, "Lab shows both"); + // A web correction of a Lab colour is edited in RGB. + let rows = warning_rows(&settled(&ctx, &mut app)); + click_at(&ctx, &mut app, rows[1].0); + assert_eq!(dialog(&app).str("mode"), "rgb"); + assert!(is_web_safe(&color_of(dialog(&app)))); + } + #[test] fn fields_round_trip_modes_and_colours() { for (m, id) in MODES { diff --git a/crates/ui-egui/src/dialogs/symbol_options.rs b/crates/ui-egui/src/dialogs/symbol_options.rs index 146e02c6eb..9d73ad769d 100644 --- a/crates/ui-egui/src/dialogs/symbol_options.rs +++ b/crates/ui-egui/src/dialogs/symbol_options.rs @@ -8,7 +8,8 @@ //! `exportType` (`movieClip` | `graphic`), `type` (`dynamic` | //! `static`; a new symbol is dynamic), `registration` (0..8, the 9-point grid; //! 4 = centre), `alignToPixelGrid` (bool, off for a new symbol), `__edit` (true when editing an -//! existing symbol). Help: +//! existing symbol), `__keepArt` (true when a new symbol leaves the selection as ordinary art). +//! Help: //! . use serde_json::{Map, Value, json}; @@ -69,15 +70,23 @@ const EXPORT_TYPES: [(&str, &str); 2] = [("movieClip", "Movie Clip"), ("graphic" pub(super) const SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Symbol Options").into(), body, confirm, min_width: 320.0, ..DialogSpec::FORM }; -/// Open Symbol Options to name a new symbol made from the selection. -pub fn open(app: &mut VectorcraftApp) -> Result { +/// Open Symbol Options to name a new symbol made from the selection. With `keep_art`, OK leaves +/// the selection as ordinary art instead of replacing it with an instance. +pub fn open(app: &mut VectorcraftApp, keep_art: bool) -> Result { let st = app.session.active().ok_or("no document open")?; if st.selection.is_empty() { return Err("nothing selected".into()); } let name = st.doc.unique_symbol_name("New Symbol"); - let mut fields = - json!({ "name": name, "exportType": "movieClip", "type": "dynamic", "registration": 4, "alignToPixelGrid": false, "__edit": false }); + let mut fields = json!({ + "name": name, + "exportType": "movieClip", + "type": "dynamic", + "registration": 4, + "alignToPixelGrid": false, + "__edit": false, + "__keepArt": keep_art, + }); if let Some(o) = fields.as_object_mut() { o.extend(slice_fields(None)); } @@ -193,6 +202,9 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { } else { let mut params = json!({ "name": name, "exportType": export, "type": kind, "registration": registration, "alignToPixelGrid": pixel }); merge(&mut params, slice_params(d)); + if d.bool("__keepArt") { + params["keepArt"] = json!(true); + } app.run("symbol.new", params) }; if r.is_ok() { diff --git a/crates/ui-egui/src/dialogs/symbolism_options.rs b/crates/ui-egui/src/dialogs/symbolism_options.rs index 33d902b90e..05392bbd4f 100644 --- a/crates/ui-egui/src/dialogs/symbolism_options.rs +++ b/crates/ui-egui/src/dialogs/symbolism_options.rs @@ -6,7 +6,7 @@ use serde_json::{Map, Value, json}; -use super::{DialogResult, DialogSpec, form, run_and_close}; +use super::{DialogResult, DialogSpec, form, set_tool_options_and_close}; use crate::state::Dialog; use crate::{VectorcraftApp, widgets}; @@ -50,7 +50,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { /// OK: set the brush the Symbolism tools share (the tool keeps it within its ranges). fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { let values: Map = KEYS.iter().filter(|k| d.fields.contains_key(**k)).map(|k| (k.to_string(), json!(d.f64(k, 0.0)))).collect(); - run_and_close(app, "tool.setOption", json!({ "tool": d.str("tool"), "values": values })) + set_tool_options_and_close(app, json!({ "tool": d.str("tool"), "values": values })) } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 08968d5e93..0a9e32a385 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -178,6 +178,64 @@ fn effect_preview_is_kept_as_one_undo_step() { assert_eq!(app.session.doc().unwrap().doc, before); } +/// A field label's colon is written as the UI language writes it, in the generic parameter +/// dialogs and the effect dialogs alike (#7991): French puts a no-break space before it, Chinese +/// writes a full-width colon, and English is unchanged. +#[test] +fn field_label_colons_follow_the_ui_language() { + let mut app = app(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + let text = + app.run("text.create", json!({"x": 20, "y": 80, "text": "Hello", "area": {"width": 100, "height": 100}})).unwrap()["id"].as_u64().unwrap(); + // Each dialog, opened the way its menu item opens it, and the label it shows. + let entries = crate::menus::menu_entries(&app); + let clean_up = entries.iter().find(|e| e.path == ["Object", "Path"] && e.label == "Clean Up…").expect("listed"); + let clean_up = crate::menus::click_target(&clean_up.label, clean_up.command.as_deref().unwrap(), &clean_up.params); + let dialogs = [ + (clean_up.0, clean_up.1, "Stray Points"), + ("effect.dialog".to_string(), json!({"effect": "blur.radial"}), "Horizontal"), + ("text.areaOptions".to_string(), json!({}), "Text Flow"), + ]; + for (command, params, label) in dialogs { + app.run("select.set", json!({"ids": [text]})).unwrap(); + if command != "text.areaOptions" { + app.run("select.all", json!({})).unwrap(); + } + crate::menus::invoke(&mut app, &command, params); + assert!(app.ui.dialog.is_some(), "{command} opened no dialog"); + for (code, colon) in [("fr", "\u{a0}:"), ("zh-hans", ":"), ("en", ":")] { + let lang = crate::i18n::Lang::from_code(code).unwrap(); + crate::i18n::set_current(lang); + let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + crate::i18n::set_current(crate::i18n::Lang::EN); + let want = format!("{}{colon}", crate::i18n::tr(lang, label)); + assert!(shown.lines().any(|l| l.trim() == want), "{command}, {code}: {want:?} in {shown}"); + if code == "fr" { + let bare: Vec<_> = shown.lines().map(str::trim).filter(|l| l.ends_with(':') && !l.ends_with("\u{a0}:")).collect(); + assert!(bare.is_empty(), "{command}: French labels with a bare colon: {bare:?}"); + } + } + app.ui.dialog = None; + } + assert_eq!(super::form::humanized("strayPoints"), "Stray Points:", "English is unchanged"); +} + +/// A label followed by its value takes the UI language's colon too (#7991): Blur Center's value for +/// screen readers, and a style's attribute list, which no longer shows a second colon. +#[test] +fn label_and_value_colons_follow_the_ui_language() { + let fr = crate::i18n::Lang::from_code("fr").unwrap(); + crate::i18n::set_current(fr); + let center = super::effect::blur_center_value([0.5, 0.25]); + let attribute = super::form::attribute_line("fontSize", &json!(12)); + crate::i18n::set_current(crate::i18n::Lang::EN); + let (h, v) = (crate::i18n::tr(fr, "Horizontal"), crate::i18n::tr(fr, "Vertical")); + assert_eq!(center, format!("{h}\u{a0}: 50%, {v}\u{a0}: 25%")); + assert_eq!(attribute, format!("{}\u{a0}: 12", crate::i18n::tr(fr, "Font Size"))); + assert_eq!(super::effect::blur_center_value([0.5, 0.25]), "Horizontal: 50%, Vertical: 25%"); + assert_eq!(super::form::attribute_line("fontSize", &json!(12)), "Font Size: 12"); +} + /// Drop Shadow's Color typed as text the effect can't draw: OK returns the error and keeps the /// dialog open, with Preview on or off, and the document stays as it was. #[test] @@ -2832,6 +2890,61 @@ fn the_blob_brush_tip_preview_is_a_named_slider_with_arrow_keys() { assert_eq!(angle(&app), -44.0, "the drag gives the preview the focus"); } +/// A drag that starts on a black dot of the Blob Brush tip preview sets the Roundness from the +/// pointer's distance from the center along the tip's short axis, leaves the Angle as it is, goes +/// on past the square's edge (stopping at 100%), and gives the Roundness slider the focus, whose +/// keys step the Roundness by 1% (10% with Shift) within 0% to 100%. A drag that starts anywhere +/// else sets only the Angle, and Tab goes from the Angle slider to the Roundness slider. +#[test] +fn a_drag_on_a_blob_brush_tip_dot_sets_the_roundness() { + use egui::Key::{ArrowDown, ArrowRight, ArrowUp, End, Home, Tab}; + use egui::Modifiers as M; + let mut app = app(); + app.run("tool.options", json!({"tool": "blobBrush"})).unwrap(); + let values = |app: &VectorcraftApp| { + let d = app.ui.dialog.as_ref().expect("Blob Brush Tool Options is open"); + (d.f64("angle", f64::NAN), d.f64("roundness", f64::NAN)) + }; + let mut f = Frames::new(); + f.run(&mut app, vec![]); + let out = f.run(&mut app, vec![]); + let (_, value, text) = slider_node(&out, "Roundness"); + assert_eq!((value, text.as_deref()), (Some(100.0), Some("100%"))); + let center = f.control(&mut app, "Roundness", egui::accesskit::Role::Slider); + // At 0° the dots are straight above and below the center, 18 pt from it at 100%. A click + // pressed 6 pt from the upper dot and released 11 pt from it in the same frame takes the dot. + let (down, up) = (center + egui::vec2(0.0, -12.0), center + egui::vec2(0.0, -7.0)); + let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: M::NONE }; + f.run(&mut app, vec![egui::Event::PointerMoved(down), button(down, true), egui::Event::PointerMoved(up), button(up, false)]); + assert_eq!(values(&app), (0.0, 39.0), "a click that starts on the upper dot"); + f.drag(&mut app, center + egui::vec2(0.0, -7.0), egui::vec2(1.0, -11.0)); + assert_eq!(values(&app), (0.0, 100.0), "the upper dot dragged out to the tip's length"); + f.drag(&mut app, center + egui::vec2(0.0, -18.0), egui::vec2(1.0, 9.0)); + assert_eq!(values(&app), (0.0, 50.0), "the upper dot dragged half way to the center"); + f.drag(&mut app, center + egui::vec2(0.0, 9.0), egui::vec2(3.0, 60.0)); + assert_eq!(values(&app), (0.0, 100.0), "the lower dot dragged out of the square"); + f.drag(&mut app, center + egui::vec2(0.0, 18.0), egui::vec2(0.0, -18.0)); + assert_eq!(values(&app), (0.0, 0.0), "the lower dot dragged to the center"); + let mut seen = vec![]; + for (key, mods, want) in + [(ArrowUp, M::NONE, 1.0), (ArrowRight, M::SHIFT, 11.0), (ArrowDown, M::NONE, 10.0), (End, M::NONE, 100.0), (Home, M::NONE, 0.0)] + { + f.key(&mut app, key, mods); + seen.push((key, mods.shift, values(&app))); + assert_eq!(values(&app), (0.0, want), "{seen:?}"); + } + let out = f.run(&mut app, vec![]); + assert_eq!(slider_node(&out, "Roundness").2.as_deref(), Some("0%")); + // With a 0% tip the dots are at the center; a drag that starts away from them sets the Angle. + f.drag(&mut app, center + egui::vec2(20.0, 0.0), egui::vec2(0.0, -20.0)); + assert_eq!(values(&app), (45.0, 0.0), "the drag ends up to the right"); + f.key(&mut app, ArrowRight, M::NONE); + assert_eq!(values(&app), (46.0, 0.0), "the drag gives the Angle slider the focus"); + f.key(&mut app, Tab, M::NONE); + f.key(&mut app, ArrowUp, M::NONE); + assert_eq!(values(&app), (46.0, 1.0), "Tab goes on to the Roundness slider"); +} + /// Screen readers can set the Blob Brush tip preview's Angle to a number: the slider offers the /// set-value action, a fraction rounds to the whole degrees the field shows, a number past -180° to /// 180° sets the nearer end, the last request in a frame wins, and a value that is not a finite @@ -3654,3 +3767,94 @@ fn color_halftones_max_radius_stays_in_pixels_whatever_the_units() { assert!(shows, "{typed} shows as {shown}, not in centimetres"); } } + +/// The resolution fields of Flatten Transparency, Document Raster Effects Settings, Effect › +/// Rasterize, the PNG options and the PDF save dialog's Compression section show their unit in the interface +/// language (French "ppp"), as the `{n} ppi` row writes it. +#[test] +fn resolution_fields_show_the_ppi_unit_in_the_interface_language() { + fn texts(s: &egui::Shape, out: &mut Vec) { + match s { + egui::Shape::Text(t) => out.push(t.galley.text().to_string()), + egui::Shape::Vec(v) => v.iter().for_each(|s| texts(s, out)), + _ => {} + } + } + fn shown(app: &mut VectorcraftApp) -> Vec { + let ctx = egui::Context::default(); + theme::install_fonts(&ctx); + theme::apply(&ctx, Default::default()); + let raw = + || egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 1000.0))), ..Default::default() }; + // A window is measured in its first frame and drawn from the second. + ctx.run_ui(raw(), |ui| show(app, ui.ctx())).textures_delta.clear(); + let mut out = ctx.run_ui(raw(), |ui| show(app, ui.ctx())); + out.textures_delta.clear(); + let mut all = vec![]; + out.shapes.iter().for_each(|s| texts(&s.shape, &mut all)); + all + } + type Open = fn(&mut VectorcraftApp); + let dialogs: [(&str, Open, &str); 5] = [ + ( + "Flatten Transparency", + |app| { + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + app.run("transparency.set", json!({"opacity": 50})).unwrap(); + app.run("ui.flattenTransparencyDialog", json!({})).unwrap(); + }, + "ppp", + ), + ( + "Document Raster Effects Settings", + |app| { + crate::menus::invoke(app, "document.rasterEffectsSettings", json!({})); + app.ui.dialog.as_mut().unwrap().fields.insert("resolution".into(), json!(200)); + }, + "200 ppp", + ), + ( + "Rasterize", + |app| { + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + crate::menus::invoke(app, "effect.dialog", json!({"effect": "rasterize"})); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("useDocumentResolution".into(), json!(false)); + d.fields.insert("resolution".into(), json!(200)); + }, + "200 ppp", + ), + ( + "PNG Options", + |app| { + png_options::open(app, vectorcraft_engine::cmd::fileio::format("png").unwrap(), json!({"format": "png", "path": "/out/a.png"})); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("ppi".into(), json!(200)); + d.fields.insert("__otherPpi".into(), json!(true)); + }, + "200 ppp", + ), + ( + "Save PDF", + |app| { + app.run("ui.savePdfDialog", json!({"path": "/tmp/ppi.pdf"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("__section".into(), json!("Compression")); + }, + " ppp", + ), + ]; + let mut bad = vec![]; + for (name, open, want) in dialogs { + let mut app = app(); + open(&mut app); + crate::i18n::set_current(crate::i18n::Lang::from_code("fr").unwrap()); + let texts = shown(&mut app); + crate::i18n::set_current(crate::i18n::Lang::EN); + let translated = texts.iter().any(|t| t.trim() == want.trim() || (want.starts_with(' ') && t.ends_with(want))); + let english = texts.iter().any(|t| t.trim() == "ppi" || t.ends_with(" ppi")); + if !translated || english { + bad.push(format!("{name}: {texts:?}")); + } + } + assert!(bad.is_empty(), "{}", bad.join("\n")); +} diff --git a/crates/ui-egui/src/dialogs/tests_eps.rs b/crates/ui-egui/src/dialogs/tests_eps.rs index bebe8a1407..5cd2efe24c 100644 --- a/crates/ui-egui/src/dialogs/tests_eps.rs +++ b/crates/ui-egui/src/dialogs/tests_eps.rs @@ -67,6 +67,224 @@ fn eps_options_take_saved_flattener_presets_and_refuse_bad_ones() { assert!(written.borrow()[0].1.starts_with(b"%!PS-Adobe-3.0 EPSF-3.0"), "{:?}", &written.borrow()[0].1[..8]); } +/// Two overlapping squares, the second half transparent, so that an EPS export flattens them. +fn transparent_art(app: &mut VectorcraftApp) { + for (x, color) in [(5, "#ff0000"), (20, "#0000ff")] { + app.run("select.none", json!({})).unwrap(); + app.run("paint.setFill", json!({"color": color})).unwrap(); + app.run("shape.rectangle", json!({"x": x, "y": 5, "width": 30, "height": 30})).unwrap(); + } + app.run("transparency.set", json!({"opacity": 50})).unwrap(); +} + +/// Custom… over EPS Options, as its button opens it. +fn open_custom(app: &mut VectorcraftApp) { + let parent = app.ui.dialog.clone().expect("EPS Options are open"); + app.ui.dialog = Some(eps_options::over(&parent, &app.session.prefs.flattener_presets)); + frame(app); +} + +#[test] +fn custom_flattener_options_start_from_the_preset_and_cancel_goes_back_unchanged() { + let (mut app, _) = app(1); + app.run("ui.epsOptionsDialog", json!({"path": "/out/a.eps", "flattenerPreset": "high"})).unwrap(); + frame(&mut app); + let before = app.ui.dialog.as_ref().unwrap().fields.clone(); + open_custom(&mut app); + assert_eq!(kind(&app), Some(eps_options::CUSTOM_KIND)); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.f64("balance", 0.0), d.f64("lineArtPpi", 0.0), d.bool("clipComplexRegions")), (100.0, 1200.0, true), "High Resolution's"); + assert!(!d.bool("preserveAlpha"), "EPS has no alpha"); + set(&mut app, "balance", json!(10)); + cancel(&mut app); + assert_eq!(kind(&app), Some("epsOptions")); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields, before, "Cancel leaves EPS Options as they were"); +} + +#[test] +fn custom_flattener_options_are_exported_and_remembered_until_a_preset_is_chosen() { + let (mut app, written) = app(1); + transparent_art(&mut app); + app.run("flattener.presets.save", json!({"name": "Mine", "balance": 100})).unwrap(); + let opts = json!({"path": "/out/a.eps", "flattenerPreset": "Mine", "previewFormat": "none", "thumbnails": false}); + app.run("ui.epsOptionsDialog", opts).unwrap(); + frame(&mut app); + open_custom(&mut app); + assert_eq!(app.ui.dialog.as_ref().unwrap().f64("balance", 0.0), 100.0, "the saved preset's"); + set(&mut app, "balance", json!(0)); + confirm(&mut app).unwrap(); + assert_eq!(kind(&app), Some("epsOptions"), "OK goes back to EPS Options"); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.fields["flattener"]["balance"].as_f64(), d.fields["flattener"]["preserveAlpha"].as_bool()), (Some(0.0), Some(false))); + assert_eq!(d.str("flattenerPreset"), "Medium Resolution", "a built-in preset under options that set everything"); + frame(&mut app); + // The custom options don't need the saved preset they started from. + app.run("flattener.presets.delete", json!({"name": "Mine"})).unwrap(); + confirm(&mut app).unwrap(); + assert!(ps(&written.borrow()[0].1).contains("image"), "balance 0 rasterizes the flattened art"); + // The next EPS Options start from them; a preset asked for without options drops them. + crate::menus::invoke(&mut app, "ui.epsOptionsDialog", json!({})); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["flattener"]["balance"].as_f64(), Some(0.0)); + cancel(&mut app); + app.run("ui.epsOptionsDialog", json!({"path": "/out/b.eps", "flattenerPreset": "medium"})).unwrap(); + assert!(!app.ui.dialog.as_ref().unwrap().fields.contains_key("flattener")); + confirm(&mut app).unwrap(); + assert!(!ps(&written.borrow()[1].1).contains("image"), "Medium Resolution keeps the squares vector"); +} + +#[test] +fn a_flattener_preset_set_from_outside_drops_the_custom_options() { + let (mut app, _) = app(1); + app.run("ui.epsOptionsDialog", json!({"path": "/out/a.eps"})).unwrap(); + frame(&mut app); + open_custom(&mut app); + set(&mut app, "balance", json!(20)); + confirm(&mut app).unwrap(); + assert!(app.ui.dialog.as_ref().unwrap().fields.contains_key("flattener")); + // `ui.dialog.set {flattenerPreset: "low"}`, as the control channel sets it. + let old = app.ui.dialog.as_ref().unwrap().fields.get("flattenerPreset").cloned(); + set(&mut app, "flattenerPreset", json!("low")); + field_set(&mut app, "flattenerPreset", old.as_ref()).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert!(!d.fields.contains_key("flattener"), "the preset replaces the custom options"); + assert_eq!(d.str("flattenerPreset"), "Low Resolution"); +} + +#[test] +fn bad_custom_flattener_options_keep_the_dialog_open() { + let (mut app, _) = app(1); + app.run("ui.epsOptionsDialog", json!({"path": "/out/a.eps", "overprints": "discard"})).unwrap(); + frame(&mut app); + open_custom(&mut app); + set(&mut app, "gradientPpi", json!(9000)); + frame(&mut app); + let e = confirm(&mut app).unwrap_err(); + assert!(e.contains("resolutions"), "{e}"); + assert_eq!(kind(&app), Some(eps_options::CUSTOM_KIND)); + // Overprints decides whether overprints are kept, so OK keeps the option as it was. + set(&mut app, "gradientPpi", json!(150)); + set(&mut app, "preserveAlpha", json!(true)); + confirm(&mut app).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.fields["flattener"]["preserveOverprints"].as_bool(), d.fields["flattener"]["preserveAlpha"].as_bool()), (Some(true), Some(false))); +} + +/// Headless frames of the dialog layer with screen-reader output, input events and a clock. +pub(super) struct Frames { + ctx: egui::Context, + time: f64, +} + +impl Frames { + pub(super) fn new() -> Self { + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + Self { ctx, time: 0.0 } + } + + fn run(&mut self, app: &mut VectorcraftApp, events: Vec) -> egui::FullOutput { + self.time += 0.1; + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1280.0, 900.0)); + let input = egui::RawInput { events, time: Some(self.time), screen_rect: Some(screen), ..Default::default() }; + let mut out = self.ctx.run_ui(input, |ui| show(app, ui.ctx())); + out.textures_delta.clear(); + out + } + + /// The screen-reader node of the control of `role` named `label`, with its center. + pub(super) fn control(&mut self, app: &mut VectorcraftApp, label: &str, role: egui::accesskit::Role) -> (egui::accesskit::NodeId, egui::Pos2) { + self.run(app, vec![]); + let out = self.run(app, vec![]); + let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; + let (id, n) = + nodes.iter().find(|(_, n)| n.label() == Some(label) && n.role() == role).unwrap_or_else(|| panic!("no {role:?} named {label:?}")); + let b = n.bounds().expect("bounds"); + (*id, egui::pos2((b.x0 + b.x1) as f32 * 0.5, (b.y0 + b.y1) as f32 * 0.5)) + } + + pub(super) fn click(&mut self, app: &mut VectorcraftApp, at: egui::Pos2) { + for pressed in [true, false] { + let button = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + self.run(app, vec![egui::Event::PointerMoved(at), button]); + } + } + + /// Click the text field named `label`, type `text` over its text and press Tab. + pub(super) fn type_into(&mut self, app: &mut VectorcraftApp, label: &str, text: &str) { + let (_, at) = self.control(app, label, egui::accesskit::Role::TextInput); + self.click(app, at); + self.run(app, vec![egui::Event::Text(text.into())]); + let tab = |pressed| egui::Event::Key { key: egui::Key::Tab, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; + self.run(app, vec![tab(true)]); + self.run(app, vec![tab(false)]); + self.run(app, vec![]); + } +} + +/// Enter on the focused Custom… button opens the custom options and does not also confirm them. +#[test] +fn enter_on_the_custom_button_opens_the_custom_options() { + use egui::accesskit::{Action, ActionRequest, Role, TreeId}; + let (mut app, _) = app(1); + app.run("flattener.presets.save", json!({"name": "Mine", "balance": 0})).unwrap(); + app.run("ui.epsOptionsDialog", json!({"path": "/out/a.eps", "flattenerPreset": "Mine"})).unwrap(); + let mut f = Frames::new(); + let (node, _) = f.control(&mut app, "Custom…", Role::Button); + f.run( + &mut app, + vec![egui::Event::AccessKitActionRequest(ActionRequest { action: Action::Focus, target_node: node, target_tree: TreeId::ROOT, data: None })], + ); + let enter = |pressed| egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; + f.run(&mut app, vec![enter(true)]); + f.run(&mut app, vec![enter(false)]); + assert_eq!(kind(&app), Some(eps_options::CUSTOM_KIND), "the custom options stay open"); + let parent = super::parent(app.ui.dialog.as_ref().unwrap()).unwrap(); + assert_eq!(parent.str("flattenerPreset"), "Mine", "EPS Options keep their preset"); +} + +/// With a value out of range, the editor shows the values entered, and changing a switch keeps +/// them, so OK still refuses the bad value. +#[test] +fn a_switch_changed_beside_a_bad_value_keeps_the_values_entered() { + let (mut app, _) = app(1); + app.run("ui.epsOptionsDialog", json!({"path": "/out/a.eps"})).unwrap(); + frame(&mut app); + open_custom(&mut app); + set(&mut app, "balance", json!(20)); + set(&mut app, "gradientPpi", json!(9000)); + set(&mut app, "lineArtPpi", json!("many")); + let mut f = Frames::new(); + let (_, at) = f.control(&mut app, "Convert All Text to Outlines", egui::accesskit::Role::CheckBox); + let before = app.ui.dialog.as_ref().unwrap().bool("textToOutlines"); + f.click(&mut app, at); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(d.bool("textToOutlines"), !before, "the switch changes"); + assert_eq!((d.f64("balance", 0.0), d.f64("gradientPpi", 0.0)), (20.0, 9000.0), "the other values stay as entered"); + assert_eq!(d.fields["lineArtPpi"], json!("many"), "a value of the wrong type stays to be refused"); + assert!(confirm(&mut app).is_err()); + set(&mut app, "lineArtPpi", json!(300)); + assert!(confirm(&mut app).unwrap_err().contains("resolutions")); +} + +/// A value of the wrong type shows blank, and typing the default preset's value into its field +/// replaces it, so OK takes the options. +#[test] +fn the_default_value_typed_over_a_value_of_the_wrong_type_replaces_it() { + let (mut app, _) = app(1); + app.run("ui.epsOptionsDialog", json!({"path": "/out/a.eps"})).unwrap(); + frame(&mut app); + open_custom(&mut app); + set(&mut app, "lineArtPpi", json!("many")); + let default = vectorcraft_engine::cmd::FlattenOptions::default().line_art_ppi; + let mut f = Frames::new(); + f.type_into(&mut app, "Line Art and Text Resolution:", &default.to_string()); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["lineArtPpi"], json!(default)); + confirm(&mut app).unwrap(); + assert_eq!(kind(&app), Some("epsOptions")); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["flattener"]["lineArtPpi"].as_f64(), Some(default)); +} + #[test] fn the_eps_options_dialog_needs_a_document() { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); diff --git a/crates/ui-egui/src/dialogs/tests_import_pdf.rs b/crates/ui-egui/src/dialogs/tests_import_pdf.rs index 62e783c267..5ecd7734cb 100644 --- a/crates/ui-egui/src/dialogs/tests_import_pdf.rs +++ b/crates/ui-egui/src/dialogs/tests_import_pdf.rs @@ -95,12 +95,19 @@ fn import_pdf_pages_as_links_opens_each_page_linked() { let path = dir.join("three.pdf").to_string_lossy().into_owned(); std::fs::write(&path, three_pages()).unwrap(); let mut app = app(); + // All pages: checked without a click. io::open_bytes(&mut app, &path, &three_pages(), Some(path.clone())).unwrap(); - assert_eq!(field(&app, "linkPages"), false, "off by default"); frame(&mut app); - set(&mut app, "linkPages", json!(true)); + confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(artboard_widths(&app), [100.0, 200.0, 300.0]); + assert_eq!(placed_pages(&app), [true, true, true], "All opens the pages linked"); + // A range: cleared, and checked by hand it opens the range linked. + io::open_bytes(&mut app, &path, &three_pages(), Some(path.clone())).unwrap(); set(&mut app, "allPages", json!(false)); set(&mut app, "range", json!("1, 3")); + assert!(!import_pdf::links_on(app.ui.dialog.as_ref().unwrap()), "Range: cleared"); + set(&mut app, "linkPages", json!(true)); frame(&mut app); confirm(&mut app).unwrap(); assert!(app.ui.dialog.is_none()); @@ -124,6 +131,41 @@ fn import_pdf_pages_as_links_opens_each_page_linked() { assert_eq!(placed_pages(&app), [false, false]); } +/// Picking All checks Import PDF pages as links and picking Range clears it. A click on the box +/// stands until the other one is picked; picking the one already picked or editing the range keeps +/// it. `ui.dialog.set` picks the way the buttons do. +#[test] +fn picking_all_or_a_range_sets_the_links_default() { + let mut app = app(); + io::open_bytes(&mut app, "three.pdf", &three_pages(), Some("/tmp/three.pdf".into())).unwrap(); + let pick = |app: &mut VectorcraftApp, k: &str, v: serde_json::Value| set_field(app.ui.dialog.as_mut().unwrap(), k.into(), v); + let on = |app: &VectorcraftApp| import_pdf::links_on(app.ui.dialog.as_ref().unwrap()); + assert!(on(&app), "All: checked"); + pick(&mut app, "allPages", json!(false)); + assert!(!on(&app), "Range: cleared"); + pick(&mut app, "linkPages", json!(true)); + pick(&mut app, "allPages", json!(false)); + pick(&mut app, "range", json!("1-2")); + frame(&mut app); + assert!(on(&app), "checked by hand, picking Range again and editing the range keep it"); + pick(&mut app, "allPages", json!(true)); + assert!(on(&app), "All: checked"); + pick(&mut app, "linkPages", json!(false)); + pick(&mut app, "allPages", json!(true)); + frame(&mut app); + assert!(!on(&app), "cleared by hand, picking All again keeps it"); + pick(&mut app, "allPages", json!(false)); + pick(&mut app, "allPages", json!(true)); + assert!(on(&app), "All picked after Range: checked again"); + // A file `linkPages` does not take (one over its size limit) leaves the box clear. + assert_eq!(field(&app, "__linkable"), true); + set(&mut app, "__linkable", json!(false)); + assert!(!on(&app), "a file linkPages does not take"); + // A file given without its path can't link its pages: the box stays clear. + io::open_bytes(&mut app, "three.pdf", &three_pages(), None).unwrap(); + assert!(!on(&app)); +} + #[test] fn single_page_pdfs_open_directly() { let mut app = app(); diff --git a/crates/ui-egui/src/dialogs/tests_modal.rs b/crates/ui-egui/src/dialogs/tests_modal.rs index 06eef4d2c6..29a37ac4ad 100644 --- a/crates/ui-egui/src/dialogs/tests_modal.rs +++ b/crates/ui-egui/src/dialogs/tests_modal.rs @@ -678,6 +678,14 @@ fn simplify_dialog_preview_counts_and_cancel_restore_the_original() { let texts = frame(&ctx, &mut app, vec![]); let preview = texts.iter().find(|(t, _)| t == "Preview").map(|(_, r)| *r).expect("a Preview checkbox"); assert!(texts.iter().any(|(t, _)| t == "Anchor Points: 20 → 2"), "the reduction is visible: {texts:?}"); + // In French the label ends in a no-break space and a colon (#7991). + let fr = crate::i18n::Lang::from_code("fr").unwrap(); + crate::i18n::set_current(fr); + let french = frame(&ctx, &mut app, vec![]); + crate::i18n::set_current(crate::i18n::Lang::EN); + let want = format!("{}\u{a0}: 20 → 2", crate::i18n::tr(fr, "Anchor Points")); + assert!(french.iter().any(|(t, _)| *t == want), "{want:?} in {french:?}"); + frame(&ctx, &mut app, vec![]); assert!(app.session.in_interaction()); assert!(app.session.doc().unwrap().selection.anchors.is_empty()); assert_eq!(app.session.doc().unwrap().history.undo.len(), undo_len); diff --git a/crates/ui-egui/src/dialogs/tests_print.rs b/crates/ui-egui/src/dialogs/tests_print.rs index cad38bb984..00b45e0db7 100644 --- a/crates/ui-egui/src/dialogs/tests_print.rs +++ b/crates/ui-egui/src/dialogs/tests_print.rs @@ -428,13 +428,17 @@ fn request(action: egui::accesskit::Action, target_node: egui::accesskit::NodeId egui::Event::AccessKitActionRequest(ActionRequest { action, target_node, target_tree: TreeId::ROOT, data: None }) } -/// Type `typed` into Scale W, which shows `shown` (the first field that does, before H), and Tab out. +/// Type `typed` into Scale W, which shows `shown` (the leftmost field that does, before H), and Tab out. fn type_w(screen: &mut Screen, app: &mut VectorcraftApp, shown: &str, typed: &str) { let key = |key, modifiers| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }; screen.run(app, vec![]); let out = screen.run(app, vec![]); let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; - let w = nodes.iter().find(|(_, n)| n.role() == egui::accesskit::Role::TextInput && n.value().is_some_and(|v| v.starts_with(shown))); + // W is left of H on their row (the tree lists its nodes in no particular order). + let w = nodes + .iter() + .filter(|(_, n)| n.role() == egui::accesskit::Role::TextInput && n.value().is_some_and(|v| v.starts_with(shown))) + .min_by(|(_, a), (_, b)| a.bounds().map_or(f64::MAX, |r| r.x0).total_cmp(&b.bounds().map_or(f64::MAX, |r| r.x0))); screen.run(app, vec![request(egui::accesskit::Action::Focus, w.expect("the Scale W field").0)]); screen.run(app, vec![key(egui::Key::A, egui::Modifiers::COMMAND), egui::Event::Text(typed.into())]); screen.run(app, vec![key(egui::Key::Tab, egui::Modifiers::NONE)]); diff --git a/crates/ui-egui/src/dialogs/tests_raster_supplied_options.rs b/crates/ui-egui/src/dialogs/tests_raster_supplied_options.rs new file mode 100644 index 0000000000..a1c22e2db0 --- /dev/null +++ b/crates/ui-egui/src/dialogs/tests_raster_supplied_options.rs @@ -0,0 +1,54 @@ +use serde_json::json; +use vectorcraft_engine::cmd::fileio; + +use super::tests_export::{app, frame, kind}; +use super::{confirm, png_options}; + +#[test] +fn raster_options_preserve_supplied_values_through_the_png_command() { + let (mut app, written) = app(1); + app.run("file.export.png", json!({"ppi": 300, "background": "#204080", "antiAlias": "type", "interlaced": true})).unwrap(); + assert_eq!(kind(&app), Some("pngOptions")); + let fields = &app.ui.dialog.as_ref().unwrap().fields; + assert_eq!(fields["ppi"], 300); + assert_eq!(fields["background"], "#204080"); + assert_eq!(fields["antiAlias"], "type"); + assert_eq!(fields["interlaced"], true); + frame(&mut app); + confirm(&mut app).unwrap(); + { + let output = written.borrow(); + assert_eq!(output.len(), 1); + let png = &output[0].1; + assert_eq!(png[28], 1); + let physical = png.windows(4).position(|w| w == b"pHYs").unwrap(); + assert_eq!(&png[physical + 4..physical + 8], ((300.0f64 / 0.0254).round() as u32).to_be_bytes()); + let decoded = craft_image_codecs::decode(png).unwrap(); + assert_eq!(decoded.dimensions(), (250, 167)); + assert_eq!(&decoded.to_rgba8()[..4], &[0x20, 0x40, 0x80, 255]); + } + + png_options::open(&mut app, fileio::format("jpg").unwrap(), json!({"format": "jpg", "path": "/out/supplied.jpg", "ppi": 144, "quality": 40})); + let fields = &app.ui.dialog.as_ref().unwrap().fields; + assert_eq!(fields["quality"], 40); + assert_eq!(fields["ppi"], 144); + assert_eq!(fields["background"], "white"); + frame(&mut app); + confirm(&mut app).unwrap(); + assert_eq!(written.borrow().len(), 2); + + for omitted in [json!({}), json!({"ppi": null, "background": null, "antiAlias": null, "interlaced": null})] { + app.run("file.export.png", omitted).unwrap(); + let fields = &app.ui.dialog.as_ref().unwrap().fields; + assert_eq!(fields["ppi"], 72); + assert_eq!(fields["background"], "transparent"); + assert_eq!(fields["antiAlias"], "art"); + assert_eq!(fields["interlaced"], false); + app.ui.dialog = None; + } + + app.run("file.export.png", json!({"ppi": 0})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["ppi"], 0); + assert!(confirm(&mut app).unwrap_err().contains("ppi must be a positive number")); + assert_eq!(written.borrow().len(), 2); +} diff --git a/crates/ui-egui/src/dialogs/tests_rectangular_grid.rs b/crates/ui-egui/src/dialogs/tests_rectangular_grid.rs index ef5dca5ede..e2db8b6d75 100644 --- a/crates/ui-egui/src/dialogs/tests_rectangular_grid.rs +++ b/crates/ui-egui/src/dialogs/tests_rectangular_grid.rs @@ -339,6 +339,20 @@ fn rectangular_grid_failed_creation_does_not_save_counts() { assert_eq!(app.session.doc().unwrap().history.undo.len(), before.undo); } +/// Tool Options with a width the tool refuses is an error that keeps the dialog open and sets +/// nothing. +#[test] +fn rectangular_grid_tool_options_with_a_refused_width_stay_open() { + let mut app = app(); + let before = app.session.tool_options_of(KIND); + super::shapes::open_options(&mut app, KIND).unwrap(); + set(&mut app, "width", json!(0)); + let e = super::confirm(&mut app).unwrap_err(); + assert!(e.contains("`width`"), "{e}"); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND)); + assert_eq!(app.session.tool_options_of(KIND), before); +} + /// #1377: the dialog shows the tool's stored skews (sliders under their divider counts) and /// switches; OK draws with them and stores them, and the next drag uses them too. #[test] diff --git a/crates/ui-egui/src/dialogs/tests_save_for_web.rs b/crates/ui-egui/src/dialogs/tests_save_for_web.rs index 17c565e454..e27f4b766c 100644 --- a/crates/ui-egui/src/dialogs/tests_save_for_web.rs +++ b/crates/ui-egui/src/dialogs/tests_save_for_web.rs @@ -727,6 +727,141 @@ fn colour_table_buttons_edit_the_lists() { assert_eq!(d.fields["colorTable"], json!({"locked": [], "webShift": ["#123456"], "sort": "hue"})); } +/// A click selects one color, a Shift-click the range from the last one clicked, a Ctrl-click +/// (Command-click) adds or removes one; Delete Color deletes the whole selection in one edit, +/// takes it out of the other lists, fixes the palette and refuses to delete every color. +#[test] +fn colour_table_selection_and_delete_color() { + let mut d = Dialog::new(save_for_web::KIND, json!({})); + let order: Vec = ["#000000", "#111111", "#222222", "#333333"].map(String::from).to_vec(); + let sel = |d: &Dialog| save_for_web::selection(d); + assert!(sel(&d).is_empty()); + save_for_web::pick(&mut d, &order, "#111111", false, false); + assert_eq!(sel(&d), ["#111111"]); + save_for_web::pick(&mut d, &order, "#333333", true, false); + assert_eq!((sel(&d), d.str("__color")), (vec!["#111111".to_string(), "#222222".into(), "#333333".into()], "#111111".into())); + save_for_web::pick(&mut d, &order, "#222222", false, true); + assert_eq!(sel(&d), ["#111111", "#333333"]); + save_for_web::pick(&mut d, &order, "#000000", false, true); + assert_eq!((sel(&d), d.str("__color")), (vec!["#111111".to_string(), "#333333".into(), "#000000".into()], "#000000".into())); + save_for_web::pick(&mut d, &order, "#000000", false, true); + assert_eq!((sel(&d), d.str("__color")), (vec!["#111111".to_string(), "#333333".into()], "#333333".into())); + // A Shift-click back from the anchor. + save_for_web::pick(&mut d, &order, "#222222", false, false); + save_for_web::pick(&mut d, &order, "#000000", true, false); + assert_eq!(sel(&d), ["#000000", "#111111", "#222222"]); + // `__color` alone (an agent's selection) is the selection too. + d.fields.remove("__colors"); + d.fields.insert("__color".into(), json!("#222222")); + assert_eq!(sel(&d), ["#222222"]); + + save_for_web::toggle(&mut d, "locked", "#222222", true); + save_for_web::toggle(&mut d, "locked", "#000000", true); + save_for_web::toggle(&mut d, "webShift", "#333333", true); + save_for_web::pick(&mut d, &order, "#333333", false, true); + save_for_web::delete_colors(&mut d, &order).unwrap(); + assert_eq!(d.fields["colorTable"], json!({"locked": ["#000000"], "webShift": [], "customPalette": order, "deleted": ["#222222", "#333333"]})); + assert!(!d.fields.contains_key("__colors") && !d.fields.contains_key("__color") && sel(&d).is_empty()); + // Nothing selected: nothing deleted. + let before = d.fields.clone(); + save_for_web::delete_colors(&mut d, &order).unwrap(); + assert_eq!(d.fields, before); + // The colors left can't all go: refused, nothing changed. + save_for_web::pick(&mut d, &order, "#000000", false, false); + save_for_web::pick(&mut d, &order, "#111111", false, true); + let before = d.fields.clone(); + assert_eq!(save_for_web::delete_colors(&mut d, &order), Err(vectorcraft_engine::cmd::webexport::KEEP_ONE.to_string())); + assert_eq!(d.fields, before); + // Nor can the last color that is not mapped to transparent. + save_for_web::toggle(&mut d, "transparent", "#111111", true); + save_for_web::pick(&mut d, &order, "#000000", false, false); + let before = d.fields.clone(); + assert_eq!(save_for_web::delete_colors(&mut d, &order), Err(vectorcraft_engine::cmd::webexport::KEEP_ONE.to_string())); + assert_eq!(d.fields, before); + // Restore Generated Table. + save_for_web::restore_table(&mut d); + assert_eq!((&d.fields["colorTable"]["deleted"], &d.fields["colorTable"]["customPalette"]), (&json!([]), &json!([]))); +} + +/// Click the dialog's text `label` with the pointer (frames a quarter second apart). +fn click_text(app: &mut VectorcraftApp, label: &str) { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let frame = |app: &mut VectorcraftApp, events: Vec| { + let time = ctx.input(|i| i.time) + 0.25; + let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 1000.0))); + let raw = egui::RawInput { screen_rect, events, time: Some(time), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| show(app, ui.ctx())); + out.textures_delta.clear(); + fn walk(s: &egui::Shape, v: &mut Vec<(String, egui::Rect)>) { + match s { + egui::Shape::Text(t) => v.push((t.galley.text().to_string(), egui::Rect::from_min_size(t.pos, t.galley.size()))), + egui::Shape::Vec(s) => s.iter().for_each(|s| walk(s, v)), + _ => {} + } + } + let mut v = vec![]; + out.shapes.iter().for_each(|c| walk(&c.shape, &mut v)); + v + }; + frame(app, vec![]); + let texts = frame(app, vec![]); + let at = texts.iter().find(|(t, _)| t == label).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("no `{label}` in {texts:?}")); + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(app, vec![egui::Event::PointerMoved(at)]); + frame(app, vec![press(true)]); + frame(app, vec![press(false)]); +} + +/// A Custom table whose preview fails (only a color mapped to transparent left) still offers +/// Restore Generated Table, which brings the preview back. +#[test] +fn restore_generated_table_shows_when_the_preview_fails() { + let dir = vectorcraft_testkit::temp_dir("sfw-restore-table"); + let (mut app, _) = app(&dir, false); + app.run("shape.rectangle", json!({"x": 40, "y": 0, "width": 20, "height": 40})).unwrap(); + app.run("paint.setFill", json!({"color": "#0000ff"})).unwrap(); + app.run("file.saveForWeb", json!({})).unwrap(); + let table = json!({"deleted": ["#cc3300"], "customPalette": ["#cc3300", "#0000ff"], "transparent": ["#0000ff"]}); + for (k, v) in [("format", json!("gif")), ("antiAlias", json!("none")), ("dither", json!("none")), ("colorTable", table)] { + set(&mut app, k, v); + } + let p = json!({"format": "gif", "antiAlias": "none", "colorTable": app.ui.dialog.as_ref().unwrap().fields["colorTable"].clone()}); + assert!(app.session.execute("document.exportForWeb.preview", &p).is_err(), "the preview fails"); + click_text(&mut app, "Restore Generated Table"); + let t = &app.ui.dialog.as_ref().unwrap().fields["colorTable"]; + assert_eq!((&t["deleted"], &t["customPalette"]), (&json!([]), &json!([]))); +} + +/// The saved file lacks the deleted color, whose pixels take the color left; the edit is +/// remembered, reopens with the dialog and stays through a format change. +#[test] +fn delete_color_reaches_the_saved_file_and_is_remembered() { + let dir = vectorcraft_testkit::temp_dir("sfw-delete-color"); + let (mut app, _) = app(&dir, false); + app.run("shape.rectangle", json!({"x": 40, "y": 0, "width": 20, "height": 40})).unwrap(); + app.run("paint.setFill", json!({"color": "#0000ff"})).unwrap(); + app.run("file.saveForWeb", json!({})).unwrap(); + for (k, v) in [("format", json!("gif")), ("antiAlias", json!("none")), ("dither", json!("none"))] { + set(&mut app, k, v); + } + frame(&mut app); + set(&mut app, "__colors", json!(["#cc3300"])); + save_for_web::delete_colors(app.ui.dialog.as_mut().unwrap(), &["#cc3300".into(), "#0000ff".into()]).unwrap(); + frame(&mut app); + for format in ["jpg", "gif"] { + set(&mut app, "format", json!(format)); + frame(&mut app); + } + let r = confirm(&mut app).unwrap(); + let image = image::open(r["path"].as_str().unwrap()).unwrap().to_rgba8(); + assert_eq!((image.get_pixel(20, 14).0, image.get_pixel(50, 20).0), ([0, 0, 255, 255], [0, 0, 255, 255])); + assert_eq!(app.session.last_web_settings().color_table.deleted, ["#cc3300"]); + app.run("file.saveForWeb", json!({})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["colorTable"]["deleted"], json!(["#cc3300"])); + frame(&mut app); +} + #[test] fn optimize_to_file_size_takes_the_settings_that_fit() { let dir = vectorcraft_testkit::temp_dir("sfw-optimize"); diff --git a/crates/ui-egui/src/dialogs/tests_scroll.rs b/crates/ui-egui/src/dialogs/tests_scroll.rs new file mode 100644 index 0000000000..bb013802ed --- /dev/null +++ b/crates/ui-egui/src/dialogs/tests_scroll.rs @@ -0,0 +1,449 @@ +//! Dialogs in a short or narrow window: a dialog too large for the window scrolls instead of +//! running off the screen. Every scroll bar here is drawn at rest (a solid bar style), so the tests +//! can find it. + +use egui::{Pos2, Rect, Shape, vec2}; +use serde_json::json; +use vectorcraft_engine::Session; + +use super::*; + +type Open = fn(&mut VectorcraftApp); + +/// What a dialog drew: the shapes, the dialog window's rectangle, and how it scrolls +/// ([`modal::scrolling`]). +struct Shown { + shapes: Vec, + window: Rect, + body: Option, + whole: [bool; 2], +} + +/// Open a dialog with `open` in a `size` window, with the pointer in the window's corner (away +/// from the dialog), and draw it until it settles. With `scroll`, then scroll far down and right +/// near the dialog's right edge (on the bar of a window that scrolls as a whole, beside the lists +/// inside it) and draw it until it settles again. +fn show_in(open: Open, size: egui::Vec2, scroll: bool) -> Shown { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 80, "height": 60})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, Default::default()); + ctx.global_style_mut(|s| s.spacing.scroll = egui::style::ScrollStyle::solid()); + open(&mut app); + let screen = Rect::from_min_size(Pos2::ZERO, size); + let window = |ctx: &egui::Context| { + ctx.memory(|m| { + m.areas() + .visible_layer_ids() + .into_iter() + .filter(|l| l.order == egui::Order::Foreground) + .filter_map(|l| Some((l.id, m.area_rect(l.id)?))) + .max_by(|a, b| a.1.area().total_cmp(&b.1.area())) + }) + .unwrap_or((egui::Id::NULL, Rect::NOTHING)) + }; + let mut time = 0.0; + let mut frames = |app: &mut VectorcraftApp, first: Vec| { + let mut first = Some(first); + let mut shapes = vec![]; + for _ in 0..12 { + time += 1.0; + let input = + egui::RawInput { screen_rect: Some(screen), events: first.take().unwrap_or_default(), time: Some(time), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| show(app, ui.ctx())); + out.textures_delta.clear(); + shapes = std::mem::take(&mut out.shapes); + } + shapes + }; + let mut shapes = frames(&mut app, vec![egui::Event::PointerMoved(screen.max - vec2(2.0, 2.0))]); + if scroll { + let wheel = egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: vec2(-5000.0, -5000.0), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Unknown, + modifiers: egui::Modifiers::NONE, + }; + let (id, w) = window(&ctx); + let (body, whole) = modal::scrolling(&ctx, id); + let before = Shown { shapes: std::mem::take(&mut shapes), window: w, body, whole }; + // On the window's upright bar, else on its body's bar, else on its sideways bar, else at + // its right edge. + let sideways = bars(&before, true, true).into_iter().find(|r| r.width() >= 0.5 * w.width()); + let at = whole_bar(&before).or(body_bar(&before)).or(sideways).map_or(egui::pos2(w.right() - 23.0, w.center().y), |r| r.center()); + shapes = frames(&mut app, vec![egui::Event::PointerMoved(at), wheel]); + } + let (id, window) = window(&ctx); + let (body, whole) = modal::scrolling(&ctx, id); + Shown { shapes, window, body, whole } +} + +/// Filled bars 4 to 10 pt across and longer than 12 pt (scroll bars and their handles), upright or +/// (`sideways`) flat, inside the dialog window; with `seen`, only those inside their clip. +fn bars(shown: &Shown, sideways: bool, seen: bool) -> Vec { + fn walk(s: &Shape, clip: Rect, sideways: bool, seen: bool, out: &mut Vec) { + match s { + Shape::Rect(r) if r.fill != egui::Color32::TRANSPARENT => { + let (across, along) = if sideways { (r.rect.height(), r.rect.width()) } else { (r.rect.width(), r.rect.height()) }; + if (4.0..=10.0).contains(&across) && along > 12.0 && (!seen || clip.contains_rect(r.rect)) { + out.push(r.rect); + } + } + Shape::Vec(v) => v.iter().for_each(|s| walk(s, clip, sideways, seen, out)), + _ => {} + } + } + let mut out = vec![]; + shown.shapes.iter().for_each(|c| walk(&c.shape, c.clip_rect, sideways, seen, &mut out)); + out.retain(|r| shown.window.expand(0.5).contains_rect(*r)); + out +} + +/// The bar of a shared dialog's scrolling body: the rightmost upright bar as tall as the body is +/// drawn (a list inside the body draws its bar further left). +fn body_bar(shown: &Shown) -> Option { + let view = shown.body?; + bars(shown, false, true).into_iter().filter(|r| (r.height() - view).abs() <= 1.0).max_by(|a, b| a.right().total_cmp(&b.right())) +} + +/// The bar of a window that scrolls as a whole: an upright bar at the window's right edge that +/// runs most of the window's height (lists inside it are shorter). +fn whole_bar(shown: &Shown) -> Option { + let w = shown.window; + bars(shown, false, true) + .into_iter() + .filter(|r| r.right() >= w.right() - 24.0 && r.height() >= 0.8 * w.height()) + .max_by(|a, b| a.height().total_cmp(&b.height())) +} + +/// The texts `labels` the dialog drew, each with whether it can be seen (inside the screen and +/// its clip). +fn buttons(shown: &Shown, screen: Rect, labels: &[&str]) -> Vec<(String, bool)> { + texts(shown) + .into_iter() + .filter(|(s, ..)| labels.contains(&s.as_str())) + .map(|(s, r, clip)| (s, screen.contains_rect(r) && clip.contains_rect(r))) + .collect() +} + +#[test] +fn a_dialog_taller_than_the_window_scrolls_its_body_and_keeps_its_buttons_in_view() { + let opens: [(&str, Open, &[&str]); 7] = [ + ("SVG Options", |app| svg_options::open(app, svg_options::Mode::Export, Some("/tmp/x.svg")), &["OK", "Cancel"]), + ("EPS Options", |app| eps_options::open(app, &json!({"format": "eps", "path": "/tmp/x.eps"})), &["Export", "Cancel"]), + ("DXF Options", |app| dxf_options::open(app, &json!({"format": "dxf", "path": "/tmp/x.dxf"})), &["Export", "Cancel"]), + ( + "Save PDF", + |app| { + save_pdf::open(app, &json!({"path": "/tmp/x.pdf"})).unwrap(); + }, + &["Cancel"], + ), + ( + "Save for Web", + |app| { + save_for_web::open(app).unwrap(); + }, + &["Cancel", "Done"], + ), + ("Export for Screens", export_for_screens::open, &["Cancel"]), + ( + "Print", + |app| { + print::open(app).unwrap(); + }, + &["Cancel", "Done"], + ), + ]; + let screen = Rect::from_min_size(Pos2::ZERO, vec2(1024.0, 480.0)); + for (name, open, labels) in opens { + let tall = show_in(open, vec2(1280.0, 900.0), false); + assert!(tall.window.height() > screen.height(), "{name}: the dialog is taller than the short window ({:?})", tall.window); + assert_eq!((tall.body, tall.whole), (None, [false; 2]), "{name}: in a tall window nothing scrolls"); + let shown = show_in(open, screen.size(), false); + assert!(screen.contains_rect(shown.window), "{name}: the dialog stays on the screen: {:?}", shown.window); + let found = buttons(&shown, screen, labels); + assert_eq!(found.len(), labels.len(), "{name}: {found:?}"); + assert!(found.iter().all(|(_, seen)| *seen), "{name}: the buttons stay in view: {found:?}"); + assert_eq!(shown.whole, [false; 2], "{name}: the window does not scroll as a whole"); + let bar = body_bar(&shown); + assert!(bar.is_some(), "{name}: the body scrolls ({:?}) and its bar is drawn: {:?}", shown.body, bars(&shown, false, true)); + } +} + +#[test] +fn a_list_in_a_scrolling_body_is_no_taller_than_the_body() { + // The settings of Save for Web and the sections of Print and Save PDF scroll in lists of their + // own; in a short window those lists are no taller than the body shows, so each list and its + // bar can be scrolled into view whole. + let opens: [(&str, Open); 3] = [ + ("Save for Web", |app| { + save_for_web::open(app).unwrap(); + }), + ("Print", |app| { + print::open(app).unwrap(); + if let Some(d) = app.ui.dialog.as_mut() { + d.fields.insert("__section".into(), json!("Marks and Bleed")); + } + }), + ("Save PDF", |app| { + save_pdf::open(app, &json!({"path": "/tmp/x.pdf"})).unwrap(); + if let Some(d) = app.ui.dialog.as_mut() { + d.fields.insert("__section".into(), json!("Marks and Bleeds")); + } + }), + ]; + let screen = Rect::from_min_size(Pos2::ZERO, vec2(1024.0, 400.0)); + let mut wrong = vec![]; + for (name, open) in opens { + let shown = show_in(open, screen.size(), false); + let Some(body) = body_bar(&shown) else { + wrong.push(format!("{name}: the body does not scroll ({:?}): {:?}", shown.body, bars(&shown, false, false))); + continue; + }; + // The tracks of the lists' bars, seen or not: left of the body's bar and inside the window + // (a list taller than the body runs past the window's bottom). + let lists: Vec = bars(&shown, false, false).into_iter().filter(|r| r.right() < body.left()).collect(); + let tallest = lists.iter().map(|r| r.height()).fold(0.0, f32::max); + if tallest == 0.0 || tallest > body.height() + 0.5 { + wrong.push(format!("{name}: no list bar no taller than the body ({}): {:?}", body.height(), bars(&shown, false, false))); + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); +} + +#[test] +fn save_for_web_in_the_smallest_window_keeps_its_settings_and_buttons_in_view() { + let open: Open = |app| { + save_for_web::open(app).unwrap(); + }; + // The app window's smallest size, 800 by 500 pixels, at a UI scale of 100%, 110% and 125%. + let mut wrong = vec![]; + for size in [vec2(800.0, 500.0), vec2(727.0, 454.0), vec2(640.0, 400.0)] { + let screen = Rect::from_min_size(Pos2::ZERO, size); + let shown = show_in(open, size, false); + let labels = ["Format:", "Optimize to File Size…", "Cancel", "Done"]; + let found = buttons(&shown, screen, &labels); + if !screen.contains_rect(shown.window) || found.len() != labels.len() || !found.iter().all(|(_, seen)| *seen) { + wrong.push(format!("{size:?}: the dialog ({:?}) leaves its settings and buttons in view: {found:?}", shown.window)); + } + if body_bar(&shown).is_none() || shown.whole != [false; 2] { + wrong.push(format!("{size:?}: only the body scrolls ({:?}, {:?})", shown.body, shown.whole)); + } + // The controls under the narrower panes stay in their column, left of the settings. + let controls = text_rects(&shown, "Preview in Browser").first().map(|r| r.right()); + let settings = text_rects(&shown, "Format:").first().map(|r| r.left()); + if !matches!((controls, settings), (Some(c), Some(s)) if c < s) { + wrong.push(format!("{size:?}: Preview in Browser ({controls:?}) is left of the settings ({settings:?})")); + } + // Preview in Browser is right of the download speed list or on a row below it, not over it. + let button = text_rects(&shown, "Preview in Browser").first().copied(); + let speed = text_rects(&shown, "56.6 Kbps").first().copied(); + if !matches!((button, speed), (Some(b), Some(s)) if b.left() > s.right() + 16.0 || b.top() > s.bottom() + 8.0) { + wrong.push(format!("{size:?}: Preview in Browser ({button:?}) clears the download speed list ({speed:?})")); + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); +} + +/// The rectangles of the texts `label` the dialog drew. +fn text_rects(shown: &Shown, label: &str) -> Vec { + fn walk(s: &Shape, label: &str, out: &mut Vec) { + match s { + Shape::Text(t) if t.galley.text() == label => out.push(t.visual_bounding_rect()), + Shape::Vec(v) => v.iter().for_each(|s| walk(s, label, out)), + _ => {} + } + } + let mut out = vec![]; + shown.shapes.iter().for_each(|c| walk(&c.shape, label, &mut out)); + out +} + +#[test] +fn a_window_too_large_for_the_screen_scrolls_as_a_whole() { + let opens: [(&str, Open, &[&str]); 4] = [ + ("Preferences", |app| crate::prefs_dialog::open(app, None), &["OK", "Cancel"]), + ("Keyboard Shortcuts", crate::shortcut_editor::open, &["OK", "Cancel"]), + ("New Document", new_document::open, &["Create", "Close"]), + ("Find Font", crate::find_font::open, &["Done"]), + ]; + // The app window's smallest size. + let screen = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0)); + for (name, open, labels) in opens { + let tall = show_in(open, vec2(1280.0, 900.0), false); + assert!( + tall.window.height() > screen.height() || tall.window.width() > screen.width(), + "{name}: the dialog is larger than the small window ({:?})", + tall.window + ); + assert_eq!(tall.whole, [false; 2], "{name}: in a large window the dialog does not scroll as a whole"); + let shown = show_in(open, screen.size(), false); + assert!(screen.contains_rect(shown.window), "{name}: the dialog stays on the screen: {:?}", shown.window); + assert!(shown.whole[1], "{name}: the dialog scrolls as a whole"); + assert!(whole_bar(&shown).is_some(), "{name}: the window's bar is drawn: {:?}", bars(&shown, false, true)); + // The buttons can sit outside the part in view; each is in view at the top or scrolled to + // the end. + let scrolled = show_in(open, screen.size(), true); + let (top, end) = (buttons(&shown, screen, labels), buttons(&scrolled, screen, labels)); + for label in labels { + let seen = |found: &[(String, bool)]| found.iter().any(|(s, seen)| s == label && *seen); + assert!(seen(&top) || seen(&end), "{name}: {label} can be scrolled into view: {top:?} {end:?}"); + } + } +} + +#[test] +fn keyboard_shortcuts_keeps_its_scroll_under_import_shortcut_set() { + // Scrolled down in the smallest window, Keyboard Shortcuts is where it was left when Import + // Shortcut Set, opened over it, is canceled; closed and opened again, it starts at its top. + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, Default::default()); + let screen = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0)); + let mut time = 0.0; + // Draws 12 frames, the first with `events`; returns whether the heading can be seen. + let mut heading_seen = |app: &mut VectorcraftApp, events: Vec| { + let mut events = Some(events); + let mut seen = false; + for _ in 0..12 { + time += 1.0; + let input = + egui::RawInput { screen_rect: Some(screen), events: events.take().unwrap_or_default(), time: Some(time), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| show(app, ui.ctx())); + out.textures_delta.clear(); + let shown = Shown { shapes: out.shapes, window: screen, body: None, whole: [false; 2] }; + seen = buttons(&shown, screen, &["Keyboard Shortcuts"]).iter().any(|(_, seen)| *seen); + } + seen + }; + let wheel = |at: Pos2| { + let wheel = egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: vec2(0.0, -5000.0), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Unknown, + modifiers: egui::Modifiers::NONE, + }; + vec![egui::Event::PointerMoved(at), wheel] + }; + crate::shortcut_editor::open(&mut app); + assert!(heading_seen(&mut app, vec![]), "Keyboard Shortcuts opens at its top"); + // On the window's bar, inside its 20 pt margin. + let window = ctx.memory(|m| m.area_rect(egui::Id::unique("dialog-shortcuts"))).unwrap_or(screen); + assert!(!heading_seen(&mut app, wheel(egui::pos2(window.right() - 23.0, window.center().y))), "the wheel scrolls the heading away"); + let kys = "/Menus {\n /Acme\\ Copy { /Modifiers 11 /Key 902 }\n}\n"; + crate::io::open_bytes(&mut app, "Keys.kys", kys.as_bytes(), None).unwrap(); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(shortcut_import::KIND)); + heading_seen(&mut app, vec![]); + cancel(&mut app); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some("shortcuts"), "Cancel shows Keyboard Shortcuts again"); + assert!(!heading_seen(&mut app, vec![]), "shown again, Keyboard Shortcuts is where it was scrolled to"); + cancel(&mut app); + heading_seen(&mut app, vec![]); + crate::shortcut_editor::open(&mut app); + assert!(heading_seen(&mut app, vec![]), "opened again, Keyboard Shortcuts starts at its top"); +} + +/// Open Import Shortcut Set on a set of two shortcuts. +fn open_shortcut_import(app: &mut VectorcraftApp) { + let kys = "/Menus {\n /Acme\\ Copy { /Modifiers 11 /Key 902 }\n /Acme\\ Paste { /Modifiers 11 /Key 903 }\n}\n"; + crate::io::open_bytes(app, "Keys.kys", kys.as_bytes(), None).unwrap(); +} + +#[test] +fn a_window_that_fits_itself_but_is_too_wide_scrolls_sideways() { + // Import Shortcut Set sizes its lists from the window's height and is about 780 pt wide. An + // 800 by 600 pixel window at a UI scale of 125% is 640 by 480 pt. + let wide = show_in(open_shortcut_import, vec2(1280.0, 900.0), false); + let screen = Rect::from_min_size(Pos2::ZERO, vec2(640.0, 480.0)); + assert!(wide.window.width() > screen.width(), "Import Shortcut Set is wider than the window: {:?}", wide.window); + assert_eq!(wide.whole, [false; 2], "in a large window it does not scroll"); + let shown = show_in(open_shortcut_import, screen.size(), false); + assert!(screen.contains_rect(shown.window), "the dialog stays on the screen: {:?}", shown.window); + assert_eq!(shown.whole, [true, false], "it scrolls sideways only"); + let sideways: Vec = bars(&shown, true, true).into_iter().filter(|r| r.width() >= 0.5 * shown.window.width()).collect(); + assert!(!sideways.is_empty(), "its sideways bar is drawn: {:?}", bars(&shown, true, false)); +} + +#[test] +fn a_window_wider_than_the_screen_scrolls_sideways_to_its_right_edge() { + // In a window 70% as wide as the dialog, the dialog scrolls sideways, and scrolled to its right + // edge, the text drawn furthest right in a large window can be seen. + let opens: [(&str, Open); 3] = [ + ("Import Shortcut Set", open_shortcut_import), + ("Keyboard Shortcuts", crate::shortcut_editor::open), + ("Preferences", |app| crate::prefs_dialog::open(app, None)), + ]; + let mut wrong = vec![]; + for (name, open) in opens { + let wide = show_in(open, vec2(1600.0, 1000.0), false); + let Some((right, _)) = texts(&wide) + .into_iter() + .filter(|(_, r, _)| wide.window.contains_rect(*r)) + .map(|(s, r, _)| (s, r.right())) + .max_by(|a, b| a.1.total_cmp(&b.1)) + else { + wrong.push(format!("{name}: no text in the large window")); + continue; + }; + let screen = Rect::from_min_size(Pos2::ZERO, vec2((0.7 * wide.window.width()).round(), 1000.0)); + let shown = show_in(open, screen.size(), false); + let scrolled = show_in(open, screen.size(), true); + // Within 1 pt: a text's drawn box can reach a fraction of a point past the content's edge. + let seen = + |shown: &Shown| texts(shown).iter().any(|(s, r, clip)| *s == right && screen.contains_rect(*r) && clip.expand(1.0).contains_rect(*r)); + let sideways = bars(&shown, true, true).into_iter().any(|r| r.width() >= 0.5 * shown.window.width()); + if !screen.contains_rect(shown.window) || !shown.whole[0] || !sideways || seen(&shown) || !seen(&scrolled) { + let at = |shown: &Shown| texts(shown).into_iter().filter(|(s, ..)| *s == right).collect::>(); + wrong.push(format!( + "{name} in {:?}: window {:?}, scrolls {:?}, sideways bar {sideways}, {right:?} seen at first {} {:?}, scrolled {} {:?}, bars {:?}", + screen.size(), + shown.window, + shown.whole, + seen(&shown), + at(&shown), + seen(&scrolled), + at(&scrolled), + bars(&shown, true, true) + )); + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); +} + +/// Every text the dialog drew, with its rectangle and its clip. +fn texts(shown: &Shown) -> Vec<(String, Rect, Rect)> { + fn walk(s: &Shape, clip: Rect, out: &mut Vec<(String, Rect, Rect)>) { + match s { + Shape::Text(t) => out.push((t.galley.text().to_string(), t.visual_bounding_rect(), clip)), + Shape::Vec(v) => v.iter().for_each(|s| walk(s, clip, out)), + _ => {} + } + } + let mut out = vec![]; + shown.shapes.iter().for_each(|c| walk(&c.shape, c.clip_rect, &mut out)); + out +} + +#[test] +fn a_dialog_with_buttons_in_its_body_scrolls_them_with_the_body() { + // Check Spelling draws its buttons inside its body: in a window too short for it, the heading + // stays in view and the buttons scroll with the body. + let open: Open = |app| { + check_spelling::open(app).unwrap(); + }; + let tall = show_in(open, vec2(1280.0, 900.0), false); + let screen = Rect::from_min_size(Pos2::ZERO, vec2(1024.0, (0.6 * tall.window.height()).round())); + let shown = show_in(open, screen.size(), false); + let scrolled = show_in(open, screen.size(), true); + let seen = |shown: &Shown, label: &str| buttons(shown, screen, &[label]).iter().any(|(_, seen)| *seen); + assert!(screen.contains_rect(shown.window), "the dialog stays on the screen: {:?}", shown.window); + assert!(body_bar(&shown).is_some() && shown.whole == [false; 2], "only the body scrolls ({:?}, {:?})", shown.body, shown.whole); + assert!(seen(&shown, "Check Spelling") && seen(&scrolled, "Check Spelling"), "the heading stays in view"); + assert!(!seen(&shown, "Cancel") && seen(&scrolled, "Cancel"), "Cancel is out of view until the body is scrolled down"); +} diff --git a/crates/ui-egui/src/dialogs/text_import.rs b/crates/ui-egui/src/dialogs/text_import.rs index 99128cc321..f0fe62b40d 100644 --- a/crates/ui-egui/src/dialogs/text_import.rs +++ b/crates/ui-egui/src/dialogs/text_import.rs @@ -3,7 +3,7 @@ //! places it as area type (`file.place` with `text`) and remembers the options: the next text file //! starts from them, and is placed with them when Show Import Options is off. //! -//! Fields: `platform` (`windows` | `mac`), `characterSet` (`unicode` | `ansi`), +//! Fields: `platform` (`windows` | `mac`), `characterSet` (one of [`CHARACTER_SETS`]), //! `removeLineReturns`, `removeParagraphReturns`, `replaceSpaces` (on or off), `spaces` (how many //! spaces make a tab, 2–100), and `__params` (the `file.place` params naming the file). @@ -22,6 +22,21 @@ pub(super) const SPEC: DialogSpec = /// The label column of the Encoding rows. const LABEL: f32 = 104.0; +/// The Character Set choices: `file.place`'s `text.characterSet` value and the menu label. +const CHARACTER_SETS: [(&str, &str); 11] = [ + ("unicode", "Unicode"), + ("ansi", "ANSI"), + ("shiftJis", "Shift JIS"), + ("gb2312", "GB2312"), + ("chineseBig5", "Chinese Big 5"), + ("cyrillic", "Cyrillic"), + ("gb18030", "GB18030"), + ("greek", "Greek"), + ("turkish", "Turkish"), + ("baltic", "Baltic"), + ("centralEuropean", "Central European"), +]; + /// Is the file `p` names (`path` or `name`) a text file? pub fn is_text(p: &Value) -> bool { let name = p.get("path").or_else(|| p.get("name")).and_then(Value::as_str).unwrap_or_default(); @@ -41,7 +56,8 @@ pub fn open(app: &mut VectorcraftApp, params: &Value) -> Value { "__params": params, }); let last = &app.ui.text_import; - for (k, wanted) in [("platform", ["windows", "mac"]), ("characterSet", ["unicode", "ansi"])] { + let sets = CHARACTER_SETS.map(|(value, _)| value); + for (k, wanted) in [("platform", &["windows", "mac"][..]), ("characterSet", &sets[..])] { if let Some(v) = last.get(k).and_then(Value::as_str).filter(|v| wanted.contains(v)) { fields[k] = json!(v); } @@ -68,7 +84,7 @@ pub fn last_options(app: &VectorcraftApp) -> Value { fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { widgets::subheader(ui, tl!("Encoding")); form::choice(ui, d, "platform", tl!("Platform:"), (LABEL, 180.0), &[("windows", "Windows"), ("mac", "Mac")]); - form::choice(ui, d, "characterSet", tl!("Character Set:"), (LABEL, 180.0), &[("unicode", "Unicode"), ("ansi", "ANSI")]); + form::choice(ui, d, "characterSet", tl!("Character Set:"), (LABEL, 180.0), &CHARACTER_SETS); ui.add_space(10.0); widgets::subheader(ui, tl!("Line Breaks")); for (key, label) in @@ -166,6 +182,39 @@ mod tests { assert_eq!(st.history.undo.len(), 1); } + /// Every character set is a choice: one confirmed last comes back on the next text file and + /// decodes it, an unknown remembered value falls back to Unicode, and with Show Import Options + /// off the remembered set is the one the file is placed with. + #[test] + fn a_remembered_character_set_comes_back_and_places_the_file() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let file = json!({"name": "notes.txt", "dataBase64": vectorcraft_format::base64_encode(&[0x93, 0xFA, 0x96, 0x7B])}); + app.ui.text_import = json!({"characterSet": "shiftJis", "platform": "windows"}); + app.run("file.place", file.clone()).unwrap(); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.str("characterSet")).as_deref(), Some("shiftJis")); + assert!(frame(&mut app).contains("Shift JIS"), "the remembered set is shown"); + let r = super::super::confirm(&mut app).unwrap(); + let st = app.session.doc().unwrap(); + let n = st.doc.node(vectorcraft_engine::doc::NodeId(r["ids"][0].as_u64().unwrap())).unwrap(); + let NodeKind::Text(t) = &n.kind else { panic!("type") }; + assert_eq!(t.plain_text(), "日本"); + assert_eq!(last_options(&app)["characterSet"], "shiftJis", "remembered for Show Import Options off"); + app.ui.text_import = json!({"characterSet": "latin9"}); + app.run("file.place", file).unwrap(); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.str("characterSet")).as_deref(), Some("unicode")); + let values: Vec<&str> = CHARACTER_SETS.iter().map(|(v, _)| *v).collect(); + let labels: Vec<&str> = CHARACTER_SETS.iter().map(|(_, l)| *l).collect(); + assert_eq!( + values, + ["unicode", "ansi", "shiftJis", "gb2312", "chineseBig5", "cyrillic", "gb18030", "greek", "turkish", "baltic", "centralEuropean"] + ); + assert_eq!( + labels, + ["Unicode", "ANSI", "Shift JIS", "GB2312", "Chinese Big 5", "Cyrillic", "GB18030", "Greek", "Turkish", "Baltic", "Central European"] + ); + } + /// A text file dropped on a canvas is placed by the dialog's OK in the document it was dropped /// on, even when another document became active meanwhile. #[test] diff --git a/crates/ui-egui/src/dialogs/three_d_materials.rs b/crates/ui-egui/src/dialogs/three_d_materials.rs index 3091a00cac..39d3d1a8a3 100644 --- a/crates/ui-egui/src/dialogs/three_d_materials.rs +++ b/crates/ui-egui/src/dialogs/three_d_materials.rs @@ -1,6 +1,6 @@ //! The 3D and Materials panel's Materials tab: the document's Graphics (its symbols) as thumbnails, -//! Add as Single Graphic, and the graphics mapped onto the selected 3D object (its planar faces, or -//! Revolve's side) with their face, position, size and turn. Picking a thumbnail maps that graphic +//! Add as Single Graphic, and the graphics mapped onto the selected 3D object (its planar faces, +//! Extrude & Bevel's side, or Revolve's side) with their face, position, size and turn. Picking a thumbnail maps that graphic //! onto the selected objects (`threeD.mapGraphic`); art dropped on the thumbnails becomes a graphic //! (`threeD.addGraphic`). Editing a mapped graphic changes the effect's `graphics` parameter, which //! the panel sends as it sends every other setting. @@ -85,6 +85,15 @@ pub(crate) fn library(app: &VectorcraftApp, ui: &mut egui::Ui, apply: bool) -> O action } +/// The name of `face` in the interface. +fn face_label(face: PlanarFace) -> &'static str { + match face { + PlanarFace::Front => tl!("Front"), + PlanarFace::Back => tl!("Back"), + PlanarFace::Side => tl!("Side"), + } +} + /// The Materials tab of the 3D effect in `d.fields["__effect"]`: the Graphics list, then the /// graphics mapped onto the object, the selected one with its settings. Edits `d.fields`; a click /// in the list is left in [`ACTION`]. @@ -112,7 +121,7 @@ pub(crate) fn controls(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) } let mut index = d.fields.get(SELECTED).and_then(Value::as_u64).map_or(0, |i| i as usize).min(list.len() - 1); for (i, g) in list.iter().enumerate() { - let face = if g.face == PlanarFace::Back { tl!("Back") } else { tl!("Front") }; + let face = face_label(g.face); if ui.selectable_label(i == index, format!("{} · {face}", g.symbol)).clicked() { index = i; } @@ -121,15 +130,18 @@ pub(crate) fn controls(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) ui.add_space(6.0); let Some(g) = list.get(index).cloned() else { return }; let mut edited = g.clone(); - // A plane has one face, and Revolve's graphics go on its side. + // A plane has one face, and Revolve's graphics go on its side. Extrude & Bevel's graphics go on + // its front or back cap, or on its side (its walls and bevels). if effect != ROTATE && effect != REVOLVE { ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = 6.0; label(ui, tl!("Face")); - let labels = [tl!("Front"), tl!("Back")]; - let at = usize::from(g.face == PlanarFace::Back); - if let Some(k) = widgets::dropdown(ui, "three-d-graphic-face", labels[at], &labels, 120.0) { - edited.face = PlanarFace::ALL[k.min(1)]; + let labels = PlanarFace::ALL.map(face_label); + let at = PlanarFace::ALL.iter().position(|f| *f == g.face).unwrap_or(0); + if let Some(k) = widgets::dropdown(ui, "three-d-graphic-face", labels[at], &labels, 120.0) + && let Some(face) = PlanarFace::ALL.get(k) + { + edited.face = *face; } }); } diff --git a/crates/ui-egui/src/dialogs/tools.rs b/crates/ui-egui/src/dialogs/tools.rs index 6dbcfe28ce..5e7b0d4092 100644 --- a/crates/ui-egui/src/dialogs/tools.rs +++ b/crates/ui-egui/src/dialogs/tools.rs @@ -112,7 +112,7 @@ pub fn open_tool_dialog(app: &mut VectorcraftApp, kind: &str, p: Value) { "rotate" => json!({"angle": 0}), "reflect" => json!({"axis": "vertical", "angle": 90}), "scale" => json!({"sx": 100, "sy": 100, "uniform": true}), - "shear" => json!({"angle": 0, "axis": "horizontal"}), + "shear" => json!({"angle": 0, "axis": "horizontal", "axisAngle": 0}), _ => json!({}), }; if let (Some(b), Some(o)) = (base.as_object_mut(), p.as_object()) { diff --git a/crates/ui-egui/src/dialogs/transform.rs b/crates/ui-egui/src/dialogs/transform.rs index 4f576b561a..cf8c2e6b44 100644 --- a/crates/ui-egui/src/dialogs/transform.rs +++ b/crates/ui-egui/src/dialogs/transform.rs @@ -220,6 +220,7 @@ fn command(app: &VectorcraftApp, d: &Dialog) -> (&'static str, Value) { // The axis by name, or the angle it is at. "reflect" if d.str("axis") == "angle" => ("object.reflect", json!({"axis": d.f64("angle", 90.0)})), "reflect" => ("object.reflect", json!({"axis": d.fields.get("axis").cloned().unwrap_or(json!("vertical"))})), + "shear" if d.str("axis") == "angle" => ("object.shear", json!({"angle": d.f64("angle", 0.0), "axis": d.f64("axisAngle", 0.0)})), _ => ("object.shear", json!({"angle": d.f64("angle", 0.0), "axis": d.str("axis")})), }; params["copy"] = json!(d.bool("copy")); @@ -377,6 +378,54 @@ mod tests { } } + /// Shear's axis is Horizontal, Vertical or an angle: the Axis Angle field takes input only with + /// the Angle axis and keeps its value with the others, and OK sends that angle as the axis, + /// apart from the Shear Angle. + #[test] + fn shear_takes_an_axis_angle() { + use egui::accesskit::Role; + use egui_kittest::kittest::{NodeT, Queryable}; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 60, "height": 20})).unwrap(); + crate::menus::invoke(&mut app, "object.shear", json!({})); + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1100.0, 900.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !std::mem::replace(&mut fonts, true) { + crate::theme::install_fonts(ui.ctx()); + return; + } + crate::dialogs::show(app, ui.ctx()); + }, + app, + ); + h.run_steps(5); + let dimmed = + |h: &egui_kittest::Harness<'_, VectorcraftApp>| h.get_by_role_and_label(Role::TextInput, "Axis Angle").accesskit_node().is_disabled(); + assert!(dimmed(&h), "Horizontal leaves the Axis Angle off"); + // Along an axis at 90° the left and right sides slide, 45° moving the right one by the width; + // at 0° the top and bottom slide by the height. Each case is undone before the next. + for (axis, axis_angle, sent, size) in + [("angle", 90, json!(90.0), (60.0, 80.0)), ("angle", 0, json!(0.0), (80.0, 20.0)), ("vertical", 30, json!("vertical"), (60.0, 80.0))] + { + let d = h.state_mut().ui.dialog.as_mut().unwrap(); + d.fields.extend([("axis".to_string(), json!(axis)), ("axisAngle".to_string(), json!(axis_angle)), ("angle".to_string(), json!(45))]); + h.run_steps(2); + assert_eq!(dimmed(&h), axis != "angle", "{axis}"); + assert_eq!(h.state().ui.dialog.as_ref().unwrap().fields["axisAngle"], json!(axis_angle), "the field keeps its value"); + crate::dialogs::confirm(h.state_mut()).unwrap(); + let app = h.state(); + let (cmd, p) = app.session.journal.last().unwrap(); + assert_eq!((cmd.as_str(), &p["axis"], &p["angle"]), ("object.shear", &sent, &json!(45.0)), "{axis} {axis_angle}"); + let b = app.session.doc().unwrap().doc.layers[0].children().unwrap()[0].geometric_bounds().unwrap(); + assert_eq!((b.width().round(), b.height().round()), size, "{axis} {axis_angle}"); + h.state_mut().run("edit.undo", json!({})).unwrap(); + crate::menus::invoke(h.state_mut(), "object.shear", json!({})); + h.run_steps(2); + } + } + /// #1915: Move's Distance and Angle follow Horizontal and Vertical, and they follow them back. /// The angle is counter-clockwise on the page and Vertical is down = +, so 90° moves up. #[test] diff --git a/crates/ui-egui/src/dialogs/width_point.rs b/crates/ui-egui/src/dialogs/width_point.rs index afa27c2abf..b0881b9082 100644 --- a/crates/ui-egui/src/dialogs/width_point.rs +++ b/crates/ui-egui/src/dialogs/width_point.rs @@ -6,12 +6,22 @@ //! OK runs `stroke.widthPoint.set`; Delete removes an existing point (`stroke.widthPoint.remove`) //! or discards a prospective point without changing the document. //! -//! Fields: `id`, `index` (an existing width point, otherwise null), `t` (its place), `side1`, -//! `side2` (the left and right widths, points), `linked`, `adjustAdjoining`; Delete sets `discard: true` and confirms. +//! On either half of a discontinuous point the dialog shows both sets of side widths, Incoming +//! (before the point along the path) and Outgoing (after it), and Single Width Only keeps one of +//! them as a continuous point. OK sets both halves in one `stroke.widthPoint.set` (one undo step), +//! and Delete removes both halves. +//! +//! Fields: `id`, `index` (an existing width point, otherwise null; the incoming half of a +//! discontinuous point), `t` (its place), `side1`, `side2` (the left and right widths, points), +//! `linked`, `adjustAdjoining`; for a discontinuous point also `outIndex`, `outSide1`, `outSide2`, +//! `outLinked` (the outgoing half) and `single` (`""`, `"incoming"` or `"outgoing"`); Delete sets +//! `discard: true` and confirms. use egui::vec2; use serde_json::{Value, json}; +use vectorcraft_doc::Unit; use vectorcraft_engine::doc::NodeId; +use vectorcraft_engine::width_point_pair; use super::swatch_options::{grid, label}; use super::{DialogSpec, run_and_close}; @@ -31,9 +41,20 @@ fn point(app: &VectorcraftApp, id: u64, index: usize) -> Option<(f64, f64, f64)> st.profile.as_ref()?.points.get(index).map(|&(t, l, r)| (t, l * half, r * half)) } +/// The incoming and outgoing halves of the discontinuous point that width point `index` of `id` +/// belongs to, or none when it is a continuous point. The halves are paired by +/// [`width_point_pair`], as `stroke.widthPoint.set` pairs them, so either half finds the same pair. +fn halves(app: &VectorcraftApp, id: u64, index: usize) -> Option<(usize, usize)> { + let points = &app.session.active()?.doc.node(NodeId(id))?.appearance.stroke()?.profile.as_ref()?.points; + points.get(index)?; + let pair = |a: usize| width_point_pair(points, a).map(|b| (a, b)); + pair(index).or_else(|| index.checked_sub(1).and_then(pair)) +} + /// Open Width Point Edit for `index`, or a prospective point at fraction `t` without an index /// (`{id, index?, t?, adjustAdjoining?}`). Opening only samples the stroke: confirmation creates -/// the point. Adjoining adjustment defaults to false. +/// the point. Adjoining adjustment defaults to false. Either half of a discontinuous point opens +/// both. pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { let id = p.get("id").and_then(Value::as_u64).ok_or("give the path `id`")?; let doc = &app.session.active().ok_or("no document")?.doc; @@ -42,6 +63,8 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { Some(v) => Some(v.as_u64().and_then(|i| usize::try_from(i).ok()).ok_or("no such width point")?), None => None, }; + let pair = index.and_then(|i| halves(app, id, i)); + let index = pair.map_or(index, |(a, _)| Some(a)); let (t, l, r) = if let Some(index) = index { point(app, id, index).ok_or("no such width point")? } else { @@ -59,45 +82,86 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { (t, l, r) }; let adjust = p.get("adjustAdjoining").and_then(Value::as_bool).unwrap_or(false); - let fields = json!({"id": id, "index": index, "t": t, "side1": l, "side2": r, "linked": (l - r).abs() < 1e-9, "adjustAdjoining": adjust}); + let mut fields = json!({"id": id, "index": index, "t": t, "side1": l, "side2": r, "linked": (l - r).abs() < 1e-9, "adjustAdjoining": adjust}); + if let Some((_, out)) = pair { + let (_, l, r) = point(app, id, out).ok_or("no such width point")?; + for (key, value) in [ + ("outIndex", json!(out)), + ("outSide1", json!(l)), + ("outSide2", json!(r)), + ("outLinked", json!((l - r).abs() < 1e-9)), + ("single", json!("")), + ] { + fields[key] = value; + } + } app.ui.dialog = Some(Dialog::new(KIND, fields)); Ok(Value::Null) } -fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { - let unit = app.session.stroke_unit(); - let (s1, s2, linked) = (d.f64("side1", 0.0), d.f64("side2", 0.0), d.bool("linked")); - let mut sides = None; +/// Whether the dialog edits a discontinuous point. +fn paired(d: &Dialog) -> bool { + d.fields.get("outIndex").is_some_and(|v| !v.is_null()) +} + +/// One set of side widths: Side 1 with its link, Side 2 and Total Width, kept in the fields `keys` +/// (side 1, side 2, linked) and shown in the number fields `ids`. +fn sides(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit, keys: [&str; 3], ids: [&str; 3]) { + let [k1, k2, kl] = keys; + let (s1, s2, linked) = (d.f64(k1, 0.0), d.f64(k2, 0.0), d.bool(kl)); + let mut new = None; grid(ui, |ui| { label(ui, tl!("Side 1:")); ui.horizontal(|ui| { - if let Some(v) = widgets::num_field(ui, "wp-side1", Some(s1), unit, 90.0) { - sides = Some((v, if linked { v } else { s2 })); + if let Some(v) = widgets::num_field(ui, ids[0], Some(s1), unit, 90.0) { + new = Some((v, if linked { v } else { s2 })); } if widgets::icon_button(ui, if linked { "link" } else { "link-2-off" }, tl!("Keep both sides the same width"), linked, 22.0).clicked() { - d.fields.insert("linked".into(), json!(!linked)); + d.fields.insert(kl.into(), json!(!linked)); if !linked { - sides = Some((s1, s1)); + new = Some((s1, s1)); } } }); ui.end_row(); label(ui, tl!("Side 2:")); - if let Some(v) = widgets::num_field(ui, "wp-side2", Some(s2), unit, 90.0) { - sides = Some((if linked { v } else { s1 }, v)); + if let Some(v) = widgets::num_field(ui, ids[1], Some(s2), unit, 90.0) { + new = Some((if linked { v } else { s1 }, v)); } ui.end_row(); label(ui, tl!("Total Width:")); - if let Some(v) = widgets::num_field(ui, "wp-total", Some(s1 + s2), unit, 90.0) { + if let Some(v) = widgets::num_field(ui, ids[2], Some(s1 + s2), unit, 90.0) { // Both sides in proportion (equal halves from nothing). let k = if s1 + s2 > 1e-9 { v / (s1 + s2) } else { 0.0 }; - sides = Some(if k > 0.0 { (s1 * k, s2 * k) } else { (v / 2.0, v / 2.0) }); + new = Some(if k > 0.0 { (s1 * k, s2 * k) } else { (v / 2.0, v / 2.0) }); } ui.end_row(); }); - if let Some((a, b)) = sides { - d.fields.insert("side1".into(), json!(a.max(0.0))); - d.fields.insert("side2".into(), json!(b.max(0.0))); + if let Some((a, b)) = new { + d.fields.insert(k1.into(), json!(a.max(0.0))); + d.fields.insert(k2.into(), json!(b.max(0.0))); + } +} + +fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + let unit = app.session.stroke_unit(); + let incoming = (["side1", "side2", "linked"], ["wp-side1", "wp-side2", "wp-total"]); + if paired(d) { + widgets::section_header(ui, tl!("Incoming")); + ui.push_id("wp-incoming", |ui| sides(ui, d, unit, incoming.0, incoming.1)); + widgets::section_header(ui, tl!("Outgoing")); + ui.push_id("wp-outgoing", |ui| sides(ui, d, unit, ["outSide1", "outSide2", "outLinked"], ["wp-out-side1", "wp-out-side2", "wp-out-total"])); + widgets::section_header(ui, tl!("Single Width Only")); + ui.horizontal(|ui| { + let single = d.str("single"); + for (value, text) in [("", tl!("None")), ("incoming", tl!("Incoming")), ("outgoing", tl!("Outgoing"))] { + if widgets::radio(ui, text, single == value, true) { + d.fields.insert("single".into(), json!(value)); + } + } + }); + } else { + sides(ui, d, unit, incoming.0, incoming.1); } ui.add_space(4.0); ui.allocate_ui(vec2(ui.available_width(), 22.0), |ui| { @@ -110,16 +174,30 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let (id, index) = (d.fields.get("id").cloned().unwrap_or_default(), d.fields.get("index").cloned().unwrap_or_default()); + let out = d.fields.get("outIndex").filter(|_| paired(d)).cloned(); if d.bool("discard") { if index.is_null() { // Deleting a prospective point discards the dialog; no document point exists yet. app.ui.dialog = None; return Ok(Value::Null); } - return run_and_close(app, "stroke.widthPoint.remove", json!({"id": id, "index": index})); + let p = match out { + Some(out) => json!({"id": id, "indices": [index, out]}), + None => json!({"id": id, "index": index}), + }; + return run_and_close(app, "stroke.widthPoint.remove", p); } let (left, right) = (d.f64("side1", 0.0), d.f64("side2", 0.0)); - let p = json!({"id": id, "index": index, "t": d.f64("t", 0.0), "left": left, "right": right, "adjustAdjoining": d.bool("adjustAdjoining")}); + let mut p = json!({"id": id, "index": index, "t": d.f64("t", 0.0), "left": left, "right": right, "adjustAdjoining": d.bool("adjustAdjoining")}); + if let Some(out) = out { + p["outIndex"] = out; + p["outLeft"] = json!(d.f64("outSide1", 0.0)); + p["outRight"] = json!(d.f64("outSide2", 0.0)); + let single = d.str("single"); + if !single.is_empty() { + p["single"] = json!(single); + } + } run_and_close(app, "stroke.widthPoint.set", p) } diff --git a/crates/ui-egui/src/dialogs/width_point/tests.rs b/crates/ui-egui/src/dialogs/width_point/tests.rs index 4c5b972f12..bf32a6124f 100644 --- a/crates/ui-egui/src/dialogs/width_point/tests.rs +++ b/crates/ui-egui/src/dialogs/width_point/tests.rs @@ -400,3 +400,176 @@ fn new_width_point_checkbox_adjusts_adjoining_in_one_step() { fn new_width_point_checkbox_off_preserves_adjoining() { creation_adjoining_checkbox(false); } + +/// [`app`]'s line with a discontinuous point in the middle: 4 + 4 pt before it, 2 + 6 pt after it. +fn pair_app() -> (VectorcraftApp, u64) { + let (mut app, id) = app(); + app.run("stroke.widthProfile.set", json!({"ids": [id], "points": [[0, 1, 1], [0.5, 0.8, 0.8], [0.5, 0.4, 1.2], [1, 1, 1]]})).unwrap(); + app.session.doc_mut().unwrap().mark_saved(); + (app, id) +} + +fn assert_pair_fields(d: &Dialog) { + assert_eq!((d.fields["index"].clone(), d.fields["outIndex"].clone()), (json!(1), json!(2))); + assert_eq!((d.f64("side1", 0.0), d.f64("side2", 0.0), d.bool("linked")), (4.0, 4.0, true)); + assert_eq!((d.f64("outSide1", 0.0), d.f64("outSide2", 0.0), d.bool("outLinked")), (2.0, 6.0, false)); + assert_eq!(d.str("single"), ""); +} + +#[test] +fn either_half_of_a_discontinuous_point_shows_both_sets_of_side_widths() { + for index in [1, 2] { + let (mut app, id) = pair_app(); + app.run("ui.widthPointEdit", json!({"id": id, "index": index})).unwrap(); + assert_pair_fields(app.ui.dialog.as_ref().unwrap()); + let shown = frame(&mut app); + for s in ["Incoming", "Outgoing", "Single Width Only", "None", "Adjust Adjoining Width Points", "Delete"] { + assert!(shown.iter().any(|t| t == s), "{s} in {shown:?}"); + } + for s in ["Side 1:", "Side 2:", "Total Width:"] { + assert_eq!(shown.iter().filter(|t| *t == s).count(), 2, "{s} in each set: {shown:?}"); + } + } + // Double-clicking the point with the Width tool opens the same two sets. + let (mut app, _) = pair_app(); + let view = app.view_info(); + app.select_tool("width"); + crate::canvas::dispatch(&mut app, &PointerEvent::new(PointerKind::DoubleClick, 200.0, 150.0), view); + assert_pair_fields(app.ui.dialog.as_ref().expect("Width Point Edit opened")); + // A continuous point keeps one set. + let (mut app, id) = pair_app(); + app.run("ui.widthPointEdit", json!({"id": id, "index": 0})).unwrap(); + assert!(app.ui.dialog.as_ref().unwrap().fields.get("outIndex").is_none()); + let shown = frame(&mut app); + assert!(!shown.iter().any(|t| t == "Incoming" || t == "Outgoing"), "{shown:?}"); + assert_eq!(shown.iter().filter(|t| *t == "Side 1:").count(), 1); +} + +/// Three width points each within 1e-6 of the next, but the outer two farther apart: the halves +/// are paired as `stroke.widthPoint.set` pairs them, from the incoming half's place, whichever +/// of them is opened. The first two make one discontinuous point, and the third stays a +/// continuous point. +#[test] +fn points_in_a_chain_pair_as_the_engine_pairs_them() { + let chain = json!([[0, 1, 1], [0.5, 0.8, 0.8], [0.50000075, 0.4, 1.2], [0.5000015, 0.6, 0.6], [1, 1, 1]]); + for index in [1, 2] { + let (mut app, id) = app(); + app.run("stroke.widthProfile.set", json!({"ids": [id], "points": chain})).unwrap(); + app.run("ui.widthPointEdit", json!({"id": id, "index": index})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + assert_eq!((d.fields["index"].clone(), d.fields["outIndex"].clone()), (json!(1), json!(2)), "opened {index}"); + d.fields.insert("outSide1".into(), json!(1)); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none(), "opened {index}"); + assert_eq!(points(&app, id)[2], (0.50000075, 0.2, 1.2), "opened {index}"); + } + let (mut app, id) = app(); + app.run("stroke.widthProfile.set", json!({"ids": [id], "points": chain})).unwrap(); + app.run("ui.widthPointEdit", json!({"id": id, "index": 3})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + assert_eq!(d.fields["index"], json!(3)); + assert!(d.fields.get("outIndex").is_none()); + d.fields.insert("side1".into(), json!(1)); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(points(&app, id)[3], (0.5000015, 0.2, 0.6)); +} + +#[test] +fn ok_sets_both_halves_of_a_discontinuous_point_in_one_step() { + let (mut app, id) = pair_app(); + let before = app.session.doc().unwrap().doc.clone(); + let history = creation_history(&app); + // Cancel after edits changes nothing. + app.run("ui.widthPointEdit", json!({"id": id, "index": 2})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("outSide1".into(), json!(9)); + super::super::cancel(&mut app); + assert_eq!(app.session.doc().unwrap().doc, before); + assert_eq!(creation_history(&app), history); + app.run("ui.widthPointEdit", json!({"id": id, "index": 2})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + for (key, value) in [("side1", 6), ("side2", 2), ("outSide1", 1), ("outSide2", 3)] { + d.fields.insert(key.into(), json!(value)); + } + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(points(&app, id), vec![(0.0, 1.0, 1.0), (0.5, 1.2, 0.4), (0.5, 0.2, 0.6), (1.0, 1.0, 1.0)]); + assert_eq!(creation_history(&app), (history.0 + 1, 0, true)); + let after = app.session.doc().unwrap().doc.clone(); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.doc().unwrap().doc, before); + app.run("edit.redo", json!({})).unwrap(); + assert_eq!(app.session.doc().unwrap().doc, after); + // OK with nothing changed records no undo step. + app.run("ui.widthPointEdit", json!({"id": id, "index": 1})).unwrap(); + super::super::confirm(&mut app).unwrap(); + assert_eq!(creation_history(&app), (history.0 + 1, 0, true)); +} + +#[test] +fn delete_removes_both_halves_of_a_discontinuous_point() { + let (mut app, id) = pair_app(); + let before = app.session.doc().unwrap().doc.clone(); + let history = creation_history(&app); + app.run("ui.widthPointEdit", json!({"id": id, "index": 1})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("discard".into(), json!(true)); + super::super::confirm(&mut app).unwrap(); + assert_eq!(points(&app, id), vec![(0.0, 1.0, 1.0), (1.0, 1.0, 1.0)]); + assert_eq!(creation_history(&app).0, history.0 + 1); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.doc().unwrap().doc, before); +} + +/// Click the last visible text `label` in the dialog (a radio after a heading of the same name). +fn click_last(app: &mut VectorcraftApp, ctx: &egui::Context, label: &str) { + for _ in 0..4 { + creation_dialog_frame(app, ctx, vec![]); + } + let texts = creation_dialog_frame(app, ctx, vec![]); + let pos = texts.iter().rev().find(|(text, _)| text == label).unwrap_or_else(|| panic!("missing visible control {label}: {texts:?}")).1.center(); + for pressed in [true, false] { + let button = egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + creation_dialog_frame(app, ctx, vec![egui::Event::PointerMoved(pos), button]); + } + creation_dialog_frame(app, ctx, vec![]); +} + +#[test] +fn single_width_only_keeps_the_chosen_half_as_one_point() { + for (choice, kept) in [("Incoming", (0.8, 0.8)), ("Outgoing", (0.4, 1.2))] { + let (mut app, id) = pair_app(); + let before = app.session.doc().unwrap().doc.clone(); + let history = creation_history(&app); + app.run("ui.widthPointEdit", json!({"id": id, "index": 1})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, Default::default()); + click_last(&mut app, &ctx, choice); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("single"), choice.to_lowercase()); + click_last(&mut app, &ctx, "OK"); + assert!(app.ui.dialog.is_none()); + assert_eq!(points(&app, id), vec![(0.0, 1.0, 1.0), (0.5, kept.0, kept.1), (1.0, 1.0, 1.0)], "{choice}"); + assert_eq!(creation_history(&app), (history.0 + 1, 0, true)); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.doc().unwrap().doc, before); + } +} + +#[test] +fn a_compound_member_edits_both_halves_of_its_owners_point() { + let (mut app, line) = app(); + let second = app.run("shape.line", json!({"x1": 320, "y1": 50, "x2": 320, "y2": 250})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [line, second]})).unwrap(); + let owner = app.run("object.compoundPath.make", json!({})).unwrap()["id"].as_u64().unwrap(); + app.run("stroke.widthProfile.set", json!({"ids": [owner], "points": [[0, 1, 1], [0.5, 0.8, 0.8], [0.5, 0.4, 1.2], [1, 1, 1]]})).unwrap(); + app.run("ui.widthPointEdit", json!({"id": second, "index": 2})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + assert_eq!(d.fields["id"], json!(owner)); + d.fields.insert("adjustAdjoining".into(), json!(true)); + d.fields.insert("side1".into(), json!(8)); + d.fields.insert("outSide2".into(), json!(3)); + super::super::confirm(&mut app).unwrap(); + // The incoming change (Side 1 doubled) doubles the start's Side 1; the outgoing one (Side 2 + // halved) halves the end's Side 2. + assert_eq!(points(&app, owner), vec![(0.0, 2.0, 1.0), (0.5, 1.6, 0.8), (0.5, 0.4, 0.6), (1.0, 1.0, 0.5)]); +} diff --git a/crates/ui-egui/src/display_profile.rs b/crates/ui-egui/src/display_profile.rs index b3f10ab27e..a1acf8ebbe 100644 --- a/crates/ui-egui/src/display_profile.rs +++ b/crates/ui-egui/src/display_profile.rs @@ -78,6 +78,10 @@ struct State { transform: Option>, /// The bytes last reported, so a reading of the same profile builds nothing. reported: Option<(Option, Vec)>, + /// The desktop app reads the display's profile ([`DisplayProfile::attach_reader`]). + reader: bool, + /// Refresh Monitor Profile asked for a reading that hasn't started yet. + requested: bool, } impl Default for State { @@ -90,6 +94,8 @@ impl Default for State { reason: Some("this build doesn't read display profiles".into()), transform: None, reported: None, + reader: false, + requested: false, } } } @@ -116,6 +122,42 @@ impl DisplayProfile { } } + /// The desktop app reads the display's profile, so [`Self::request_read`] can ask it to. + pub fn attach_reader(&self) { + self.write().reader = true; + } + + /// Whether something reads the display's profile ([`Self::attach_reader`]). + pub(crate) fn has_reader(&self) -> bool { + self.read().reader + } + + /// Edit › Refresh Monitor Profile: asks the desktop app to read the display's profile again on + /// its next frame, without waiting for its intervals; while a reading runs, the request waits + /// for it to end. Refused while `enabled` (the preference) is off, and when nothing reads the + /// profile. Nothing is queued when it is refused. + pub fn request_read(&self, enabled: bool) -> Result<(), String> { + if !enabled { + return Err("turn on Use Monitor Profile for Canvas first".into()); + } + let mut s = self.write(); + if !s.reader { + return Err("this build doesn't read display profiles".into()); + } + s.requested = true; + Ok(()) + } + + /// Whether [`Self::request_read`] asked for a reading that hasn't started. + pub fn read_requested(&self) -> bool { + self.read().requested + } + + /// Takes the request [`Self::request_read`] made: whether there was one. + pub fn take_request(&self) -> bool { + self.read_requested() && std::mem::take(&mut self.write().requested) + } + /// Takes `reading` in. A profile is checked, and its conversion built, on the calling thread; /// a profile that can't be used leaves the canvas sRGB, with the reason in [`Self::status`]. /// The same profile reported again for the same display changes nothing. Returns whether the @@ -170,8 +212,9 @@ impl DisplayProfile { /// The status `ui.inspect` reports as `displayProfile`: the display, what was found /// (`profile`, `srgbProfile`, `system`, `none`, `pending` or `unsupported`), the profile's - /// description and where it was read from, whether the canvas is converted, why not, and - /// whether the system converts the window. + /// description and where it was read from, whether the canvas is converted, why not, whether + /// the system converts the window, and whether a reading [`Self::request_read`] asked for + /// hasn't started. pub fn status(&self, enabled: bool) -> Value { let s = self.read(); json!({ @@ -183,6 +226,7 @@ impl DisplayProfile { "applied": enabled && s.transform.is_some(), "reason": s.reason, "osManaged": s.kind == Kind::System, + "readRequested": s.requested, }) } @@ -535,6 +579,22 @@ pub(crate) mod tests { assert!(d.key(true) > key); } + #[test] + fn a_reading_is_requested_only_with_the_preference_on_and_a_reader() { + let d = DisplayProfile::default(); + assert_eq!(d.request_read(true).unwrap_err(), "this build doesn't read display profiles"); + d.attach_reader(); + assert_eq!(d.request_read(false).unwrap_err(), "turn on Use Monitor Profile for Canvas first"); + assert!(!d.read_requested() && !d.take_request(), "a refused request is not queued"); + d.request_read(true).unwrap(); + d.request_read(true).unwrap(); + assert_eq!(d.status(true)["readRequested"].as_bool(), Some(true)); + // Two requests before the reading starts make one reading. + assert!(d.take_request()); + assert!(!d.take_request()); + assert_eq!(d.status(true)["readRequested"].as_bool(), Some(false)); + } + #[test] fn a_profile_that_can_t_be_used_leaves_the_canvas_srgb_and_says_why() { let d = DisplayProfile::default(); diff --git a/crates/ui-egui/src/doc_windows/tests.rs b/crates/ui-egui/src/doc_windows/tests.rs index cde101a965..76ff46ff20 100644 --- a/crates/ui-egui/src/doc_windows/tests.rs +++ b/crates/ui-egui/src/doc_windows/tests.rs @@ -259,7 +259,7 @@ fn tile_brings_floating_documents_back_into_the_grid() { frame(&mut app, &ctx, vec![]); let docs: Vec = app.canvas.panes.last.iter().map(|(w, _)| w.0).collect(); assert_eq!(docs, [0, 1], "a floating document leaves the grid; the tabbed ones share it"); - assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": true, "panes": 3})); + assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": true, "panes": 3, "layout": "grid"})); frame(&mut app, &ctx, vec![]); let docs: Vec = app.canvas.panes.last.iter().map(|(w, _)| w.0).collect(); assert_eq!(docs, [0, 1, 2]); @@ -844,7 +844,7 @@ fn arrange_treats_each_view_as_a_window() { assert!(!enabled(&app, "window.arrange.tile") && !enabled(&app, "window.arrange.cascade"), "one window"); app.run("window.newWindow", json!({})).unwrap(); assert!(enabled(&app, "window.arrange.tile") && enabled(&app, "window.arrange.cascade"), "two views of one document"); - assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": true, "panes": 2})); + assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": true, "panes": 2, "layout": "grid"})); app.run("window.arrange.cascade", json!({})).unwrap(); frame(&mut app, &ctx, vec![]); let uid = app.session.documents()[0].uid; diff --git a/crates/ui-egui/src/edit_toolbar.rs b/crates/ui-egui/src/edit_toolbar.rs index d58351ac21..51155e710f 100644 --- a/crates/ui-egui/src/edit_toolbar.rs +++ b/crates/ui-egui/src/edit_toolbar.rs @@ -532,7 +532,7 @@ pub(crate) fn drawer(app: &mut VectorcraftApp, ctx: &egui::Context) { let inner = ui.available_width() - 10.0; for (cat, gs) in groups() { ui.add_space(6.0); - ui.label(egui::RichText::new(format!("{}:", tl!(cat))).size(12.0).color(t.text_strong)); + ui.label(egui::RichText::new(crate::i18n::colon(tl!(cat))).size(12.0).color(t.text_strong)); ui.add_space(4.0); for g in gs { // A flyout group: its tools framed together, as one toolbar button holds them. diff --git a/crates/ui-egui/src/edit_toolbar/tests.rs b/crates/ui-egui/src/edit_toolbar/tests.rs index 8983199324..17d605936a 100644 --- a/crates/ui-egui/src/edit_toolbar/tests.rs +++ b/crates/ui-egui/src/edit_toolbar/tests.rs @@ -207,7 +207,7 @@ fn the_commands_add_move_remove_and_reset_tools() { assert_eq!(slots(&app)[2], ["slice"]); let ellipse = slot_of(&app, "ellipse").unwrap(); app.run("toolbar.addTool", json!({"tool": "star", "slot": ellipse, "place": "group"})).unwrap(); - assert_eq!(slots(&app)[ellipse], ["ellipse", "star"]); + assert_eq!(slots(&app)[ellipse], ["ellipse", "circle", "star"]); assert!(!slots(&app)[slot_of(&app, "rectangle").unwrap()].contains(&"star")); // Onto its own group: nothing changes. let before = slots(&app); @@ -217,7 +217,7 @@ fn the_commands_add_move_remove_and_reset_tools() { assert_eq!(crate::toolbar::slots(&app)[0].0, Some("Select")); // Out: one tool, or its whole group; an emptied slot goes. app.run("toolbar.removeTool", json!({"tool": "ellipse"})).unwrap(); - assert_eq!(slots(&app)[ellipse], ["star"]); + assert_eq!(slots(&app)[ellipse], ["circle", "star"]); app.run("toolbar.removeTool", json!({"tool": "addAnchor", "group": true})).unwrap(); assert!(slot_of(&app, "pen").is_none() && slot_of(&app, "addAnchor").is_none()); // Bad params change nothing. @@ -354,6 +354,25 @@ fn tools_in_the_toolbar_are_dimmed_in_the_drawer() { assert_eq!(cell_at(&shown, drawer, "Artboard Tool").1, dim); } +/// The drawer's headings end in the UI language's colon: in French a no-break space and a colon +/// (#7991), in English a plain colon. +#[test] +fn drawer_headings_use_the_language_colon() { + let mut app = app(); + let ctx = ctx(); + app.run("window.editToolbar", json!({"open": true})).unwrap(); + for (code, colon) in [("fr", "\u{a0}:"), ("en", ":")] { + let lang = crate::i18n::Lang::from_code(code).unwrap(); + crate::i18n::set_current(lang); + frame(&mut app, &ctx, 0.0, vec![]); + let shown = frame(&mut app, &ctx, 0.1, vec![]); + crate::i18n::set_current(crate::i18n::Lang::EN); + let drawer = drawer_rect(&ctx).unwrap(); + let want = format!("{}{colon}", crate::i18n::tr(lang, "Select")); + assert!(shown.iter().any(|(s, p, _)| s.trim() == want && drawer.contains(*p)), "{code}: {want:?}"); + } +} + /// #1018: tools drag from the drawer onto the toolbar (between two tools, or onto one to join /// its group), from the toolbar into the drawer, and within the toolbar, only while the drawer /// is open. @@ -379,7 +398,7 @@ fn tools_drag_between_the_drawer_and_the_toolbar() { let drawer = drawer_rect(&ctx).unwrap(); let (slice, _) = cell_at(&shown, drawer, "Slice Tool"); drag(&mut app, &ctx, 2.0, slice, tools[ellipse].center()); - assert_eq!(slots(&app)[ellipse], ["ellipse", "slice"]); + assert_eq!(slots(&app)[ellipse], ["ellipse", "circle", "slice"]); // A dimmed tool (in the toolbar already) doesn't drag. let before = slots(&app); let shown = frame(&mut app, &ctx, 2.9, vec![]); @@ -578,6 +597,17 @@ fn the_add_tool_menu_fills_a_new_toolbar_without_a_drag() { click(&mut app, &ctx, 40.0, items(&shown, "Lasso Tool")[0].0); assert_eq!(mine(&app), [["magicWand"]]); assert_eq!(slots(&app), shipped); + // In French the menu's headings end in a no-break space and a colon (#7991). + open(&mut app, 49.0); + let fr = crate::i18n::Lang::from_code("fr").unwrap(); + crate::i18n::set_current(fr); + frame(&mut app, &ctx, 49.7, vec![]); + let french = frame(&mut app, &ctx, 49.8, vec![]); + crate::i18n::set_current(crate::i18n::Lang::EN); + for heading in ["Remove Tool", "Select"] { + let want = format!("{}\u{a0}:", crate::i18n::tr(fr, heading)); + assert_eq!(items(&french, &want).len(), 1, "{want:?}"); + } } /// New Toolbar… in the drawer's menu opens the New Toolbar dialog, which asks for a name. diff --git a/crates/ui-egui/src/find_font.rs b/crates/ui-egui/src/find_font.rs index 6cffc344d1..0ee21574fb 100644 --- a/crates/ui-egui/src/find_font.rs +++ b/crates/ui-egui/src/find_font.rs @@ -4,10 +4,13 @@ //! missing fonts' files, in the Missing Fonts dialog: `ui.findFontsInFolder`). Find In limits Find //! to the active artboard or the selected layers. +use std::sync::Arc; + use egui::Ui; use serde_json::{Value, json}; use crate::VectorcraftApp; +use crate::caches::{FindFontCache, FontsKey}; use crate::state::Dialog; use crate::theme::Tokens; use crate::widgets; @@ -20,7 +23,7 @@ pub fn open(app: &mut VectorcraftApp) { /// Open the dialog on the first font the document misses, to replace it (Missing Fonts' Find /// Fonts). pub fn open_on_missing(app: &mut VectorcraftApp) { - let first = fonts(app).iter().position(|f| matches!(f["status"].as_str(), Some("missing" | "substitute"))); + let first = document_fonts(app, false).0.iter().position(|f| matches!(f["status"].as_str(), Some("missing" | "substitute"))); open_at(app, first.unwrap_or(0)); } @@ -28,7 +31,7 @@ pub fn open_on_missing(app: &mut VectorcraftApp) { /// System's font ([`system_family`]) to change to, and the last Find In choice (Document at first). fn open_at(app: &mut VectorcraftApp, selected: usize) { let find_in = FIND_IN.iter().find(|f| **f == app.ui.find_font_in).copied().unwrap_or("document"); - let used = fonts(app); + let (used, _) = document_fonts(app, false); let source = "system"; let rows = replacement_rows(app, source, &used); let family = system_family(); @@ -252,6 +255,30 @@ fn fonts(app: &mut VectorcraftApp) -> Vec { app.session.execute("text.fonts", &json!({})).ok().and_then(|v| v.as_array().cloned()).unwrap_or_default() } +/// The active document's fonts ([`fonts`]) and, when `missing` is asked for, whether it misses a +/// font ([`vectorcraft_engine::cmd::fontfiles::missing_fonts`]; `false` when it is not asked +/// for). Both are kept in [`crate::CanvasCache::find_font`] and worked out again only for another +/// document, another version of its content or another font generation. No document: no fonts. +fn document_fonts(app: &mut VectorcraftApp, missing: bool) -> (Arc>, bool) { + let Some(st) = app.session.active() else { return (Arc::default(), false) }; + // The generation is read first: fonts loaded while the answers are worked out leave the entry + // under the older generation, so the next frame works them out again. + let key = FontsKey { uid: st.uid, doc: Arc::downgrade(&st.doc), generation: vectorcraft_text::FontDb::global().generation() }; + if app.canvas.find_font.as_ref().is_none_or(|c| c.key != key) { + let fonts = Arc::new(fonts(app)); + app.canvas.find_font = Some(FindFontCache { key, fonts, missing: None }); + } + if missing + && let Some(c) = app.canvas.find_font.as_mut() + && c.missing.is_none() + && let Some(st) = app.session.active() + { + c.missing = Some(!vectorcraft_engine::cmd::fontfiles::missing_fonts(&st.doc).is_empty()); + } + let c = app.canvas.find_font.as_ref(); + (c.map(|c| c.fonts.clone()).unwrap_or_default(), missing && c.and_then(|c| c.missing).unwrap_or(false)) +} + pub fn confirm(app: &mut VectorcraftApp) -> Result { if let Some(ctx) = app.ui_ctx.clone() { clear_search(&ctx); @@ -279,10 +306,9 @@ fn change(app: &mut VectorcraftApp, d: &Dialog, from: &Value, all: bool) -> Resu pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let Some(mut d) = app.ui.dialog.clone() else { return }; let t = Tokens::get(ctx); - let list = fonts(app); // Find in Folder… shows when the document misses fonts, fonts used only in its symbols included. - let offer_folder = crate::picks::can(app, &crate::picks::PickRequest::Folder) - && app.session.active().is_some_and(|st| !vectorcraft_engine::cmd::fontfiles::missing_fonts(&st.doc).is_empty()); + let can_pick = crate::picks::can(app, &crate::picks::PickRequest::Folder); + let (list, offer_folder) = document_fonts(app, can_pick); let mut close = false; let mut find_in_folder = false; let mut act: Option<&str> = None; @@ -416,7 +442,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { match run_button(app, &d, a, from) { // The rows are a snapshot: the document's fonts and the recent fonts have moved on. Ok(_) if a != "find" => { - let used = fonts(app); + let (used, _) = document_fonts(app, false); d.fields.insert("rows".into(), rows_json(&replacement_rows(app, &d.str("replaceFrom"), &used))); } Ok(_) => {} @@ -1421,4 +1447,231 @@ mod tests { let (note, color) = font_note(&row("exact", 2)); assert!(note.contains("2 characters") && color.is_some()); } + + /// The font list the dialog keeps for the active document. + fn kept_list(app: &VectorcraftApp) -> Arc> { + app.canvas.find_font.as_ref().expect("the dialog kept the document's fonts").fonts.clone() + } + + /// The kept list and Find in Folder… are what `text.fonts` and `missing_fonts` give now. + fn assert_current(app: &mut VectorcraftApp, shown: &str, why: &str) { + let listed = fonts(app); + assert_eq!(*kept_list(app), listed, "{why}: the list"); + let missing = app.session.active().is_some_and(|st| !vectorcraft_engine::cmd::fontfiles::missing_fonts(&st.doc).is_empty()); + let picks = crate::picks::can(app, &crate::picks::PickRequest::Folder); + assert_eq!(shown.contains("Find in Folder…"), picks && missing, "{why}: Find in Folder… {shown}"); + } + + /// A document set in a missing family and in Inter, with a folder picker. + fn missing_font_document() -> VectorcraftApp { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + for (y, font) in [(20, "Missing Family"), (40, "Inter")] { + app.session.execute("text.create", &json!({"x": 10, "y": y, "text": "Hi", "font": font})).unwrap(); + } + app.services.pick_folder = Some(Box::new(|| None)); + app + } + + /// Frames that change nothing in the document, a new selection included, keep the font list + /// and the missing-font answer worked out on the first; the answer is worked out only once a + /// folder picker is there. + #[test] + fn the_font_list_is_worked_out_once_per_document_version() { + let mut app = missing_font_document(); + let picker = app.services.pick_folder.take(); + open(&mut app); + assert!(kept_over_frames(&mut app, "no folder picker"), "frames of one document version keep its list"); + assert_eq!(app.canvas.find_font.as_ref().and_then(|c| c.missing), None, "no picker: the document is not searched for missing fonts"); + app.services.pick_folder = picker; + assert!(kept_over_frames(&mut app, "a folder picker"), "a picker alone keeps the list"); + assert_eq!(app.canvas.find_font.as_ref().and_then(|c| c.missing), Some(true)); + app.run("select.all", json!({})).unwrap(); + assert!(kept_over_frames(&mut app, "a new selection"), "a new selection keeps the list"); + } + + /// Draws frames of the dialog and tells whether they kept the list kept before them. Another + /// test thread that changes the available fonts meanwhile makes the dialog work the list out + /// again, so the frames are drawn again until the fonts stay as they are. + fn kept_over_frames(app: &mut VectorcraftApp, why: &str) -> bool { + for _ in 0..20 { + // The generation the kept list was worked out under: the database's generation only + // counts up, so the same one after the frames means no fonts changed in between. + let before = kept_list(app); + let generation = app.canvas.find_font.as_ref().map(|c| c.key.generation); + let shown = crate::tests_labels::painted_text(app, |app, ui| show(app, ui.ctx())); + assert_current(app, &shown, why); + if Some(vectorcraft_text::FontDb::global().generation()) == generation { + return Arc::ptr_eq(&before, &kept_list(app)); + } + } + panic!("{why}: the available fonts kept changing") + } + + /// An edit, its undo and a Change All each give the list of the document as it is then. + #[test] + fn an_edit_works_the_font_list_out_again() { + let mut app = missing_font_document(); + open(&mut app); + crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + let first = kept_list(&app); + app.run("text.replaceFont", json!({"from": {"family": "Missing Family"}, "to": {"family": "Inter"}})).unwrap(); + let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + assert_current(&mut app, &shown, "after the replacement"); + assert!(!shown.contains("Find in Folder…"), "nothing is missing: {shown}"); + assert_eq!(kept_list(&app).len(), 1, "{:?}", kept_list(&app)); + app.run("edit.undo", json!({})).unwrap(); + let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + assert_current(&mut app, &shown, "after the undo"); + assert_eq!(*kept_list(&app), *first, "the undo brings back the first list"); + let mut d = app.ui.dialog.clone().unwrap(); + d.fields.insert("family".into(), json!("Source Serif 4")); + d.fields.insert("style".into(), json!("")); + let from = first.iter().find(|f| f["family"] == "Inter").unwrap().clone(); + change(&mut app, &d, &from, true).unwrap(); + let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + assert_current(&mut app, &shown, "after Change All"); + assert!(kept_list(&app).iter().any(|f| f["family"] == "Source Serif 4"), "{:?}", kept_list(&app)); + } + + /// Fonts that become available, a composite font defined among them, give the list and the + /// missing-font answer as they are with those fonts. + #[test] + fn other_available_fonts_work_the_font_list_out_again() { + const FAMILY: &str = "Find Font Kept List CF"; + let mut app = missing_font_document(); + app.session.execute("text.create", &json!({"x": 10, "y": 60, "text": "Ab12", "font": FAMILY})).unwrap(); + open(&mut app); + crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + // The same document under another generation of the font database: what is kept for it no + // longer counts. + let entry = app.canvas.find_font.as_mut().unwrap(); + entry.key.generation = u64::MAX; + entry.fonts = Arc::default(); + entry.missing = Some(false); + let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + assert_current(&mut app, &shown, "another font generation"); + let row = |app: &VectorcraftApp| kept_list(app).iter().find(|f| f["family"] == FAMILY).cloned().unwrap(); + assert_eq!(row(&app)["status"], "missing"); + let generation = vectorcraft_text::FontDb::global().generation(); + let parts = json!({"name": FAMILY, "parts": {"kanji": {"font": "Source Sans 3"}, "roman": {"font": "JetBrains Mono"}, "numerals": {"font": "Inter"}}}); + app.run("type.compositeFonts.set", json!({"fonts": [parts]})).unwrap(); + assert_ne!(vectorcraft_text::FontDb::global().generation(), generation, "defining a composite font is a new generation"); + let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + assert_current(&mut app, &shown, "the composite font defined"); + assert_eq!(row(&app)["status"], "exact"); + app.run("type.compositeFonts.set", json!({"fonts": []})).unwrap(); + let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + assert_current(&mut app, &shown, "the composite font taken out"); + assert_eq!(row(&app)["status"], "missing"); + } + + /// Another document in front, and pattern editing entered and canceled, each give the list of + /// the document in front as it is then. + #[test] + fn the_font_list_follows_the_document_in_front() { + let mut app = missing_font_document(); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let id = app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi", "font": "Source Serif 4"})).unwrap()["id"].clone(); + app.services.pick_folder = Some(Box::new(|| None)); + open(&mut app); + let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + assert_current(&mut app, &shown, "the second document"); + app.session.set_active(0); + let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + assert_current(&mut app, &shown, "the first document"); + assert!(shown.contains("Find in Folder…"), "{shown}"); + app.session.set_active(1); + app.run("select.set", json!({"ids": [id]})).unwrap(); + app.run("object.pattern.make", json!({"name": "Kept List"})).unwrap(); + assert!(app.session.active().unwrap().doc.pattern_edit.is_some(), "pattern editing"); + let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + assert_current(&mut app, &shown, "pattern editing"); + app.run("object.pattern.cancel", json!({})).unwrap(); + let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + assert_current(&mut app, &shown, "pattern editing canceled"); + } + + /// CPU time of this thread in nanoseconds where the system reports it (Linux), else `None`. + fn thread_cpu_ns() -> Option { + std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok() + } + + /// Time the font list and the missing-font answer a Find Font frame reads, for a document of + /// 2,000 point-type objects of 50 characters each and one of 20, set in five installed faces + /// and a missing family, with a folder picker: worked out on every frame as `text.fonts` and + /// `missing_fonts` (each frame before they were kept), on the first frame of a document version + /// ([`document_fonts`] with nothing kept) and on later frames. Per run, the large document + /// draws 120 frames and the small one 12,000 (so the thread's CPU clock, which advances in + /// steps of a few milliseconds, sees them), and later frames number 1,000,000; the sides + /// alternate, and the median time per frame of 7 runs is printed. + /// Run with `cargo test --release -p vectorcraft-ui-egui --lib find_font_list_timing -- --ignored --nocapture`. + #[test] + #[ignore = "manual timing probe; performance depends on machine load"] + fn find_font_list_timing() { + const KEPT: u32 = 1_000_000; + const FACES: [(&str, &str); 6] = [ + ("Inter", "Regular"), + ("Inter", "Medium"), + ("Source Sans 3", "Bold"), + ("Source Serif 4", "Regular"), + ("JetBrains Mono", "Regular"), + ("Missing Family", "Regular"), + ]; + for (objects, frames) in [(2_000, 120), (20, 12_000)] { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 2000, "height": 2000})).unwrap(); + for i in 0..objects { + let (family, style) = FACES[i % FACES.len()]; + let text: String = (0..50).map(|c| char::from(b'a' + ((i + c) % 26) as u8)).collect(); + let (x, y) = ((i % 20 * 90) as f64, (i / 20 * 18) as f64 + 20.0); + app.session.execute("text.create", &json!({"x": x, "y": y, "text": text, "font": family, "style": style})).unwrap(); + } + app.services.pick_folder = Some(Box::new(|| None)); + let every_frame = |app: &mut VectorcraftApp| { + let list = fonts(app); + let offer = crate::picks::can(app, &crate::picks::PickRequest::Folder) + && app.session.active().is_some_and(|st| !vectorcraft_engine::cmd::fontfiles::missing_fonts(&st.doc).is_empty()); + (list, offer) + }; + let expected = every_frame(&mut app); + assert!(expected.1 && expected.0.len() == FACES.len(), "{expected:?}"); + let kept = document_fonts(&mut app, true); + assert_eq!((kept.0.to_vec(), kept.1), expected, "the kept answers are the ones worked out every frame"); + // Each side's answers for one frame: the number of fonts listed and Find in Folder…. + let time = |app: &mut VectorcraftApp, frames: u32, f: &mut dyn FnMut(&mut VectorcraftApp) -> (usize, bool)| { + let (cpu, wall) = (thread_cpu_ns(), std::time::Instant::now()); + for _ in 0..frames { + assert_eq!(f(app), (FACES.len(), true)); + } + let ns = thread_cpu_ns().zip(cpu).map_or_else(|| wall.elapsed().as_nanos(), |(b, a)| b - a); + ns as f64 / f64::from(frames) / 1000.0 + }; + let (mut full, mut first, mut later) = (vec![], vec![], vec![]); + for _ in 0..7 { + full.push(time(&mut app, frames, &mut |app| { + let (list, offer) = every_frame(app); + (list.len(), offer) + })); + first.push(time(&mut app, frames, &mut |app| { + app.canvas.find_font = None; + let (list, offer) = document_fonts(app, true); + (list.len(), offer) + })); + later.push(time(&mut app, KEPT, &mut |app| { + let (list, offer) = document_fonts(app, true); + (list.len(), offer) + })); + } + let median = |v: &mut Vec| { + v.sort_by(f64::total_cmp); + v[v.len() / 2] + }; + let clock = if thread_cpu_ns().is_some() { "thread CPU time" } else { "wall-clock time" }; + eprintln!("{objects} text objects of 50 characters; {clock} per frame, median of 7 runs"); + eprintln!("worked out every frame ({frames} frames a run): {:>12.3} us {full:.3?}", median(&mut full)); + eprintln!("first frame of a version ({frames} a run): {:>12.3} us {first:.3?}", median(&mut first)); + eprintln!("later frames of the version ({KEPT} a run): {:>12.4} us {later:.4?}", median(&mut later)); + } + } } diff --git a/crates/ui-egui/src/font_menu.rs b/crates/ui-egui/src/font_menu.rs index d5368d1fa4..855bc3a3f4 100644 --- a/crates/ui-egui/src/font_menu.rs +++ b/crates/ui-egui/src/font_menu.rs @@ -13,9 +13,12 @@ //! they look to it ([`vectorcraft_text::FontDb::similar_families`]), that family first and without the Recent //! Fonts section, until the ≈ chip under the filters clears it or the menu closes. The Font //! Technology filter's Variable lists only variable font families. Preferences › Type › Enable -//! in-menu font previews and Font Preview Size turn the samples off or size the rows. The menu lays -//! out its filters on the same five rows wherever it opens. However narrow its field, it opens at -//! least wide enough for those rows and for a family name up to 220 points wide with its sample +//! in-menu font previews and Font Preview Size turn the samples off or size the rows. While the +//! samples are shown, a row under the filters sets Font Preview Size to Small, Medium or Large +//! ([`apply_preview_size`]), which sizes the rows of every font menu, and the list stays on the +//! rows it showed. The menu lays out its filters on the same five rows wherever it opens, with the +//! size row under them while the samples are shown. However narrow its field, it opens at least +//! wide enough for those rows and for a family name up to 220 points wide with its sample //! beside it, up to 60% of the window; each sample fills its row's height. Recently used families //! appear first, in the order they were last applied, within the same search and filters as the //! remaining families. In the Character and Properties panels and the Control bar, @@ -185,11 +188,7 @@ impl Default for MenuLook<'static> { impl<'a> MenuLook<'a> { pub fn of(app: &'a VectorcraftApp) -> Self { - let row = match app.session.prefs.font_preview_size.as_str() { - "small" => 20.0, - "large" => 32.0, - _ => ROW, - }; + let row = preview_row(&app.session.prefs.font_preview_size); Self { samples: app.session.prefs.font_preview, on_white: app.session.prefs.font_samples_on_white, @@ -211,6 +210,22 @@ impl<'a> MenuLook<'a> { /// Height of a row, in points (Font Preview Size: Medium). const ROW: f32 = 24.0; +/// Font Preview Size's values (Preferences › Type), each with the row height it gives. +const PREVIEW_SIZES: [(&str, f32); 3] = [("small", 20.0), ("medium", ROW), ("large", 32.0)]; + +/// The row height of Font Preview Size `size`: Medium's for a value it does not have. +fn preview_row(size: &str) -> f32 { + PREVIEW_SIZES.iter().find(|(key, _)| *key == size).map_or(ROW, |(_, row)| *row) +} + +/// The label of Font Preview Size `size`, as Preferences names it. +fn preview_size_label(size: &str) -> &'static str { + match size { + "small" => tl!("Small"), + "large" => tl!("Large"), + _ => tl!("Medium"), + } +} /// Width of the star at the end of a family's row. const STAR: f32 = 18.0; /// Width of the Show Similar Fonts button before the star. @@ -453,6 +468,9 @@ struct MenuState { header: f32, /// The width of the widest row of filters without wrapping, last frame. filters: f32, + /// The rows' height last frame, and how far down the list its view began, in rows. At a new + /// height (Font Preview Size) the list scrolls back to the same row. + scrolled: Option<(f32, f32)>, /// The families the wheel steps through, listed at its first notch over the closed field and /// kept for that text selection while the pointer stays on it: each step makes its family a recent one, which would /// otherwise move it in the order. The Document filter's families are kept the same way: a @@ -500,10 +518,10 @@ impl Filters { /// The families the type in `doc` is set in, lowercase and by the name the menu lists them under /// ([`vectorcraft_text::FontDb::canonical`]): the runs of every text object in the layers, symbols, -/// patterns and graph designs, hidden, locked and masked ones included, with a composite font named -/// as such. A pattern being edited is read from its editing layer only. Each run's family is looked -/// up with its style, so a family and style split from a PostScript name (`Honoka`, `Mincho`) find -/// the installed font of that name. Styles no type uses are left out. +/// patterns, graph designs and stored scatter brushes, hidden, locked and masked ones included, with +/// a composite font named as such. A pattern being edited is read from its editing layer only. Each +/// run's family is looked up with its style, so a family and style split from a PostScript name +/// (`Honoka`, `Mincho`) find the installed font of that name. Styles no type uses are left out. fn document_families(db: &vectorcraft_text::FontDb, doc: &vectorcraft_doc::Document) -> HashSet { // Each family and style once, so a document with many runs in a few fonts looks each one up // once. @@ -531,6 +549,14 @@ fn document_families(db: &vectorcraft_text::FontDb, doc: &vectorcraft_doc::Docum for n in doc.layers.iter().map(|l| &**l).chain(doc.symbols.iter().map(|s| &*s.art)).chain(patterns).chain(designs) { vectorcraft_doc::swatches::walk_with_masks(n, &mut add); } + // A scatter brush draws copies of its art's type along a stroke; art and pattern brushes drop + // type when they bend their art. Malformed library entries are skipped. + let brushes = doc.unknown.get(vectorcraft_brush::DOC_KEY).map(vectorcraft_brush::parse_library).unwrap_or_default(); + for b in &brushes { + if let vectorcraft_brush::BrushKind::Scatter(s) = &b.kind { + vectorcraft_doc::swatches::walk_with_masks(&s.art, &mut add); + } + } named.iter().flat_map(|(f, styles)| styles.iter().map(move |s| db.canonical(f, s).0.to_lowercase())).collect() } @@ -1307,7 +1333,7 @@ fn header<'s>(ui: &mut Ui, db: &'s vectorcraft_text::FontDb, state_id: egui::Id, ui.memory_mut(|m| m.request_focus(field.with("edit"))); } let query = widgets::search_field(ui, field, tl!("Search")).to_lowercase(); - let refilter = filters(ui, st, &t, look.document.is_some()); + let refilter = filters(ui, st, &t, look.document.is_some(), look.samples.then_some(look.row)); let added = added_families(db, st, look); // On the system clock, the list is drawn again when a family's 30 days end. if let (Some(at), None) = (added.as_ref().and_then(|a| a.recheck_at), look.clock) @@ -1440,9 +1466,11 @@ fn filter_rows() -> [Vec; 5] { } /// The filters on their rows ([`filter_rows`]): a row wraps only where the menu is narrower than -/// it. The Document filter is unavailable without a `document`. Records in `st` the width of the -/// widest row unwrapped; whether a filter changed. -fn filters(ui: &mut Ui, st: &mut MenuState, t: &Tokens, document: bool) -> bool { +/// it. The Document filter is unavailable without a `document`. With `row` (the rows' height while +/// samples are shown), a row under them offers Font Preview Size's values, the one of that height +/// selected; a click on one asks for it ([`apply_preview_size`]). Records in `st` the width of the +/// widest row unwrapped, the size row included; whether a filter changed. +fn filters(ui: &mut Ui, st: &mut MenuState, t: &Tokens, document: bool, row: Option) -> bool { let mut refilter = false; let mut widest = 0.0_f32; for row in filter_rows() { @@ -1492,6 +1520,31 @@ fn filters(ui: &mut Ui, st: &mut MenuState, t: &Tokens, document: bool) -> bool widest = widest.max(width); }); } + if let Some(row) = row { + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing = vec2(4.0, 2.0); + let gap = ui.spacing().item_spacing.x; + let text = |s: &str| egui::RichText::new(s).size(FILTER_SIZE); + let mut width = ui.label(text(tl!("Font Preview Size")).color(t.text_dim)).rect.width(); + // Screen readers find the three sizes in a radio group named after the row. + let group = egui::UiBuilder::new().accessibility_role(egui::accesskit::Role::RadioGroup).accessibility_label(tl!("Font Preview Size")); + ui.scope_builder(group, |ui| { + for (size, height) in PREVIEW_SIZES { + let on = (height - row).abs() < 0.5; + let label = preview_size_label(size); + let resp = ui.selectable_label(on, text(label)); + resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::RadioButton, true, on, label)); + width += gap + resp.rect.width(); + if resp.clicked() { + ui.data_mut(|d| d.insert_temp(preview_size_id(), size)); + // A focused button is activated by Enter; the list must not read it as a pick. + ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter)); + } + } + }); + widest = widest.max(width); + }); + } st.filters = widest; // While Show Similar Fonts orders the list: the family it orders by, which clears it. Its // width is left out of the widest row: a long name wraps instead of widening the menu. @@ -1679,8 +1732,16 @@ fn rows(ui: &mut Ui, range: std::ops::Range, h: Listed<'_>, sample: Optio let place = egui::Rect::from_min_size(egui::pos2(left, top + i as f32 * row_h), vec2(width, row_h)); ui.scroll_to_rect_animation(place, align, egui::style::ScrollAnimation::none()); }; + // At a new row height (Font Preview Size, set from the menu), the view stays on the rows it + // showed: the scroll offset is in points. + let at = (ui.clip_rect().top() - top) / row_h; + let kept = st.scrolled.filter(|&(h, _)| !opening && (h - row_h).abs() > 0.5).map(|(_, at)| at); + st.scrolled = Some((row_h, kept.unwrap_or(at))); if let Some((i, align)) = scroll_target(st, &rows, opening, keyed) { scroll_to(ui, i, align); + } else if let Some(at) = kept { + let place = egui::Rect::from_min_size(egui::pos2(left, top + at * row_h), vec2(width, row_h)); + ui.scroll_to_rect_animation(place, Some(egui::Align::TOP), egui::style::ScrollAnimation::none()); } let mut chosen: Option<(String, Option)> = None; let mut hovered: Option = None; @@ -2027,6 +2088,31 @@ fn open_id() -> egui::Id { egui::Id::unique("font-menu-open") } +/// The id under which a font menu keeps the Font Preview Size its buttons asked for, until +/// [`apply_preview_size`] sets it. +fn preview_size_id() -> egui::Id { + egui::Id::unique("font-menu-preview-size") +} + +/// Set the Font Preview Size (Preferences › Type) that a font menu's Small, Medium or Large button +/// asked for in the last pass, which sizes the rows of every font menu, and have the host write the +/// preferences file as it does when Preferences is confirmed. Nothing runs when it is already that +/// size; a saved value that is none of the sizes is replaced. The shell calls it at the start of +/// each frame. +pub(crate) fn apply_preview_size(app: &mut VectorcraftApp, ctx: &egui::Context) { + let Some(size) = ctx.data_mut(|d| d.remove_temp::<&'static str>(preview_size_id())) else { return }; + if app.session.prefs.font_preview_size == size { + return; + } + match app.run("prefs.set", json!({"key": "fontPreviewSize", "value": size})) { + Ok(_) => { + crate::prefs_dialog::snapshot(app); + app.prefs_changed = true; + } + Err(e) => app.ui.status = e, + } +} + /// Undo a preview whose menu is gone (its panel wasn't drawn: the text was deselected, the panel /// closed) or is closing (Escape, a press outside the menu), before anything else sees this /// frame's input: the canvas must not act inside the preview's interaction (a drag would be @@ -2057,7 +2143,8 @@ pub(crate) fn apply(app: &mut VectorcraftApp, ctx: &egui::Context, pick: FontPic FontPick::Preview(f, style) => { if !previewing { crate::panels::character::end_typing(app); - if app.session.begin_interaction("Font").is_err() { + if let Err(e) = app.begin_interaction("Font") { + app.status(e); return; } crate::panels::set_pstate(ctx, PREVIEWING, true); diff --git a/crates/ui-egui/src/font_menu/tests.rs b/crates/ui-egui/src/font_menu/tests.rs index 958a6c1af1..7d930b7af5 100644 --- a/crates/ui-egui/src/font_menu/tests.rs +++ b/crates/ui-egui/src/font_menu/tests.rs @@ -1221,6 +1221,58 @@ fn the_document_filter_counts_type_in_graph_designs() { assert_eq!(names, ["inter", "jetbrains mono"]); } +/// Type in the art of a stored scatter brush counts as the document's type, as a scatter stroke +/// draws it, after a malformed library entry too. Type in an art or pattern brush's art does not, +/// as those brushes leave type out when they bend their art. +#[test] +fn the_document_filter_counts_type_in_scatter_brushes() { + let mut app = app_with_type(&["Inter"]); + let mut art = |font: &str| { + let id = app.run("text.create", serde_json::json!({"x": 20, "y": 90, "text": "Dot", "font": font})).unwrap()["id"].as_u64().unwrap(); + let node = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).cloned().expect("the new type"); + app.run("edit.undo", serde_json::json!({})).unwrap(); + node + }; + let (scatter, bent, tiled) = (art("JetBrains Mono"), art("Source Serif 4"), art("Source Sans 3")); + let brush = |name: &str, kind| serde_json::to_value(vectorcraft_brush::Brush { name: name.into(), kind }).unwrap(); + let library = serde_json::json!([ + {"name": "Broken", "type": "scatter", "art": 7}, + brush("Art", vectorcraft_brush::BrushKind::Art(vectorcraft_brush::ArtBrush { art: bent, ..Default::default() })), + brush("Pattern", vectorcraft_brush::BrushKind::Pattern(vectorcraft_brush::PatternBrush { side: tiled, ..Default::default() })), + brush("Dots", vectorcraft_brush::BrushKind::Scatter(vectorcraft_brush::Scatter { art: scatter, ..Default::default() })), + ]); + let mut doc = (*app.session.active().unwrap().doc).clone(); + doc.unknown.insert(vectorcraft_brush::DOC_KEY.into(), library); + let db = vectorcraft_text::FontDb::global(); + let mut names: Vec<_> = super::document_families(db, &doc).into_iter().collect(); + names.sort(); + assert_eq!(names, ["inter", "jetbrains mono"]); +} + +/// A scatter brush made of type keeps its family in the Document filter after the type is deleted; +/// deleting the brush takes the family out, and undoing the deletion brings it back. +#[test] +fn the_document_filter_follows_a_scatter_brushs_edits_and_undo() { + let mut app = app_with_type(&["Inter"]); + let id = app.run("text.create", serde_json::json!({"x": 20, "y": 90, "text": "Dot", "font": "JetBrains Mono"})).unwrap()["id"].clone(); + let name = app.run("brush.new", serde_json::json!({"type": "scatter", "name": "Type Dots"})).unwrap()["name"].clone(); + app.run("edit.clear", serde_json::json!({"ids": [id]})).unwrap(); + let db = vectorcraft_text::FontDb::global(); + // One menu state throughout, so each edit has to get past the families it keeps. + let mut st = super::MenuState { document_only: true, ..Default::default() }; + let mut families = |app: &crate::VectorcraftApp| { + let used = super::used_families(db, &mut st, super::MenuLook::of(app)).expect("a document is open"); + let mut names: Vec<_> = used.iter().cloned().collect(); + names.sort(); + names + }; + assert_eq!(families(&app), ["inter", "jetbrains mono"], "the brush's type"); + app.run("brush.delete", serde_json::json!({"name": name})).unwrap(); + assert_eq!(families(&app), ["inter"], "the brush deleted"); + app.run("edit.undo", serde_json::json!({})).unwrap(); + assert_eq!(families(&app), ["inter", "jetbrains mono"], "the deletion undone"); +} + /// A run whose family and style were split from a PostScript name (as an importer without the font /// splits one) counts under the family of the installed font of that name, found with its style. #[test] @@ -1468,3 +1520,212 @@ fn the_recently_added_filter_lists_a_font_installed_just_now() { assert!(st.rows.is_empty(), "31 days later: {:?}", st.rows); std::fs::remove_dir_all(&dir).unwrap(); } + +/// While the samples are shown, a row under the filters offers Font Preview Size's Small, Medium +/// and Large at every size of the rows: a click on one asks for that size ([`super::apply_preview_size`] +/// leaves the rows' own size as it is). Without samples the row is not drawn. +#[test] +fn the_preview_size_row_asks_for_the_size_clicked() { + // The bundled fonts alone: fonts that tests running alongside add stay out of the rows. + let db = vectorcraft_text::FontDb::with_font_dirs(vec![]); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut st = super::MenuState::default(); + for size in ["small", "medium", "large"] { + let look = super::MenuLook { row: super::preview_row(size), ..Default::default() }; + let shapes = settle_menu_of(&ctx, &db, &mut st, look, vec![]); + assert!(text_at(&shapes, |t| t == "Font Preview Size").is_some(), "the row is drawn at {size}"); + let mut click = |label: &str| { + let shapes = settle_menu_of(&ctx, &db, &mut st, look, vec![]); + let at = text_at(&shapes, |t| t == label).unwrap_or_else(|| panic!("{label} is drawn at {size}")); + let button = + |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + settle_menu_of(&ctx, &db, &mut st, look, vec![egui::Event::PointerMoved(at), button(true)]); + settle_menu_of(&ctx, &db, &mut st, look, vec![button(false)]); + ctx.data_mut(|d| d.remove_temp::<&'static str>(super::preview_size_id())) + }; + assert_eq!(click("Large"), Some("large"), "at {size}"); + assert_eq!(click("Small"), Some("small"), "at {size}"); + assert_eq!(click("Medium"), Some("medium"), "at {size}"); + } + let look = super::MenuLook { row: super::preview_row("medium"), ..Default::default() }; + let shapes = settle_menu_of(&ctx, &db, &mut st, super::MenuLook { samples: false, ..look }, vec![]); + assert!(text_at(&shapes, |t| t == "Font Preview Size").is_none(), "without samples the row is not drawn"); + super::wait_for_samples(&ctx); +} + +/// Enter on a focused size button asks for that size and picks no font: the key is not also read as +/// the list's Enter, which would apply the highlighted font and close the menu. +#[test] +fn enter_on_a_focused_size_button_picks_no_font() { + let db = vectorcraft_text::FontDb::with_font_dirs(vec![]); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + // The Recently Added filter gives the list rows from the bundled fonts alone. + let mut st = super::MenuState { added_only: true, added: added_in(&db, &["Source Serif 4", "Inter"], None), ..Default::default() }; + let id = egui::Id::unique("size-enter"); + let look = super::MenuLook { row: super::preview_row("small"), clock: Some(clock()), ..Default::default() }; + let area = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 900.0)); + let frame = |st: &mut super::MenuState, events: Vec| { + let mut pick = None; + let mut out = ctx.run_ui(egui::RawInput { events, screen_rect: Some(area), ..Default::default() }, |ui| { + pick = super::list_of(ui, &db, id, st, "Inter", None, look).inner; + }); + out.textures_delta.clear(); + (out.shapes, pick) + }; + frame(&mut st, vec![]); + let (shapes, _) = frame(&mut st, vec![]); + let at = text_at(&shapes, |t| t == "Large").expect("Large is drawn"); + let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(&mut st, vec![egui::Event::PointerMoved(at), button(true)]); + frame(&mut st, vec![button(false)]); + ctx.data_mut(|d| d.remove_temp::<&'static str>(super::preview_size_id())); + let enter = |pressed| egui::Event::Key { + key: egui::Key::Enter, + physical_key: Some(egui::Key::Enter), + pressed, + repeat: false, + modifiers: Default::default(), + }; + let tab = + |pressed| egui::Event::Key { key: egui::Key::Tab, physical_key: Some(egui::Key::Tab), pressed, repeat: false, modifiers: Default::default() }; + assert!(!listed_families(&st).is_empty(), "the list has rows an Enter could pick"); + // Tab moves the focus along the controls until it is on the Large button, where Enter is pressed. + let mut found = None; + for _ in 0..60 { + frame(&mut st, vec![tab(true)]); + frame(&mut st, vec![tab(false)]); + let on_large = ctx.memory(|m| m.focused()).and_then(|f| ctx.read_response(f)).is_some_and(|r| r.rect.contains(at)); + if !on_large { + continue; + } + let (_, pick) = frame(&mut st, vec![enter(true)]); + frame(&mut st, vec![enter(false)]); + if ctx.data_mut(|d| d.remove_temp::<&'static str>(super::preview_size_id())) == Some("large") { + found = Some(pick); + break; + } + } + let pick = found.expect("Enter on the focused Large button asks for the size"); + assert!(pick.is_none(), "Enter on the size button picks no font: {pick:?}"); + super::wait_for_samples(&ctx); +} + +/// The size a font menu's button asked for becomes Font Preview Size, which sizes every font +/// menu's rows, and the host is asked to write the preferences file. The document is left as it +/// was: a font previewed on the selected type stays previewed, and the change adds no undo step. +#[test] +fn a_preview_size_asked_for_sets_the_preference_and_keeps_the_preview() { + let ctx = egui::Context::default(); + let mut app = app_with_type(&[]); + let id = app.run("text.create", serde_json::json!({"x": 20, "y": 90, "text": "Size", "font": "Inter"})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", serde_json::json!({"ids": [id]})).unwrap(); + let font = |app: &crate::VectorcraftApp| match &app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind { + vectorcraft_doc::NodeKind::Text(t) => t.first_style().font_family, + _ => String::new(), + }; + super::apply(&mut app, &ctx, super::FontPick::Preview("Source Serif 4".into(), None)); + assert_eq!(font(&app), "Source Serif 4"); + assert_eq!(super::MenuLook::of(&app).row, super::preview_row("medium")); + assert!(!app.take_prefs_changed(), "nothing to write yet"); + let undo_depth = |app: &crate::VectorcraftApp| app.session.doc().unwrap().history.undo.len(); + let depth = undo_depth(&app); + // The rows' own size: nothing changes. + ctx.data_mut(|d| d.insert_temp(super::preview_size_id(), "medium")); + super::apply_preview_size(&mut app, &ctx); + assert_eq!(app.session.prefs.font_preview_size, "medium"); + assert!(!app.take_prefs_changed(), "nothing to write for the size the rows have"); + ctx.data_mut(|d| d.insert_temp(super::preview_size_id(), "large")); + super::apply_preview_size(&mut app, &ctx); + assert_eq!(app.session.prefs.font_preview_size, "large"); + assert_eq!(undo_depth(&app), depth, "the size is not an undo step"); + assert_eq!(super::MenuLook::of(&app).row, super::preview_row("large")); + assert!(app.take_prefs_changed(), "the host is asked to write the preferences file"); + assert_eq!(app.ui.engine_prefs["fontPreviewSize"], "large"); + assert!(app.session.in_interaction(), "the preview is still open"); + assert_eq!(font(&app), "Source Serif 4", "the preview stays on the type"); + // Asked for once, applied once. + super::apply_preview_size(&mut app, &ctx); + assert_eq!(app.session.prefs.font_preview_size, "large"); + assert!(!app.take_prefs_changed(), "nothing more to write"); + // A saved value that is none of the sizes draws Medium's rows, and Medium replaces it. + app.session.prefs.font_preview_size = "huge".into(); + assert_eq!(super::MenuLook::of(&app).row, super::preview_row("medium")); + ctx.data_mut(|d| d.insert_temp(super::preview_size_id(), "medium")); + super::apply_preview_size(&mut app, &ctx); + assert_eq!(app.session.prefs.font_preview_size, "medium"); + assert!(app.take_prefs_changed(), "the replaced value is written"); + super::apply(&mut app, &ctx, super::FontPick::EndPreview); + assert_eq!(font(&app), "Inter"); + app.run("edit.undo", serde_json::json!({})).unwrap(); + assert!( + app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).is_none(), + "undo takes the type away: no step was added for the size" + ); +} + +/// Screen readers find Small, Medium and Large as radio buttons in a group named Font Preview +/// Size, with the size of the rows chosen. +#[test] +fn the_preview_size_row_is_a_radio_group_showing_the_size() { + use crate::widgets::accessibility_tests::{named, role_and_state, tree}; + use egui::accesskit::{Role, Toggled}; + // The bundled fonts alone: fonts that tests running alongside add stay out of the rows. + let db = vectorcraft_text::FontDb::with_font_dirs(vec![]); + let sizes = ["small", "medium", "large"]; + for size in sizes { + let mut st = super::MenuState::default(); + let look = super::MenuLook { row: super::preview_row(size), ..Default::default() }; + let nodes = tree(|ui| { + let _ = super::list_of(ui, &db, egui::Id::unique("size-group"), &mut st, "Inter", None, look); + }); + assert_eq!(named(&nodes, "Font Preview Size").role(), Role::RadioGroup, "at {size}"); + for other in sizes { + let chosen = if other == size { Toggled::True } else { Toggled::False }; + assert_eq!(role_and_state(&nodes, super::preview_size_label(other)), (Role::RadioButton, Some(chosen)), "{other} at {size}"); + } + } +} + +/// A new Font Preview Size chosen in the open menu keeps the list on the rows it showed: the +/// view starts the same number of rows down at the new height, not the same number of points. +#[test] +fn a_new_preview_size_keeps_the_list_on_its_rows() { + // The bundled fonts alone: fonts that tests running alongside add stay out of the rows. + let db = vectorcraft_text::FontDb::with_font_dirs(vec![]); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut st = super::MenuState::default(); + // One frame `height` points high at `size`: the list's offset, top, view height and content height. + let frame = |height: f32, size: &str, st: &mut super::MenuState| { + let area = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, height)); + let look = super::MenuLook { row: super::preview_row(size), ..Default::default() }; + let mut shown = None; + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(area), ..Default::default() }, |ui| { + let mut child = ui.new_child(egui::UiBuilder::new().max_rect(area)); + // Opening on the last family scrolls the list to its end. + let list = super::list_of(&mut child, &db, egui::Id::unique("keep-rows"), st, "Source Serif 4", None, look); + shown = Some((list.state.clamped_offset().y, list.inner_rect.top(), list.inner_rect.height(), list.content_size.y)); + }); + out.textures_delta.clear(); + shown.unwrap_or_else(|| panic!("the list was not drawn")) + }; + let (_, top, _, _) = frame(900.0, "medium", &mut st); + // A fresh opening, with room for fewer rows than the list holds. + let mut st = super::MenuState::default(); + let mut medium = (0.0, 0.0, 0.0, 0.0); + for _ in 0..4 { + medium = frame(top + 64.0, "medium", &mut st); + } + let (offset, _, view, content) = medium; + assert!(content > view + 0.5 && offset > 0.5, "the list is scrolled: {medium:?}"); + let rows_down = offset / super::preview_row("medium"); + let mut large = (0.0, 0.0, 0.0, 0.0); + for _ in 0..3 { + large = frame(top + 64.0, "large", &mut st); + } + let expected = rows_down * super::preview_row("large"); + assert!((large.0 - expected).abs() < 0.5, "the view starts {rows_down} rows down: offset {} for {expected}", large.0); + super::wait_for_samples(&ctx); +} diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 24578b18b2..e43e4bf0f4 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -100,7 +100,7 @@ fn plural_polish(n: u64) -> usize { pub static LANGUAGES: [LangInfo; 29] = [ LangInfo { code: "en", name: "English", source: "", plural: plural_one_other, complete_menus: false, catalog: OnceLock::new() }, // Hindi shares the integer zero/one rule with French. Desktop UI fonts are loaded lazily - // from installed faces by ui_fonts; the web needs a Devanagari font in its font set. + // from installed faces by ui_fonts; the web fetches a Devanagari craft-fonts face on demand. LangInfo { code: "hi", name: "हिन्दी", @@ -623,6 +623,13 @@ pub fn t(s: &str) -> &str { tr(current(), s) } +/// `label`, already in the current language, followed by a field label's colon as the current +/// language writes it (its catalog row for ":"): French puts a no-break space before the colon, and +/// Chinese and Japanese write a full-width colon. +pub fn colon(label: &str) -> String { + format!("{label}{}", t(":")) +} + /// Translate an English UI string; unknown strings come back unchanged. pub fn tr(lang: Lang, s: &str) -> &str { lang.catalog().plain(s).unwrap_or(s) @@ -633,6 +640,11 @@ pub fn tr_ctx<'a>(lang: Lang, context: &str, s: &'a str) -> &'a str { lang.catalog().contextual(context, s).unwrap_or_else(|| tr(lang, s)) } +/// The translation of `s` in `lang`'s `context` rows alone, or `None` when it has no such row. +pub fn tr_ctx_row(lang: Lang, context: &str, s: &str) -> Option<&'static str> { + lang.catalog().contextual(context, s) +} + /// A name the app gives something (a default swatch's), translated where the current language has /// a `context` row for it; any other name (one the user gave) comes back as it is. pub fn t_name<'a>(context: &str, name: &'a str) -> &'a str { @@ -722,14 +734,16 @@ fn fill_message(lang: Lang, s: &str, found: Option<(&[String], catalog::Captures message_at(lang, v, depth - 1) } }; + let left_out = left_out_kinds(lang, s, &caps); let liquify = liquify_skip_values(lang, s, &caps); let values: Vec<(&str, String)> = caps .into_iter() - .map(|(k, v)| match (&liquify, k) { - (Some((tool, _)), "_1") => (k, tool.clone()), - (Some((_, kinds)), "_2") => (k, kinds.clone()), - (_, "ident") => (k, v.to_string()), - (_, "to") if !quoted(v) => (k, exact_translation(lang.catalog(), v).unwrap_or_else(|| v.to_string())), + .map(|(k, v)| match (&left_out, &liquify, k) { + (Some(kinds), _, "kinds") => (k, kinds.clone()), + (_, Some((tool, _)), "_1") => (k, tool.clone()), + (_, Some((_, kinds)), "_2") => (k, kinds.clone()), + (_, _, "ident") => (k, v.to_string()), + (_, _, "to") if !quoted(v) => (k, exact_translation(lang.catalog(), v).unwrap_or_else(|| v.to_string())), _ => (k, nested(v)), }) .collect(); @@ -737,6 +751,69 @@ fn fill_message(lang: Lang, s: &str, found: Option<(&[String], catalog::Captures fill_once(template, &args) } +/// The kinds the warning about an SVG's variables that aren't text names (the engine's +/// `left_out_kind` in `crates/engine/src/cmd/variablecmds/library.rs`), each translated by its +/// `variable-kind` row. +const LEFT_OUT_KINDS: [&str; 4] = ["Visibility", "Linked File", "Graph Data", "Unknown"]; + +/// The list of kinds in `lang` when `s` is the warning about an SVG's variables that aren't text +/// and `caps` are its captures. Each entry is a kind of [`LEFT_OUT_KINDS`] or a `trait` the file +/// names, in backticks with each backtick in it doubled, followed by its count in parentheses; the +/// entries are separated by `, `. A kind of [`LEFT_OUT_KINDS`] is shown in `lang`, a `trait` as the +/// warning writes it, and the entries keep their order and counts, joined with the +/// `variable-list-two` row for two, and the `variable-list-middle` and `variable-list-end` rows for +/// more; a missing row leaves its part in English. `None` for any other message, or a list that +/// does not have that form. +fn left_out_kinds(lang: Lang, s: &str, caps: &[(&str, &str)]) -> Option { + let [("kinds", kinds)] = caps else { return None }; + if s.strip_prefix("variables that aren't text were left out: ") != Some(*kinds) { + return None; + } + let catalog = lang.catalog(); + let mut entries = Vec::new(); + let mut rest = *kinds; + loop { + let (name, after) = if let Some(quoted) = rest.strip_prefix('`') { + // The `trait` ends at the first backtick that is not doubled. + let mut at = 0; + let close = loop { + let found = at + quoted[at..].find('`')?; + if quoted[found + 1..].starts_with('`') { + at = found + 2; + } else { + break found; + } + }; + rest.split_at(close + 2) + } else { + let kind = LEFT_OUT_KINDS.iter().find(|k| rest.starts_with(**k))?; + (catalog.contextual("variable-kind", kind).unwrap_or(kind), &rest[kind.len()..]) + }; + let (count, after) = after.strip_prefix(" (")?.split_once(')')?; + if count.is_empty() || !count.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + entries.push(format!("{name} ({count})")); + if after.is_empty() { + break; + } + rest = after.strip_prefix(", ")?; + } + let join = |context: &str, a: &str, b: &str| { + let pattern = "{0}, {1}"; + fill_once(catalog.contextual(context, pattern).unwrap_or(pattern), &[("0", a), ("1", b)]) + }; + match entries.as_slice() { + [] => None, + [one] => Some(one.clone()), + [a, b] => Some(join("variable-list-two", a, b)), + [first, middle @ .., last] => { + let head = middle.iter().fold(first.clone(), |acc, w| join("variable-list-middle", &acc, w)); + Some(join("variable-list-end", &head, last)) + } + } +} + /// The tool labels in Liquify's warning about the objects under the brush that it left as they /// were, each translated by its `liquify-tool` row. const LIQUIFY_TOOLS: [&str; 7] = ["Warp", "Twirl", "Pucker", "Bloat", "Scallop", "Crystallize", "Wrinkle"]; diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index bb039bb08e..59dc587ee7 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -105,6 +105,7 @@ Add Anchor Point Добавяне на опорна точка Add Anchor Point Tool Инструмент „Добавяне на опорна точка“ Add Anchor Points Добавяне на опорни точки + Add Around Добавяне около обекта Add Effect Добавяне на ефект Add Freeform Line Добавяне на свободна линия Add Freeform Point Добавяне на свободна точка @@ -126,8 +127,12 @@ Add to Swatches Добавяне към образци Add Used Colors Добавяне на използваните цветове Additional Plug-ins Folder Допълнителна папка за плъгини + Plug-in Instruction Budget Бюджет на инструкции за плъгини Additional Fonts Folder Допълнителна папка за шрифтове Adjust Adjoining Width Points Регулиране на прилежащите точки за ширина + Incoming Входяща + Outgoing Изходяща + Single Width Only Само една ширина Adjust Color Balance… Коригиране на цветовия баланс… Adjust Colors Коригиране на цветовете Adjust Options: Параметри на коригиране: @@ -182,6 +187,7 @@ Angle: Ъгъл: Angles Ъгли Animated Zoom Анимирано мащабиране + Anti Alias Заглаждане Anti-alias Заглаждане Anti-Alias Заглаждане Anti-alias Rasters Заглаждане на растери @@ -348,6 +354,8 @@ font-technology Variable Променливи Brush Definition Дефиниция на четка Brush Libraries Библиотеки с четки Brush Options… Опции за четката… + Options of Selected Object… Опции на избрания обект… + Options of Selected Object Опции на избрания обект Brush Strokes Щрихи с четка Brushes Четки Built-in Libraries Вградени библиотеки @@ -404,6 +412,12 @@ font-technology Variable Променливи Character Alignment Подравняване на знаците Character / Paragraph Знак / Абзац Character Rotation Въртене на знак + Chinese Big 5 Китайски Big 5 + Cyrillic Кирилица + Greek Гръцки + Turkish Турски + Baltic Балтийски + Central European Централноевропейски Character Set: Набор от знаци: Character Style Стил на знак Character Style Options Опции за стил на знак @@ -465,6 +479,8 @@ font-technology Variable Променливи Choose a folder Избор на папка Choose… Избор… Circle Кръг + Circle Tool Инструмент Кръг + Circle too large Кръгът е твърде голям Classic Defaults Класически по подразбиране Clean Up… Почистване… Clear Изчистване @@ -539,6 +555,7 @@ font-technology Variable Променливи Color Mixer (Shift-click the chip) Цветов смесител (Shift-щракване върху блокчето) Color Mode Цветен режим Color Mode: Цветен режим: + Color Model Цветен модел Color Model: Цветен модел: Color Models Цветни модели Color Picker Палитра с цвят @@ -559,12 +576,18 @@ font-technology Variable Променливи Saturation and brightness Насищане и яркост Color field Цветово поле {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Изглед „Колело“ + Box View Изглед „Квадрат“ + Box Channel Канал на квадрата + Color box Цветови квадрат + Color Wheel Options Опции на цветното колело Color Type: Цветен тип: Color: Цвят: Colorize Оцветяване Colors Цветове Colors: Цветове: Column Graph Tool Инструмент „Колонна диаграма“ + Columns Колони Columns: Колони: Column… Колона… Combine Slices Обединяване на парчетата @@ -768,6 +791,8 @@ font-technology Variable Променливи Delete Artboard Изтриване на работна област Delete Artboards Изтриване на работни области Delete Brush Изтриване на четка + Delete Color Изтриване на цвят + Restore Generated Table Възстановяване на генерираната таблица Delete Character Style Изтриване на стил за знаци Delete Empty Artboards Изтриване на празни работни области Delete Freeform Point Изтриване на свободна точка @@ -836,6 +861,7 @@ font-technology Variable Променливи Direct Selection Tool Инструмент „Директен избор“ Direction Handles Маркери за посока Disable Auto Add/Delete Изключване на автоматично добавяне/изтриване + Interpolate Control Points When Moving Anchors Интерполиране на маркерите за посока при преместване на опорни точки Disable Opacity Mask Изключване на маска за непрозрачност Discard Отхвърляне Discard Empty Type Отхвърляне на празен текст @@ -1040,6 +1066,7 @@ font-technology Variable Променливи Enable text access for screen readers Разрешаване на достъп до текст за екранни четци Enable Touch Gestures Разрешаване на докосващи жестове Switch Selection and Drawing Modes Превключване между режим на селекция и рисуване + Select Last Selection Tool Избор на последния инструмент за селекция Enable Touch Workspace Разрешаване на работно пространство за докосване Encoding Кодиране Encoding: Кодиране: @@ -1162,7 +1189,7 @@ font-technology Variable Променливи Extrude & Bevel… Избутване и фасетка… 3D (Classic) 3D (класически) Extrude & Bevel (Classic)… Избутване и фасетка (класически)… - Revolve (Classic)… Завъртане (класическо)… + Revolve (Classic)… Завъртане около ос (класическо)… Rotate (Classic)… Ротация (класическа)… Surface Повърхност Wireframe Телена рамка @@ -1208,6 +1235,8 @@ font-technology Variable Променливи Files Файлове Files of a PDF standard can't be password-protected. Файлове от PDF стандарт не могат да бъдат защитени с парола. Files of this standard tag their colours with ICC profiles. Файловете от този стандарт етикетират цветовете си с ICC профили. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Файловете от този стандарт етикетират цветовете си с ICC профили, с изключение на CMYK цветовете в профила на предназначението на изхода, които се записват като DeviceCMYK. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. С „Без включване на профили“ и CMYK предназначение на изхода всеки CMYK цвят се записва като DeviceCMYK, освен ако не се преобразува към CMYK местоназначение с друг профил. Fill Запълване Fill & Stroke Запълване и щрих Fill (X), double-click for the Color Picker Запълване (X), щракнете двукратно за избор на цвят @@ -1949,6 +1978,7 @@ font-technology Variable Променливи Load SVG into Clipboard Зареждане на SVG в клипборда Load Text into Clipboard Зареждане на текст в клипборда Local Libraries Локални библиотеки + Locate Layer Намиране на слой Locate Object Намиране на обект Locate Selected Objects Намиране на избраните обекти Location Местоположение @@ -2143,6 +2173,7 @@ font-technology Variable Променливи Scatter: Разпръскване: Rotation: Завъртане: Rotation relative to: Завъртане спрямо: + Hue Jitter: Вариация на оттенъка: Brush Scale Options Опции за мащабиране на четката Scale Proportionately Мащабиране пропорционално Stretch to Fit Stroke Length Разтягане за запълване дължината на щриха @@ -2179,6 +2210,7 @@ font-technology Variable Променливи Black becomes the stroke color and white stays white. Other colors become tints of the stroke color by their lightness. Черното става цвят на щриха, а бялото остава бяло. Другите цветове стават оттенъци на цвета на щриха и колкото по-светъл е един цвят, толкова по-светъл е оттенъкът му. Black and white stay as they are. Dark colors become shades of the stroke color and light colors become tints of it. Черното остава черно, а бялото остава бяло. Другите цветове стават тъмни нюанси на цвета на щриха, когато са тъмни, и негови оттенъци, когато са светли. The key color becomes the stroke color. The other colors shift their hue by the same amount and keep their saturation and brightness. Основният цвят става цвят на щриха. Другите цветове се завъртат по цветовото колело толкова, колкото и основният цвят, и запазват насищането и яркостта си. + Roundness Закръгленост Roundness: Закръгленост: Fixed Фиксирано Pressure Натиск @@ -2452,6 +2484,8 @@ font-technology Variable Променливи Other Library… Друга библиотека… Some scripts were not listed Някои скриптове не са изброени The Scripts folder cannot be read Папката Scripts не може да бъде прочетена + Loading scripts… Зареждане на скриптовете… + The Scripts folder is still being read Папката Scripts все още се чете Other Script… Друг скрипт… Out of Gamut Warning Предупреждение за излизане извън цветовата гама Out of Web Color Warning Предупреждение за цвят извън уеб палитрата @@ -2480,6 +2514,9 @@ font-technology Variable Променливи Overprint Напечатване върху друго Overprint and Transparency Flattener Сплескване на надпечатването и прозрачността Overprint and Transparency Flattener Options Опции за сплескване на надпечатването и прозрачността + Custom… Потребителски… + Custom Transparency Flattener Options Потребителски опции за сплескване на прозрачността + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS няма алфа прозрачност, а „Надпечати“ определя дали надпечатванията се запазват. Overprint Black… Напечатване на черното върху друго… Overprint Fill Напечатване на запълването върху друго Overprint Preview Преглед на напечатването върху друго @@ -2584,6 +2621,7 @@ font-technology Variable Променливи Play Current Selection Изпълнение на текущия избор Save Actions… Запазване на действия… Load Actions… Зареждане на действия… + Replace Actions… Замяна на действия… Reset Actions Нулиране на действия Replace the current actions with the default set? Да се заменят ли текущите действия с набора по подразбиране? Append adds the default set after the current sets instead. С „Добавяне“ наборът по подразбиране се добавя след текущите набори. @@ -2599,6 +2637,10 @@ font-technology Variable Променливи Polar Grid Tool Инструмент „Полярна мрежа“ Polygon Многоъгълник Polygon Properties: Свойства на многоъгълника: + Line Properties: Свойства на линията: + Line Length: Дължина на линията: + Line Angle: Ъгъл на линията: + Constrain Pie Angle Запазване на ъгъла на сектора Polygon Tool Инструмент „Многоъгълник“ Portrait Портретна Power Saving (integrated) Пестене на енергия (интегрирано) @@ -2758,6 +2800,7 @@ digits Malayalam Малаялам Real World: Реален свят: Real-time Drawing and Editing Чертане и редактиране в реално време Use Monitor Profile for Canvas Използване на профила на монитора за платното + Refresh Monitor Profile Обновяване на профила на монитора The canvas is drawn in sRGB. Платното се изобразява в sRGB. Canvas display profile: Профил на дисплея за платното: The system matches the window to the display's colors. Системата съгласува цветовете на прозореца с дисплея. @@ -2949,6 +2992,8 @@ digits Malayalam Малаялам Reselect Избиране отново Reset Нулиране Reset Bounding Box Нулиране на ограничителната рамка + Rotate Bounding Box Завъртане на ограничителната рамка + Rotate Bounding Box… Завъртане на ограничителната рамка… Reset Envelope Mesh Нулиране на мрежата на обвивката Reset Envelope Shape Нулиране на формата на обвивката Reset Essentials Нулиране на основните @@ -2989,6 +3034,7 @@ digits Malayalam Малаялам Reshape Segment Преоформяне на сегмент Reshape Tool Инструмент „Преоформяне“ Reshape Type Area Преоформяне на текстова област + Resolution Разделителна способност Resolution: Разделителна способност: Responsive Адаптивен Restore Възстановяване @@ -3015,6 +3061,7 @@ digits Malayalam Малаялам The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Колелцето на мишката с натиснат Cmd/Ctrl превърта платното настрани. Dragging sideways on a numeric field's label changes the field's value. Влаченето настрани върху етикета на числово поле променя стойността на полето. A two-finger rotate gesture on a trackpad rotates the canvas view. Жест за завъртане с два пръста върху тъчпад завърта изгледа на платното. + When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Когато премествате котвени точки, всяка крива с една преместена крайна точка запазва формата си спрямо краищата си. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Задържането на клавишната комбинация на инструмент го избира, докато я пуснете, а след това отново се избира предишният инструмент. Shows the bounding box while you move the selection or draw a shape. Показва ограничителната рамка, докато премествате селекцията или рисувате форма. Create Trim Marks draws Japanese-style marks instead of Roman ones. „Създаване на режещи знаци“ рисува знаци в японски стил вместо в римски. @@ -3045,6 +3092,29 @@ digits Malayalam Малаялам The unit for East Asian type measurements, which no field uses yet. Единицата за мерките на източноазиатски текст, която засега не се използва от нито едно поле. When on, a number typed without a unit into a field in picas is read in points. Когато е включено, число, въведено без единица в поле в пики, се чете в точки. With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options. При XML ID имената на обектите се показват като XML ID в Слоеве, Променливи и Опции за слоя. + The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl. Стъпката за размер на текста и междуредие: Cmd/Ctrl+Shift+. и Cmd/Ctrl+Shift+, променят размера с една стъпка, а с Alt – с пет; в хоризонтален текст Alt със стрелка нагоре или надолу променя междуредието с една стъпка, а с Cmd/Ctrl – с пет. + The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl. Стъпката за разредка и кернинг в хилядни от em: в хоризонтален текст Alt със стрелка наляво или надясно променя кернинга при курсора или разредката на избрания текст с една стъпка, а с Cmd/Ctrl – с пет. + The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. Стъпката за изместване на базовата линия: в хоризонтален текст Alt и Shift със стрелка нагоре или надолу преместват базовата линия с една стъпка, а с Cmd/Ctrl – с пет. + Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. Показва опциите за японски и друг източноазиатски текст в панелите Знак, Абзац, OpenType и Глифи, както и командата Съставни шрифтове. + Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. Показва опциите за арабски, иврит и индийски текст в панелите Знак и Абзац, например посока на абзаца, кашиди и цифри. + The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. Инструментите за селекция избират текст само по базовата му линия, рамката на текста в област или пътя му, а не навсякъде в кутията му. + Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. Менютата за шрифтове показват всеки шрифт с английското му име; ако е изключено, шрифт, който има име и на собствения си език, показва това име. + New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. Новият текст в област започва с включен автоматичен размер, така че правоъгълна рамка с хоризонтален текст става по-висока или по-ниска според текста си. + Font lists and the Type › Font menu show a sample of each font beside its name. Списъците с шрифтове и менюто Шрифт показват мостра на всеки шрифт до името му. + Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on. Мострите на шрифтовете се рисуват с тъмен текст на бяло независимо от яркостта на интерфейса; това важи само докато визуализациите на шрифтове в менюто са включени. + How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is. Колко висок е всеки ред в списъците на полетата за шрифт, например в панела Знак, и съответно колко голяма е всяка мостра. + How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first. Колко от последно използваните шрифтове, от 1 до 15, показват Скорошни шрифтове и списъците с шрифтове, най-новите първи. + When you change the font or font style of text, characters the new font has no glyph for keep the font they had. Когато смените шрифта или стила на шрифта на текст, знаците, за които новият шрифт няма глиф, запазват предишния си шрифт. + A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export. Розово открояване върху платното отбелязва глифите, заменени от функции на OpenType, например лигатури; то не се отпечатва и не се експортира. + With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from. С инструмента Текст избирането на един знак показва до него върху платното ред с алтернативните му глифи за избор. + A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export. Розово открояване върху платното отбелязва текст, изобразен със заместващ шрифт, защото шрифтът му липсва; то не се отпечатва и не се експортира. + New type made with a Type tool starts with placeholder text, selected, so typing replaces it. Новият текст, създаден с инструмент за текст, започва с избран примерен текст, който въвеждането заменя. + Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list. Въвеждането на знак за списък, например 1. или *, и след това интервал в началото на абзац превръща абзаца в списък. + Fonts in this folder show in the font menus and can be used without being installed. Шрифтовете в тази папка се показват в менютата за шрифтове и могат да се използват, без да са инсталирани. + Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows. Прилагането на графичен стил към текст премахва собствените запълване или контур на знаците, където стилът има такива, така че се вижда боята на стила. + Align and Distribute measure point type by the ink of its glyphs instead of its em box. Подравняване и Разпределяне измерват точковия текст по мастилото на глифите му вместо по em-кутията му. + Align and Distribute measure area type by the ink of its glyphs instead of its frame. Подравняване и Разпределяне измерват текста в област по мастилото на глифите му вместо по рамката му. + The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box. Ограничаващата рамка и панелът Трансформиране измерват точковия текст по мастилото на глифите му вместо по em-кутията му. Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply. Прилепва рисуването, преместването и мащабирането към подразделенията на мрежата, дори когато мрежата е скрита; докато е включено, „Прилепване към пиксел“ не действа. The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead. Цветът на водачите, които не са избрани; работна област с „Етикет на водачите“ рисува своите водачи в цвета на етикета. Draws guides as solid lines or as dots, including the guides already in the document. Рисува водачите като плътни линии или като точки, включително водачите, които вече са в документа. @@ -3126,6 +3196,7 @@ digits Malayalam Малаялам Rounded Rectangle Tool Инструмент „Закръглен правоъгълник“ Rounded Rectangle… Закръглен правоъгълник… Row Size: Размер на реда: + Rows Ленти Rows: Ленти: Rule: Линия: Rulers Линийки @@ -3288,6 +3359,9 @@ digits Malayalam Малаялам Search commands, tools, panels and effects… Търсене на команди, инструменти, панели и ефекти… No commands match Няма съвпадащи команди {pos} of {total}: {name} {pos} от {total}: {name} + No menu item Няма елемент в менюто + Toolbar Лента с инструменти + {toolbar}, in the {tool} group {toolbar}, в групата на {tool} @plural {n} result|{n} results {n} резултат|{n} резултата @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} от {n} резултат. Продължете да пишете, за да ги стесните.|{shown} от {n} резултата. Продължете да пишете, за да ги стесните. Recent Commands Последни команди @@ -3368,6 +3442,7 @@ digits Malayalam Малаялам Set Slice Rectangle Задаване на правоъгълник за резен Set Tab Stops Задаване на табулатори Set Text Задаване на текст + Set the current fill or stroke to the selected color Задаване на избрания цвят като текущо запълване или щрих Set the selected color to the current color Задаване на текущия цвят като избран Set Zoom Задаване на мащаб Settings… Настройки… @@ -3489,7 +3564,7 @@ digits Malayalam Малаялам Show Vivid/Muted Показване на ярки/заглушени Show Warm/Cool Показване на топли/студени Show {kind} Brushes Показване на четки от вида {kind} - Show/hide plate (Alt-click: only this plate) Показване/скриване на плака (Alt-клик: само тази плака) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Показване/скриване на плака (Alt-клик: само тази плака; Alt-клик отново: всички плаки) Show: Показване: Shown with the optimised preview. Показано с оптимизирания преглед. Side 1: Страна 1: @@ -3627,6 +3702,11 @@ digits Malayalam Малаялам Opacity Masks Маски за непрозрачност Objects with Effects Обекти с ефекти Path Length Дължина на пътя + Grid Size Размер на мрежата + Grid Colors Цветове на мрежата + Flattener Preset Предварителна настройка за сплескване + X X + Y Y Spot Colors Спот цветове Spot Colors… Спот цветове… Spread: Разпространение: @@ -3852,6 +3932,13 @@ digits Malayalam Малаялам Thumbnail View Изглед с миниатюри Thumbnails: Миниатюри: Tile Мозайка + Tile All Vertically Всички в мозайка вертикално + Tile All Horizontally Всички в мозайка хоризонтално + 2-Up Layout Подредба по 2 + 3-Up Layout Подредба по 3 + 4-Up Layout Подредба по 4 + 6-Up Layout Подредба по 6 + Arrange Documents Подреждане на документите Tile Edge Color Цвят на ръба на плочката Tile Edge Color… Цвят на ръба на плочката… Tile Full Pages Покриване на цели страници @@ -4045,6 +4132,8 @@ digits Malayalam Малаялам V Spacing: В. разстояние: V: В: Variable Width Profile Профил с променлива ширина + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Четката на щриха запазва собствения си размер, затова профилът на ширината не го променя. Премахнете четката, за да използвате профил. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Четката на щриха запазва собствения си размер, затова профилът на ширината не го променя. Премахнете четката, за да използвате профил. Variables Променливи New Variable Нова променлива Delete Variable Изтриване на променлива @@ -4109,7 +4198,7 @@ digits Malayalam Малаялам Vertical: Вертикално: Very High Много високо View Изглед - View Artboard Only Преглед само на работна област + View Artboard Contents Only Преглед само на съдържанието на работната област View Opacity Mask Преглед на маска за непрозрачност View PDF after saving Преглед на PDF след запазване View {n} Изглед {n} @@ -4318,6 +4407,7 @@ imageTrace Outline Контур Bevel Фаска Offset Отстъп Axis Ос + Axis Angle Ъгъл на оста axis Horizontal Хоризонтално axis Vertical Вертикално axis Both И двете @@ -4375,6 +4465,13 @@ axis Both И двете Show External Script Warning Показвай предупреждение за външни скриптове A Script Is Running Изпълнява се скрипт Script Alert Известие от скрипт + Script File Access Достъп на скрипт до файлове + The script asks to read a file you choose. Скриптът иска да прочете файл, който изберете. + The script asks to read and write a file you choose. Скриптът иска да чете и записва файл, който изберете. + The script asks to read and write a folder you choose, with everything in it. Скриптът иска да чете и записва папка, която изберете, с цялото ѝ съдържание. + Allow Once Разреши веднъж + Always Allow This Script Винаги разрешавай този скрипт + Deny Откажи A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Скриптът може да променя отворените документи и да записва файлове чрез командите, които изпълнява. Изпълнявайте само скриптове, на които имате доверие. Do not show this warning again Не показвай повече това предупреждение Stop the script and undo what it did? Then quit again. Да се спре ли скриптът и да се отменят ли промените му? След това излезте отново. @@ -4583,6 +4680,7 @@ axis Both И двете @msg choose a folder to export to изберете папка за експортиране @msg choose a location for the package изберете местоположение за пакета @msg clipboard is empty клипбордът е празен +@msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: поне един цвят трябва да остане в цветовата таблица @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` не е цвят като "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: най-много {MAX_TABLE} цвята @msg command `{0}` is not available right now: {1} команда `{0}` не е налична в момента: {1} @@ -4737,6 +4835,9 @@ axis Both И двете @msg no such user library няма такава потребителска библиотека @msg no such view няма такъв изглед @msg no such width point няма такава точка за ширина +@msg `single` must be `incoming` or `outgoing` `single` трябва да е `incoming` или `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` и `outIndex` трябва да са двете половини на една прекъсната точка за ширина +@msg a discontinuous width point keeps its place прекъснатата точка за ширина запазва мястото си @msg no swatch `{name}` няма образец `{name}` @msg no swatch library `{l}` (see swatch.library.list) няма библиотека с образци `{l}` (вижте swatch.library.list) @msg no symbol instances selected няма избрани екземпляри на символ @@ -5009,6 +5110,9 @@ axis Both И двете @msgplural Discarded {n} recovered document|Discarded {n} recovered documents Изхвърлен е {n} възстановен документ|Изхвърлени са {n} възстановени документа @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them Възстановен е {n} документ: запазете го, за да го съхраните|Възстановени са {n} документа: запазете ги, за да ги съхраните @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} Отворено с {n} бележка: {first}|Отворено с {n} бележки: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Копирано с {n} бележка: {first}|Копирано с {n} бележки: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Изрязано с {n} бележка: {first}|Изрязано с {n} бележки: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Трасирано с {n} бележка: {first}|Трасирано с {n} бележки: {first} @msgplural {notice}. Opened with {n} note: {first}|{notice}. Opened with {n} notes: {first} {notice}. Отворено с {n} бележка: {first}|{notice}. Отворено с {n} бележки: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} {path} е запазен с {n} бележка: {first}|{path} е запазен с {n} бележки: {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first Вградено е {n} изображение; {missing} липсват: първо ги свържете наново|Вградени са {n} изображения; {missing} липсват: първо ги свържете наново @@ -5383,6 +5487,7 @@ lighting Light Светлина @msg missing panel layout липсващо оформление на панели @msg unsupported native docking operation неподдържана вградена операция за скачване Linux Display Server Дисплейен сървър за Linux + Low-Latency Drawing Рисуване с ниско забавяне X11 (XWayland) When a Pen Is Attached X11 (XWayland) при свързана писалка If a drawing tablet's pen doesn't draw, choose an X11 (XWayland) option. Ако писалката на графичния таблет не рисува, изберете опция X11 (XWayland). X11 (XWayland) X11 (XWayland) @@ -5435,6 +5540,7 @@ lighting Light Светлина Cove Извивка Depth Дълбочина Front Отпред + Side Страна Isometric Bottom Изометрично отдолу Isometric Left Изометрично отляво Isometric Right Изометрично отдясно @@ -5882,6 +5988,7 @@ lighting Light Светлина of от sRGB IEC61966-2.1 sRGB IEC61966-2.1 x Height Височина на x + Em Box Height Височина на квадратната касетка ▾ Default Actions ▾ Действия по подразбиране ⚠ {chord} was already used by {names} — it has been removed there. Внимание: Комбинацията {chord} вече се използва от {names} — премахната е там. @id file.close Затваряне @@ -6062,6 +6169,8 @@ theme Appearance Външен вид Reset Tracking and Kerning Нулиране на разредката и кернинга Reset Horizontal Scale Нулиране на хоризонталния мащаб Highlight Font Name Маркиране на името на шрифта + Highlight Font Size Маркиране на размера на шрифта + Other… Друг… Highlight Kerning Маркиране на кернинга Highlight Tracking Маркиране на разредката @msg span must be "object" or "selection", got {v} span трябва да е "object" или "selection", а не {v} @@ -6687,6 +6796,12 @@ anchor Points: Точки: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` трябва да е "free", "keepAngles" или "symmetric" @msg `{key}` must be [x, y] `{key}` трябва да е [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Преобразувател на мерни единици + Unit Converter Panel Панел „Преобразувател на мерни единици“ + Copy with Units Копиране с мерните единици + From Selection От селекцията + # Color Effects add-on: Select by Color Kind. Select by Color Kind Избиране по вид цвят Objects with Spot Colors Обекти с плакатни цветове @@ -6889,6 +7004,14 @@ breakText Glyphs Глифи Remove Gaps Премахване на разстоянията @msg that makes too many pieces (at most 100000): make the dashes longer така се получават твърде много части (най-много 100000): удължете тиретата @msg select paths, or segments, to divide изберете пътища или сегменти за разделяне +# Path Precision Tools add-on: Smooth Bridge. + Smooth Bridge… Плавен мост… + Smooth Bridge Плавен мост + Keep Originals Запазване на оригиналите +@msg select two circles to bridge изберете два кръга за свързване +@msg one circle is inside the other единият кръг е вътре в другия +@msg the circles are too far apart for this radius: raise the radius кръговете са твърде далеч един от друг за този радиус: увеличете радиуса +@msg the circles are too far apart for this radius кръговете са твърде далеч един от друг за този радиус # Path Precision Tools add-on: Common Tangents. Common Tangents… Общи допирателни… Common Tangents Общи допирателни @@ -7236,4 +7359,14 @@ breakText Glyphs Глифи @msg A panel is not joined to the rest by a crease. Панел не е свързан с останалите с линия за биговане. @msg A fold line is on a non-printing layer. Линия на сгъване е на слой, който не се печата. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Панели: {panels}, панти: {hinges}, грешки: {errors}, предупреждения: {warnings} + Fold Preview Преглед на сгъването + Fold Сгъване + Show Fold Lines Покажи линиите на сгъване + Three-Quarter Три четвърти + Open a document to preview its folded shape. Отворете документ, за да прегледате сгънатата му форма. +@msg Check the fold lines first. Първо проверете линиите на сгъване. +@msg Panels: {panels}, hinges: {hinges} Панели: {panels}, панти: {hinges} +@msg Other blanks not shown: {count} Други разкрои не са показани: {count} +@msg A joint does not close by {gap} pt. Една връзка не се затваря с {gap} pt. +@msg Two panels pass through each other. Два панела минават един през друг. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer трябва да е "singleLine", "everyLine", "standardSingleLine" или "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 99f23d313c..8c1e89f56c 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -64,6 +64,8 @@ Check Script Provjeri skriptu Some scripts were not listed Neke skripte nisu navedene The Scripts folder cannot be read Folder Scripts se ne može pročitati + Loading scripts… Učitavanje skripti… + The Scripts folder is still being read Folder Scripts se još čita Other Script… Druga skripta… Document Setup… Postavke dokumenta… Switch Units Promijeni jedinice @@ -167,6 +169,8 @@ Shear… Smicanje… Transform Each… Transformiši svaki… Reset Bounding Box Vrati granični okvir na početno + Rotate Bounding Box Rotiraj granični okvir + Rotate Bounding Box… Rotiraj granični okvir… Arrange Rasporedi Bring to Front Postavi na vrh Bring Forward Pomakni naprijed @@ -706,6 +710,13 @@ Previous Document Prethodni dokument Cascade Kaskadno Tile Popločaj + Tile All Vertically Popločaj sve okomito + Tile All Horizontally Popločaj sve vodoravno + 2-Up Layout Raspored po 2 + 3-Up Layout Raspored po 3 + 4-Up Layout Raspored po 4 + 6-Up Layout Raspored po 6 + Arrange Documents Rasporedi dokumente Float in Window Odvoji u prozor Float All in Windows Odvoji sve u prozore Consolidate All Windows Objedini sve prozore @@ -752,6 +763,11 @@ Saturation and brightness Zasićenje i svjetlina Color field Polje boje {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Prikaz kotača + Box View Prikaz kvadrata + Box Channel Kanal kvadrata + Color box Kvadrat boje + Color Wheel Options Opcije kotača boja CSS Properties CSS svojstva Document Info Informacije o dokumentu Flattener Preview Pregled spljoštavanja @@ -1503,7 +1519,7 @@ lighting Light Svjetlo Vertical Type Okomiti tekst Warp Tool Alat za iskrivljenje Width Tool Alat širina - Wrinkle Tool Alat za nabiranje + Wrinkle Tool Alat za nabore Zoom Tool Alat za zumiranje Action {n} Akcija {n} Begin Recording Započni snimanje @@ -1519,6 +1535,7 @@ lighting Light Svjetlo Play Current Selection Reprodukuj trenutni odabir Save Actions… Sačuvaj akcije… Load Actions… Učitaj akcije… + Replace Actions… Zamijeni akcije… Reset Actions Vrati akcije na početno Replace the current actions with the default set? Zamijeniti trenutne akcije zadanim skupom? Append adds the default set after the current sets instead. Dugme Dodaj umjesto toga dodaje zadani skup iza trenutnih skupova. @@ -1693,6 +1710,7 @@ digits Malayalam Malajalam Underline Podvučeno Vertical Scale % Okomita skala % Axis Osa + Axis Angle Ugao ose ICF Top/Right ICF vrh/desno ICF Bottom/Left ICF dno/lijevo Show Font Height Options Prikaži opcije visine fonta @@ -1735,6 +1753,7 @@ digits Malayalam Malajalam Rule: Pravilo: Save changes to {name} Sačuvaj promjene u {name} Save theme to My Themes Sačuvaj temu u Moje teme + Set the current fill or stroke to the selected color Postavi odabranu boju kao trenutnu ispunu ili potez Set the selected color to the current color Postavi odabranu boju na trenutnu boju Copy All Styles Kopiraj sve stilove Exported {path} Izvezeno: {path} @@ -2047,7 +2066,7 @@ digits Malayalam Malajalam Stroke: click for swatches, Shift-click for the color mixer Potez: kliknite za uzorke boja, Shift-klik za mikser boja This panel is on the roadmap (see the parity plan). Ovaj panel je u planu (vidi plan usklađenosti). Open a document to navigate it. Otvorite dokument da se krećete kroz njega. - View Artboard Only Prikaži samo radnu ploču + View Artboard Contents Only Prikaži samo sadržaj radne ploče Contextual Alternates Kontekstualne alternative Default Figure Zadane brojke Discretionary Ligatures Diskrecione ligature @@ -2197,7 +2216,7 @@ digits Malayalam Malajalam Overprint Preview (separations) Pregled pretiska (separacije) Show All Plates Prikaži sve ploče Show all plates Prikaži sve ploče - Show/hide plate (Alt-click: only this plate) Prikaži/sakrij ploču (Alt-klik: samo ova ploča) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Prikaži/sakrij ploču (Alt-klik: samo ova ploča; ponovni Alt-klik: sve ploče) Simulate Paper Simuliraj papir Use Black Point Compensation Koristi kompenzaciju crne tačke Working CMYK (don't tag) Radni CMYK (bez oznake) @@ -2237,6 +2256,8 @@ digits Malayalam Malajalam Tip extends past the end point Vrh prelazi preko krajnje tačke Tip on the end point Vrh na krajnjoj tački Variable Width Profile Profil promjenjive širine + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Četkica poteza zadržava vlastitu veličinu, pa je profil širine ne mijenja. Uklonite četkicu da biste koristili profil. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Četkica poteza zadržava vlastitu veličinu, pa je profil širine ne mijenja. Uklonite četkicu da biste koristili profil. Weight: Debljina: Art using a deleted global swatch keeps its colour. Crtež koji koristi izbrisani globalni uzorak boje zadržava svoju boju. Color Group: {name} Grupa boja: {name} @@ -2346,6 +2367,10 @@ digits Malayalam Malajalam Flip Horizontal Preokreni vodoravno Flip Vertical Preokreni okomito Polygon Properties: Svojstva mnogougla: + Line Properties: Svojstva linije: + Line Length: Dužina linije: + Line Angle: Ugao linije: + Constrain Pie Angle Zadrži ugao pite Rectangle Properties: Svojstva pravougaonika: Shape Properties: Svojstva oblika: Shape Properties Svojstva oblika @@ -2387,6 +2412,7 @@ digits Malayalam Malajalam Scatter: Raspršenost: Rotation: Rotacija: Rotation relative to: Rotacija u odnosu na: + Hue Jitter: Variranje nijanse: Brush Scale Options Opcije skale četkice Scale Proportionately Skaliraj proporcionalno Stretch to Fit Stroke Length Razvuci da stane u dužinu poteza @@ -2425,6 +2451,7 @@ digits Malayalam Malajalam Size: Veličina: Calligraphic Brush Options Opcije kaligrafske četkice Bristle Brush Options Opcije četkice s čekinjama + Roundness Zaobljenost Roundness: Zaobljenost: Shape: Oblik: Bristle Length: Dužina čekinja: @@ -2749,6 +2776,7 @@ digits Malayalam Malajalam BLANK DOCUMENT PRESETS PREDLOŠCI PRAZNIH DOKUMENATA Bleed Napust Change to Right-to-Left Layout Prebaci na raspored s desna nalijevo + Columns Kolone Columns: Kolone: Documents you create appear here. Dokumenti koje kreirate pojavljuju se ovdje. More Settings Više postavki @@ -2883,6 +2911,9 @@ digits Malayalam Malajalam Open a document to preview its pages Otvorite dokument da pregledate njegove stranice Output › Mode Izlaz › Način Overprint and Transparency Flattener Options Opcije pretiska i spljoštavanja prozirnosti + Custom… Prilagođeno… + Custom Transparency Flattener Options Prilagođene opcije spljoštavanja prozirnosti + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS nema alfa prozirnost, a Pretisci određuju da li se pretisci zadržavaju. Place the pages with the placement again Ponovo postavi stranice s postavljanjem Placement: Postavljanje: Preserve CMYK Numbers Očuvaj CMYK brojeve @@ -2931,14 +2962,19 @@ digits Malayalam Malajalam Around Object Oko objekta Background: Pozadina: Changing these settings changes how raster effects look when exported, flattened or expanded. Promjena ovih postavki mijenja izgled rasterskih efekata pri izvozu, spljoštavanju ili proširivanju. + Add Around Dodaj oko objekta + Anti Alias Zaglađivanje ivica + Color Model Model boja Color Model: Model boja: Create Clipping Mask Kreiraj masku isijecanja Preserve Spot Colors Očuvaj spot boje + Resolution Rezolucija Resolution: Rezolucija: Transparent Prozirno Layout Order: Redoslijed rasporeda: Change to Left-to-Right Layout Prebaci na raspored s lijeva nadesno Artboards: {n} Radne ploče: {n} + Rows Redovi Rows: Redovi: Assign Dodijeli Color Group: Grupa boja: @@ -3087,6 +3123,8 @@ antiAlias Sharp Oštro Every option matches {base}. Sve opcije odgovaraju {base}. Files of a PDF standard can't be password-protected. Datoteke PDF standarda ne mogu se zaštititi lozinkom. Files of this standard tag their colours with ICC profiles. Datoteke ovog standarda označavaju svoje boje ICC profilima. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Datoteke ovog standarda označavaju svoje boje ICC profilima, osim CMYK boja u profilu izlazne namjene, koje se zapisuju kao DeviceCMYK. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. Uz „Ne uključuj profile“ i CMYK izlaznu namjenu, svaka CMYK boja zapisuje se kao DeviceCMYK, osim ako se ne pretvori u CMYK odredište s drugim profilom. Flattener preset: Predložak spljoštavanja: General › Thumbnails Općenito › Sličice Grayscale images Slike u nijansama sive @@ -3300,6 +3338,12 @@ antiAlias Sharp Oštro LF (macOS, Linux) LF (macOS, Linux) CRLF (Windows) CRLF (Windows) Text Export Options Opcije izvoza teksta + Chinese Big 5 Kineski Big 5 + Cyrillic Ćirilica + Greek Grčki + Turkish Turski + Baltic Baltički + Central European Srednjoevropski Character Set: Skup znakova: Join the lines of each paragraph Spoji redove svakog pasusa Line Breaks Prelomi reda @@ -3329,6 +3373,9 @@ antiAlias Sharp Oštro Variable Options Opcije varijable Define a variable first Prvo definišite varijablu Adjust Adjoining Width Points Podesi susjedne tačke širine + Incoming Ulazna + Outgoing Izlazna + Single Width Only Samo jedna širina Keep both sides the same width Zadrži obje strane iste širine Side 1: Strana 1: Side 2: Strana 2: @@ -3434,9 +3481,13 @@ theme Appearance Izgled Break Link to Symbol Prekini vezu sa simbolom Brush Definition Definicija četkice Brush Options… Opcije četkice… + Options of Selected Object… Opcije odabranog objekta… + Options of Selected Object Opcije odabranog objekta Current Brush Trenutna četkica Current Symbol Trenutni simbol Delete Brush Izbriši četkicu + Delete Color Izbriši boju + Restore Generated Table Vrati generisanu tabelu Delete Symbol Izbriši simbol Delete the selected symbol? Izbrisati odabrani simbol? Delete the selected symbols? Izbrisati odabrane simbole? @@ -3561,6 +3612,11 @@ theme Appearance Izgled Objects Objekti Paths Putanje Path Length Dužina putanje + Grid Size Veličina mreže + Grid Colors Boje mreže + Flattener Preset Predložak spljoštavanja + X X + Y Y Add Guide Dodaj vodilicu Edit Selection Uredi odabir Recall Selection Vrati odabir @@ -3711,6 +3767,7 @@ theme Appearance Izgled Select Art Odaberi crtež Set Current Layer Postavi trenutni sloj Flatten Artwork Spljošti crtež + Locate Layer Pronađi sloj Locate Object Pronađi objekat Lock Others Zaključaj ostale Merge Selected Spoji odabrano @@ -3887,6 +3944,7 @@ theme Appearance Izgled 90° & 45° Angles Uglovi od 90° i 45° 90° Angles Uglovi od 90° Additional Plug-ins Folder Dodatni folder dodataka + Plug-in Instruction Budget Budžet instrukcija za dodatke Additional Fonts Folder Dodatni folder fontova Alignment Guides Vodilice za poravnanje Anchor Points, Handle, and Bounding Box Display Prikaz sidrenih tačaka, ručki i graničnog okvira @@ -3913,6 +3971,7 @@ theme Appearance Izgled Data Recovery Oporavak podataka Default Language Zadani jezik Disable Auto Add/Delete Onemogući automatsko dodavanje/brisanje + Interpolate Control Points When Moving Anchors Interpoliraj ručke smjera pri pomjeranju sidrenih tačaka Display All Blacks Accurately Prikaži sve crne tačno Display All Blacks as Rich Black Prikaži sve crne kao bogatu crnu Display Bitmaps as Anti-aliased Images in Pixel Preview Prikaži bitmape kao slike sa zaglađenim ivicama u pregledu piksela @@ -3929,6 +3988,7 @@ theme Appearance Izgled Enable Rubber Band for Omogući gumenu traku za Enable Touch Gestures Omogući pokrete dodirom Switch Selection and Drawing Modes Prebaci između načina odabira i crtanja + Select Last Selection Tool Odaberi posljednji alat za odabir Enable Touch Workspace Omogući radni prostor za dodir English: UK Engleski: UK Every (minutes) Svakih (minuta) @@ -4012,6 +4072,7 @@ theme Appearance Izgled Printing / Exporting Štampanje / izvoz Real-time Drawing and Editing Crtanje i uređivanje u stvarnom vremenu Use Monitor Profile for Canvas Koristi profil monitora za platno + Refresh Monitor Profile Osvježi profil monitora The canvas is drawn in sRGB. Platno se iscrtava u sRGB-u. Canvas display profile: Profil ekrana za platno: The system matches the window to the display's colors. Sistem prilagođava boje prozora ekranu. @@ -4073,6 +4134,7 @@ theme Appearance Izgled Scroll Sideways with Cmd/Ctrl + Wheel Pomjeraj vodoravno uz Cmd/Ctrl + točkić miša Scrub Numeric Fields by Dragging Mijenjaj numerička polja prevlačenjem Linux Display Server Linux server prikaza + Low-Latency Drawing Crtanje s malim kašnjenjem Print Preview Pregled štampanja Print Setup Podešavanje štampe Bitmap Bitmapa @@ -4281,6 +4343,8 @@ axis Both Obje Reset Tracking and Kerning Vrati razmak slova i podrezivanje na početno Reset Horizontal Scale Vrati vodoravnu skalu na početno Highlight Font Name Istakni naziv fonta + Highlight Font Size Istakni veličinu fonta + Other… Druga… Highlight Kerning Istakni podrezivanje Highlight Tracking Istakni razmak slova Step Type Vrsta koraka @@ -4416,6 +4480,9 @@ font-technology Variable Varijabilni Search commands, tools, panels and effects… Pretraži naredbe, alate, panele i efekte… No commands match Nijedna naredba se ne podudara {pos} of {total}: {name} {pos} od {total}: {name} + No menu item Nema stavke menija + Toolbar Traka s alatima + {toolbar}, in the {tool} group {toolbar}, u grupi {tool} @plural {n} result|{n} results {n} rezultat|{n} rezultata|{n} rezultata @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} od {n} rezultata. Nastavite kucati da ih suzite.|{shown} od {n} rezultata. Nastavite kucati da ih suzite.|{shown} od {n} rezultata. Nastavite kucati da ih suzite. Recent Commands Nedavne naredbe @@ -4452,6 +4519,7 @@ font-technology Variable Varijabilni The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Točkić miša uz pritisnut Cmd/Ctrl pomjera platno u stranu. Dragging sideways on a numeric field's label changes the field's value. Prevlačenje u stranu po oznaci brojčanog polja mijenja vrijednost polja. A two-finger rotate gesture on a trackpad rotates the canvas view. Pokret rotacije s dva prsta na dodirnoj podlozi rotira prikaz platna. + When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Kada pomjerate sidrene tačke, svaka kriva s jednim pomjerenim krajem zadržava svoj oblik u odnosu na svoje krajeve. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Držanje prečice alata bira taj alat dok je ne pustite, a zatim se ponovo bira prethodni alat. Shows the bounding box while you move the selection or draw a shape. Prikazuje granični okvir dok pomjerate odabir ili crtate oblik. Create Trim Marks draws Japanese-style marks instead of Roman ones. Kreiraj oznake za obrezivanje crta oznake u japanskom stilu umjesto rimskih. @@ -4482,6 +4550,29 @@ font-technology Variable Varijabilni The unit for East Asian type measurements, which no field uses yet. Jedinica za mjere istočnoazijskog teksta, koju još nijedno polje ne koristi. When on, a number typed without a unit into a field in picas is read in points. Kad je uključeno, broj unesen bez jedinice u polje u picama čita se u tačkama. With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options. Uz XML ID nazivi objekata prikazuju se kao XML ID u Slojevima, Varijablama i Opcijama sloja. + The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl. Korak za veličinu teksta i prored: Cmd/Ctrl+Shift+. i Cmd/Ctrl+Shift+, mijenjaju veličinu za jedan korak, a uz Alt za pet; u horizontalnom tekstu Alt sa strelicom gore ili dolje mijenja prored za jedan korak, a uz Cmd/Ctrl za pet. + The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl. Korak za razmak slova i kerning, u hiljaditim dijelovima em: u horizontalnom tekstu Alt sa strelicom lijevo ili desno mijenja kerning kod kursora ili razmak slova odabranog teksta za jedan korak, a uz Cmd/Ctrl za pet. + The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. Korak za pomak osnovne linije: u horizontalnom tekstu Alt i Shift sa strelicom gore ili dolje pomjeraju osnovnu liniju za jedan korak, a uz Cmd/Ctrl za pet. + Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. Prikazuje opcije za japanski i drugi istočnoazijski tekst u panelima Znak, Pasus, OpenType i Glifovi te naredbu Kompozitni fontovi. + Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. Prikazuje opcije za arapski, hebrejski i indijski tekst u panelima Znak i Pasus, kao što su smjer pasusa, kašide i cifre. + The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. Alati za odabir biraju tekst samo na njegovoj osnovnoj liniji, okviru teksta u području ili njegovoj putanji, a ne bilo gdje unutar njegovog okvira. + Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. Meniji fontova prikazuju svaki font pod engleskim nazivom; kad je isključeno, font koji ima i naziv na svom jeziku prikazuje taj naziv. + New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. Novi tekst u području počinje s uključenom automatskom veličinom, pa pravougaoni okvir horizontalnog teksta raste ili se smanjuje po visini prema svom tekstu. + Font lists and the Type › Font menu show a sample of each font beside its name. Liste fontova i meni Font prikazuju uzorak svakog fonta pored njegovog naziva. + Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on. Uzorci fontova crtaju se tamnim tekstom na bijelom, bez obzira na svjetlinu interfejsa; to važi samo dok su pregledi fontova u menijima uključeni. + How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is. Koliko je visok svaki red u listama polja za font, na primjer u panelu Znak, a time i koliko je velik svaki uzorak. + How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first. Koliko posljednje korištenih fontova, od 1 do 15, prikazuju Nedavni fontovi i liste fontova, najnoviji prvi. + When you change the font or font style of text, characters the new font has no glyph for keep the font they had. Kad promijenite font ili stil fonta teksta, znakovi za koje novi font nema glif zadržavaju font koji su imali. + A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export. Ružičasto isticanje na platnu označava glifove koje su zamijenile OpenType funkcije, kao što su ligature; ne štampa se i ne izvozi. + With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from. S alatom za tekst odabir jednog znaka prikazuje pored njega na platnu red njegovih alternativnih glifova za izbor. + A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export. Ružičasto isticanje na platnu označava tekst nacrtan zamjenskim fontom jer njegov font nedostaje; ne štampa se i ne izvozi. + New type made with a Type tool starts with placeholder text, selected, so typing replaces it. Novi tekst napravljen alatom za tekst počinje odabranim tekstom čuvara mjesta, koji kucanje zamjenjuje. + Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list. Kucanje oznake liste, kao što je 1. ili *, a zatim razmaka na početku pasusa pretvara pasus u listu. + Fonts in this folder show in the font menus and can be used without being installed. Fontovi u ovoj mapi prikazuju se u menijima fontova i mogu se koristiti bez instaliranja. + Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows. Primjena grafičkog stila na tekst uklanja vlastitu ispunu ili potez znakova gdje ga stil ima, tako da se vidi boja stila. + Align and Distribute measure point type by the ink of its glyphs instead of its em box. Poravnaj i Rasporedi mjere tekst u tački prema tinti njegovih glifova umjesto prema njegovom em okviru. + Align and Distribute measure area type by the ink of its glyphs instead of its frame. Poravnaj i Rasporedi mjere tekst u području prema tinti njegovih glifova umjesto prema njegovom okviru. + The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box. Granični okvir i panel Transformiši mjere tekst u tački prema tinti njegovih glifova umjesto prema njegovom em okviru. Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply. Priljepljuje crtanje, pomicanje i skaliranje uz podjele mreže, čak i dok je mreža skrivena; dok je uključeno, „Prilijepi uz piksel“ se ne primjenjuje. The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead. Boja vodilica koje nisu odabrane; radna ploča s „Oznakom vodilica“ crta svoje vodilice u boji oznake. Draws guides as solid lines or as dots, including the guides already in the document. Crta vodilice kao pune linije ili kao tačke, uključujući vodilice koje su već u dokumentu. @@ -4525,6 +4616,8 @@ font-technology Variable Varijabilni Couldn't paste from the clipboard: {e} Nije moguće zalijepiti iz međuspremnika: {e} Channel Kanal Circle Krug + Circle Tool Alat za krug + Circle too large Krug je prevelik Clip to Art Isijeci prema crtežu Colorize Oboji Gamma Gama @@ -4753,6 +4846,13 @@ imageTrace Outline Obris Show External Script Warning Prikaži upozorenje za vanjske skripte A Script Is Running Skripta se izvršava Script Alert Upozorenje skripte + Script File Access Pristup skripte datotekama + The script asks to read a file you choose. Skripta traži da pročita datoteku koju odaberete. + The script asks to read and write a file you choose. Skripta traži da čita i piše datoteku koju odaberete. + The script asks to read and write a folder you choose, with everything in it. Skripta traži da čita i piše folder koji odaberete, sa svim što je u njemu. + Allow Once Dozvoli jednom + Always Allow This Script Uvijek dozvoli ovu skriptu + Deny Odbij A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Skripta može mijenjati otvorene dokumente i pisati datoteke putem naredbi koje pokreće. Pokrećite samo skripte kojima vjerujete. Do not show this warning again Ne prikazuj više ovo upozorenje Stop the script and undo what it did? Then quit again. Zaustaviti skriptu i poništiti ono što je uradila? Zatim ponovo izađite. @@ -4880,6 +4980,8 @@ imageTrace Outline Obris @msg `{min_key}` is greater than `{max_key}` `{min_key}` je veće od `{max_key}` @msg give at least one of `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` navedite barem jedno od `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` mora biti grayscale, rgb, hsb, cmyk ili websafe +@msg `view` must be wheel or box `view` mora biti wheel ili box +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` mora biti hue, saturation, brightness, red, green ili blue @msg `{k}` must be [x, y] `{k}` mora biti [x, y] @msg `{name}` has no options `{name}` nema opcija @msg `{name}` is a built-in workspace; choose another name `{name}` je ugrađeni radni prostor; odaberite drugi naziv @@ -4986,6 +5088,7 @@ imageTrace Outline Obris @msg choose a folder to export to odaberite folder za izvoz @msg choose a location for the package odaberite lokaciju za paket @msg clipboard is empty međuspremnik je prazan +@msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: barem jedna boja mora ostati u tabeli boja @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` nije boja poput "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: najviše {MAX_TABLE} boja @msg command `{0}` is not available right now: {1} naredba `{0}` trenutno nije dostupna: {1} @@ -5144,6 +5247,9 @@ imageTrace Outline Obris @msg no such user library nema takve korisničke biblioteke @msg no such view nema takvog pogleda @msg no such width point nema takve tačke širine +@msg `single` must be `incoming` or `outgoing` `single` mora biti `incoming` ili `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` i `outIndex` moraju biti dvije polovine jedne isprekidane tačke širine +@msg a discontinuous width point keeps its place isprekidana tačka širine zadržava svoje mjesto @msg no swatch `{name}` nema uzorka boje `{name}` @msg no swatch library `{l}` (see swatch.library.list) nema biblioteke uzoraka boja `{l}` (vidi swatch.library.list) @msg no symbol instances selected nisu odabrane instance simbola @@ -5428,6 +5534,9 @@ imageTrace Outline Obris @msgplural Discarded {n} recovered document|Discarded {n} recovered documents Odbačen {n} oporavljeni dokument|Odbačena {n} oporavljena dokumenta|Odbačeno {n} oporavljenih dokumenata @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them Vraćen {n} oporavljeni dokument; sačuvajte ga da ga zadržite|Vraćena {n} oporavljena dokumenta; sačuvajte ih da ih zadržite|Vraćeno {n} oporavljenih dokumenata; sačuvajte ih da ih zadržite @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} Otvoreno s {n} bilješkom: {first}|Otvoreno s {n} bilješke: {first}|Otvoreno s {n} bilješki: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Kopirano s {n} bilješkom: {first}|Kopirano s {n} bilješke: {first}|Kopirano s {n} bilješki: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Izrezano s {n} bilješkom: {first}|Izrezano s {n} bilješke: {first}|Izrezano s {n} bilješki: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Slika praćena s {n} bilješkom: {first}|Slika praćena s {n} bilješke: {first}|Slika praćena s {n} bilješki: {first} @msgplural {notice}. Opened with {n} note: {first}|{notice}. Opened with {n} notes: {first} {notice}. Otvoreno s {n} bilješkom: {first}|{notice}. Otvoreno s {n} bilješke: {first}|{notice}. Otvoreno s {n} bilješki: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} Sačuvano {path} s {n} bilješkom: {first}|Sačuvano {path} s {n} bilješke: {first}|Sačuvano {path} s {n} bilješki: {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first Ugrađena je {n} slika; nedostaje {missing}: prvo ih ponovo povežite|Ugrađene su {n} slike; nedostaje {missing}: prvo ih ponovo povežite|Ugrađeno je {n} slika; nedostaje {missing}: prvo ih ponovo povežite @@ -5817,6 +5926,7 @@ imageTrace Outline Obris Ascent Uspon Cap Height Visina velikih slova x Height Visina malog slova x + Em Box Height Visina em okvira Justify Poravnaj obostrano First Baseline Prva osnovna linija Vertical Align Okomito poravnanje @@ -5950,6 +6060,7 @@ mark-style Japanese Japanski Cove Udubina Depth Dubina Front Prednja strana + Side Bočna strana Isometric Bottom Izometrijsko dno Isometric Left Izometrijski lijevo Isometric Right Izometrijski desno @@ -6942,6 +7053,14 @@ shape Open Otvoren Remove Gaps Ukloni razmake @msg that makes too many pieces (at most 100000): make the dashes longer to daje previše dijelova (najviše 100000): produžite crtice @msg select paths, or segments, to divide odaberite putanje ili segmente za dijeljenje +# Path Precision Tools add-on: Smooth Bridge. + Smooth Bridge… Glatki most… + Smooth Bridge Glatki most + Keep Originals Zadrži originale +@msg select two circles to bridge odaberite dva kruga za premošćavanje +@msg one circle is inside the other jedan krug je unutar drugog +@msg the circles are too far apart for this radius: raise the radius krugovi su predaleko jedan od drugog za ovaj radijus: povećajte radijus +@msg the circles are too far apart for this radius krugovi su predaleko jedan od drugog za ovaj radijus # Path Precision Tools add-on: Common Tangents. Common Tangents… Zajedničke tangente… Common Tangents Zajedničke tangente @@ -7068,6 +7187,11 @@ shape Open Otvoren Create Swatch Legend… Kreiraj legendu uzoraka boja… HEX HEX Help Bar Traka pomoći +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Pretvarač jedinica + Unit Converter Panel Panel Pretvarač jedinica + Copy with Units Kopiraj s jedinicama + From Selection Iz odabira # Type Tools add-on (Object › Plug-ins › Type Tools). Type Tools Alati za tekst Text Tweaker… Podešavanje teksta… @@ -7290,4 +7414,14 @@ shape Open Otvoren @msg A panel is not joined to the rest by a crease. Panel nije povezan s ostatkom nijednom linijom bigovanja. @msg A fold line is on a non-printing layer. Linija savijanja je na sloju koji se ne štampa. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneli: {panels}, šarke: {hinges}, greške: {errors}, upozorenja: {warnings} + Fold Preview Pregled savijanja + Fold Savijanje + Show Fold Lines Prikaži linije savijanja + Three-Quarter Tri četvrtine + Open a document to preview its folded shape. Otvorite dokument da pregledate njegov savijeni oblik. +@msg Check the fold lines first. Prvo provjerite linije savijanja. +@msg Panels: {panels}, hinges: {hinges} Paneli: {panels}, šarke: {hinges} +@msg Other blanks not shown: {count} Ostali krojevi nisu prikazani: {count} +@msg A joint does not close by {gap} pt. Spoj se ne zatvara za {gap} pt. +@msg Two panels pass through each other. Dva panela prolaze jedan kroz drugi. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer mora biti "singleLine", "everyLine", "standardSingleLine" ili "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index c54311799d..ae39014e79 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -186,6 +186,7 @@ Add Anchor Point Afegeix un punt d’ancoratge Add Anchor Point Tool Eina d’afegir un punt d’ancoratge Add Anchor Points Afegeix punts d’ancoratge + Add Around Afegeix al voltant de l’objecte Add Content Afegeix contingut Add Effect Afegeix un efecte Add Event Afegeix un esdeveniment @@ -222,7 +223,11 @@ Add Used Colors Afegeix els colors utilitzats Additional Fonts Folder Carpeta addicional de tipus de lletra Additional Plug-ins Folder Carpeta addicional de complements + Plug-in Instruction Budget Pressupost d’instruccions dels complements Adjust Adjoining Width Points Ajusta els punts d’amplada contigus + Incoming Entrant + Outgoing Sortint + Single Width Only Només una amplada Adjust Color Balance… Ajusta l’equilibri de color… Adjust Colors Ajusta els colors Adjust Options: Opcions d’ajust: @@ -296,6 +301,7 @@ Angles Angles Angular Angular Animated Zoom Zoom animat + Anti Alias Antialiàsing Anti-alias Antialiàsing Anti-Alias Antialiàsing Anti-alias Rasters Antialiàsing de ràsters @@ -434,6 +440,7 @@ antiAlias Sharp Nítid Average… Mitjana… Away from the Line Allunyat de la línia Axis Eix + Axis Angle Angle de l’eix Axis side Costat de l’eix Axis: Eix: B4 B4 @@ -583,6 +590,12 @@ antiAlias Sharp Nítid Brush Libraries Menu Menú de biblioteques de pinzells Brush Library Biblioteca de pinzells Brush Options… Opcions del pinzell… + Options of Selected Object… Opcions de l’objecte seleccionat… + Options of Selected Object Opcions de l’objecte seleccionat +@msg no path painted with a brush is selected no hi ha cap traçat pintat amb un pinzell seleccionat +@msg the selected paths are painted with brushes of different types els traçats seleccionats estan pintats amb pinzells de tipus diferents +@msg give `params` or `reset`, not both indiqueu `params` o `reset`, no tots dos +@msg a bristle brush has no options of its own on a path un pinzell de cerres no té opcions pròpies en un traçat Brush Scale Options Opcions d’escala del pinzell Brush Size Mida del pinzell Brush Strokes Traços del pinzell @@ -677,6 +690,12 @@ antiAlias Sharp Nítid Character options Opcions de caràcter Paragraph options Opcions de paràgraf Character Rotation Rotació de caràcters + Chinese Big 5 Xinès Big 5 + Cyrillic Ciríl·lic + Greek Grec + Turkish Turc + Baltic Bàltic + Central European Centreeuropeu Character Set: Joc de caràcters: Character Style Estil de caràcter Character Style Options Opcions de l’estil de caràcter @@ -700,6 +719,8 @@ antiAlias Sharp Nítid Chrome Crom Chrome… Crom… Circle Cercle + Circle Tool Eina de cercle + Circle too large El cercle és massa gran Circle (open) Cercle (obert) Classic Clàssic Classic Defaults Valors predeterminats clàssics @@ -804,6 +825,7 @@ antiAlias Sharp Nítid Color Mixer (Shift-click the chip) Mesclador de colors (Maj+clic a la mostra) Color Mode Mode de color Color Mode: Mode de color: + Color Model Model de color Color Model: Model de color: Color Models Models de color Color Panel Options Opcions del panell de color @@ -826,6 +848,11 @@ antiAlias Sharp Nítid Saturation and brightness Saturació i lluentor Color field Camp de color {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Visualització de roda + Box View Visualització de quadre + Box Channel Canal del quadre + Color box Quadre de color + Color Wheel Options Opcions de la roda de colors Color Type: Tipus de color: Color wheel Roda de color Color: Color: @@ -840,6 +867,7 @@ antiAlias Sharp Nítid Column Graph Tool Eina de gràfic de columnes Column Type: Tipus de columna: Column Width: Amplada de columna: + Columns Columnes Columns: Columnes: Column… Columna… Combine Slices Combina els talls @@ -1126,6 +1154,8 @@ antiAlias Sharp Nítid Delete Artboard Suprimeix el tauler Delete Artboards Suprimeix els taulers Delete Brush Suprimeix el pinzell + Delete Color Suprimeix el color + Restore Generated Table Restaura la taula generada Delete Character Style Suprimeix l’estil de caràcter Delete Data Set Suprimeix el conjunt de dades Delete Data Sets Suprimeix els conjunts de dades @@ -1235,6 +1265,7 @@ antiAlias Sharp Nítid Direction: Direcció: Directives Directrius Disable Auto Add/Delete Desactiva l’addició i la supressió automàtiques + Interpolate Control Points When Moving Anchors Interpola les manetes de direcció en moure punts d’ancoratge Disable Opacity Mask Desactiva la màscara d’opacitat Discard Descarta Discard Empty Type Descarta el text buit @@ -1521,6 +1552,7 @@ antiAlias Sharp Nítid Enable text access for screen readers Activa l’accés al text per als lectors de pantalla Enable Touch Gestures Activa els gestos tàctils Switch Selection and Drawing Modes Canvia entre els modes de selecció i de dibuix + Select Last Selection Tool Tria l'última eina de selecció Enable Touch Workspace Activa l’espai de treball tàctil Encoding Codificació Encoding and writing the file… S’està codificant i escrivint el fitxer… @@ -1706,6 +1738,8 @@ digits Malayalam Malaiàlam Files Fitxers Files of a PDF standard can't be password-protected. Els fitxers d’un estàndard PDF no es poden protegir amb contrasenya. Files of this standard tag their colours with ICC profiles. Els fitxers d’aquest estàndard etiqueten els colors amb perfils ICC. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Els fitxers d’aquest estàndard etiqueten els colors amb perfils ICC, excepte els colors CMYK del perfil d’intenció de sortida, que s’escriuen com a DeviceCMYK. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. Amb «No incloguis els perfils» i una intenció de sortida CMYK, cada color CMYK s’escriu com a DeviceCMYK, tret que es converteixi a una destinació CMYK d’un altre perfil. Fill Farciment Fill & Stroke Farciment i traç Fill (X), double-click for the Color Picker Farciment (X), fes doble clic per al selector de color @@ -1819,6 +1853,8 @@ digits Malayalam Malaiàlam Fonts added in the last 30 days Tipus de lletra afegits en els darrers 30 dies Font Preview Size Mida de previsualització del tipus de lletra Font Size Mida del tipus de lletra + Highlight Font Size Ressalta la mida del tipus de lletra + Other… Una altra… Font Style: Estil de tipus de lletra: Font Technology Tecnologia del tipus de lletra Font: Tipus de lletra: @@ -1856,6 +1892,7 @@ digits Malayalam Malaiàlam from the format's public description de la descripció pública del format from your earlier imports de les importacions anteriors Front Davant + Side Lateral Frosted Glaçat Full Document Document complet Full Justify Justificació completa @@ -2498,6 +2535,7 @@ digits Malayalam Malaiàlam Linked Files Fitxers enllaçats Links Enllaços Linux Display Server Servidor de pantalla de Linux + Low-Latency Drawing Dibuix de baixa latència Liquify Liquifica List Data Sets Llista els conjunts de dades List Folder Llista la carpeta @@ -2543,6 +2581,7 @@ digits Malayalam Malaiàlam Loads native code Carrega codi natiu Local Libraries Biblioteques locals Locate Library… Localitza la biblioteca… + Locate Layer Localitza la capa Locate Object Localitza l’objecte Locate Selected Objects Localitza els objectes seleccionats Location Ubicació @@ -3042,35 +3081,35 @@ digits Malayalam Malaiàlam Open password: Contrasenya d’obertura: Open Paths Traçats oberts Open Recent File 1 Obre el fitxer recent 1 - Open Recent File 10 Obre el fitxer recent 2 - Open Recent File 11 Obre el fitxer recent 3 - Open Recent File 12 Obre el fitxer recent 4 - Open Recent File 13 Obre el fitxer recent 5 - Open Recent File 14 Obre el fitxer recent 6 - Open Recent File 15 Obre el fitxer recent 7 - Open Recent File 16 Obre el fitxer recent 8 - Open Recent File 17 Obre el fitxer recent 9 - Open Recent File 18 Obre el fitxer recent 10 - Open Recent File 19 Obre el fitxer recent 11 - Open Recent File 2 Obre el fitxer recent 12 - Open Recent File 20 Obre el fitxer recent 13 - Open Recent File 21 Obre el fitxer recent 14 - Open Recent File 22 Obre el fitxer recent 15 - Open Recent File 23 Obre el fitxer recent 16 - Open Recent File 24 Obre el fitxer recent 17 - Open Recent File 25 Obre el fitxer recent 18 - Open Recent File 26 Obre el fitxer recent 19 - Open Recent File 27 Obre el fitxer recent 20 - Open Recent File 28 Obre el fitxer recent 21 - Open Recent File 29 Obre el fitxer recent 22 - Open Recent File 3 Obre el fitxer recent 23 - Open Recent File 30 Obre el fitxer recent 24 - Open Recent File 4 Obre el fitxer recent 25 - Open Recent File 5 Obre el fitxer recent 26 - Open Recent File 6 Obre el fitxer recent 27 - Open Recent File 7 Obre el fitxer recent 28 - Open Recent File 8 Obre el fitxer recent 29 - Open Recent File 9 Obre el fitxer recent 30 + Open Recent File 10 Obre el fitxer recent 10 + Open Recent File 11 Obre el fitxer recent 11 + Open Recent File 12 Obre el fitxer recent 12 + Open Recent File 13 Obre el fitxer recent 13 + Open Recent File 14 Obre el fitxer recent 14 + Open Recent File 15 Obre el fitxer recent 15 + Open Recent File 16 Obre el fitxer recent 16 + Open Recent File 17 Obre el fitxer recent 17 + Open Recent File 18 Obre el fitxer recent 18 + Open Recent File 19 Obre el fitxer recent 19 + Open Recent File 2 Obre el fitxer recent 2 + Open Recent File 20 Obre el fitxer recent 20 + Open Recent File 21 Obre el fitxer recent 21 + Open Recent File 22 Obre el fitxer recent 22 + Open Recent File 23 Obre el fitxer recent 23 + Open Recent File 24 Obre el fitxer recent 24 + Open Recent File 25 Obre el fitxer recent 25 + Open Recent File 26 Obre el fitxer recent 26 + Open Recent File 27 Obre el fitxer recent 27 + Open Recent File 28 Obre el fitxer recent 28 + Open Recent File 29 Obre el fitxer recent 29 + Open Recent File 3 Obre el fitxer recent 3 + Open Recent File 30 Obre el fitxer recent 30 + Open Recent File 4 Obre el fitxer recent 4 + Open Recent File 5 Obre el fitxer recent 5 + Open Recent File 6 Obre el fitxer recent 6 + Open Recent File 7 Obre el fitxer recent 7 + Open Recent File 8 Obre el fitxer recent 8 + Open Recent File 9 Obre el fitxer recent 9 Open Recent Files Obre fitxers recents Open Swatch Library Obre la biblioteca de mostres Open Symbol Library Obre la biblioteca de símbols @@ -3150,6 +3189,9 @@ digits Malayalam Malaiàlam Overprint Sobrimpressió Overprint and Transparency Flattener Aplanador de sobremipressió i transparència Overprint and Transparency Flattener Options Opcions de l’aplanador de sobremipressió i transparència + Custom… Personalitzat… + Custom Transparency Flattener Options Opcions personalitzades de l’aplanador de transparència + EPS has no alpha transparency, and Overprints sets whether overprints are kept. L’EPS no té transparència alfa, i Sobreimpressions determina si es conserven les sobreimpressions. Overprint Black… Sobrimpressió del negre… Overprint Fill Sobrimpressió del farciment Overprint Preview Previsualització de la sobremipressió @@ -3216,6 +3258,11 @@ digits Malayalam Malaiàlam Path Eraser Esborrador de traçats Path Eraser Tool Eina d’esborrador de traçats Path Length Longitud del traçat + Grid Size Mida de la quadrícula + Grid Colors Colors de la quadrícula + Flattener Preset Preajust de l’aplanador + X X + Y Y Path: Traçat: Pathfinder Cercador de traçats Pathfinder Options Opcions del cercador de traçats @@ -3343,6 +3390,7 @@ digits Malayalam Malaiàlam Play Current Selection Reprodueix la selecció actual Save Actions… Desa les accions… Load Actions… Carrega accions… + Replace Actions… Reemplaça les accions… Reset Actions Restableix les accions Replace the current actions with the default set? Voleu reemplaçar les accions actuals pel conjunt predeterminat? Append adds the default set after the current sets instead. Amb Afegeix, el conjunt predeterminat s’afegeix després dels conjunts actuals. @@ -3365,6 +3413,10 @@ digits Malayalam Malaiàlam Polar Grid Tool Options Opcions de l’eina de quadrícula polar Polygon Polígon Polygon Properties: Propietats del polígon: + Line Properties: Propietats de la línia: + Line Length: Longitud de la línia: + Line Angle: Angle de la línia: + Constrain Pie Angle Restringeix l’angle del sector Polygon Tool Eina de polígon Portrait Vertical Portrait (flipped) Vertical (invertit) @@ -3563,6 +3615,9 @@ digits Malayalam Malaiàlam Real World: Món real: Real-time Drawing and Editing Dibuix i edició en temps real Use Monitor Profile for Canvas Utilitza el perfil del monitor per al llenç + Refresh Monitor Profile Actualitza el perfil del monitor +@msg turn on Use Monitor Profile for Canvas first activeu primer «Utilitza el perfil del monitor per al llenç» +@msg this build doesn't read display profiles aquesta versió no llegeix perfils de pantalla The canvas is drawn in sRGB. El llenç es dibuixa en sRGB. Canvas display profile: Perfil de pantalla del llenç: The system matches the window to the display's colors. El sistema ajusta la finestra als colors de la pantalla. @@ -3759,6 +3814,8 @@ digits Malayalam Malaiàlam Reset Automation Restableix Automation Reset Bar Position Restableix la posició de la barra Reset Bounding Box Restableix el quadre delimitador + Rotate Bounding Box Gira el quadre delimitador + Rotate Bounding Box… Gira el quadre delimitador… Reset Envelope Mesh Restableix la malla de l’embolcall Reset Envelope Shape Restableix la forma de l’embolcall Reset Essentials Restableix Essentials @@ -3819,6 +3876,7 @@ digits Malayalam Malaiàlam Resize panels Redimensiona els panells Resize Slice Redimensiona el tall Resize Type Area Redimensiona l’àrea de text + Resolution Resolució Resolution: Resolució: Responsive Adaptatiu Restore Restaura @@ -3845,6 +3903,7 @@ digits Malayalam Malaiàlam The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. La roda del ratolí amb Cmd/Ctrl premut desplaça el llenç en horitzontal. Dragging sideways on a numeric field's label changes the field's value. Arrossegar en horitzontal sobre l’etiqueta d’un camp numèric canvia el valor del camp. A two-finger rotate gesture on a trackpad rotates the canvas view. Un gest de rotació amb dos dits al trackpad gira la vista del llenç. + When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Quan moveu punts d’ancoratge, cada corba amb un extrem desplaçat conserva la forma respecte dels seus extrems. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Mantenir premuda la drecera d’una eina la tria fins que la deixeu anar, i després es torna a triar l’eina anterior. Shows the bounding box while you move the selection or draw a shape. Mostra el quadre delimitador mentre moveu la selecció o dibuixeu una forma. Create Trim Marks draws Japanese-style marks instead of Roman ones. Crea marques de retall dibuixa marques d’estil japonès en lloc de romanes. @@ -3875,6 +3934,29 @@ digits Malayalam Malaiàlam The unit for East Asian type measurements, which no field uses yet. La unitat per a les mesures del text d’Àsia oriental, que encara no fa servir cap camp. When on, a number typed without a unit into a field in picas is read in points. Quan està activat, un nombre escrit sense unitat en un camp en piques es llegeix en punts. With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options. Amb ID XML, els noms dels objectes es mostren com a ID XML a Capes, Variables i Opcions de la capa. + The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl. El pas de la mida del text i de l’interlineat: Cmd/Ctrl+Maj+. i Cmd/Ctrl+Maj+, canvien la mida un pas, o cinc amb Alt també; en text horitzontal, Alt amb la fletxa amunt o avall canvia l’interlineat un pas, o cinc amb Cmd/Ctrl. + The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl. El pas del tracking i del kerning, en mil·lèsimes d’em: en text horitzontal, Alt amb la fletxa esquerra o dreta canvia el kerning al cursor o el tracking del text seleccionat un pas, o cinc amb Cmd/Ctrl. + The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. El pas del desplaçament de la línia de base: en text horitzontal, Alt i Maj amb la fletxa amunt o avall mouen la línia de base un pas, o cinc amb Cmd/Ctrl. + Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. Mostra les opcions del text japonès i d’altres llengües d’Àsia oriental als taulers Caràcter, Paràgraf, OpenType i Glifs, i l’ordre Tipus de lletra compostos. + Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. Mostra les opcions del text àrab, hebreu i índic als taulers Caràcter i Paràgraf, com la direcció del paràgraf, les caixides i els dígits. + The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. Les eines de selecció seleccionen el text només a la línia de base, al marc del text d’àrea o al seu traçat, no a qualsevol punt dins de la seva caixa. + Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. Els menús de tipus de lletra mostren cada tipus de lletra amb el nom en anglès; desactivat, un tipus de lletra que també té nom en la seva llengua mostra aquest nom. + New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. El text d’àrea nou comença amb Mida automàtica activada, de manera que un marc rectangular de text horitzontal creix o s’encongeix en alçada per encabir-hi el text. + Font lists and the Type › Font menu show a sample of each font beside its name. Les llistes de tipus de lletra i el menú Tipus de lletra mostren una mostra de cada tipus de lletra al costat del nom. + Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on. Les mostres de tipus de lletra es dibuixen en text fosc sobre blanc, sigui quina sigui la brillantor de la interfície; només s’aplica mentre les previsualitzacions als menús estan activades. + How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is. L’alçada de cada fila a les llistes dels camps de tipus de lletra, com el del tauler Caràcter, i per tant la mida de cada mostra. + How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first. Quants dels últims tipus de lletra usats, de 1 a 15, mostren Tipus de lletra recents i les llistes, del més recent al més antic. + When you change the font or font style of text, characters the new font has no glyph for keep the font they had. Quan canvieu el tipus de lletra o l’estil d’un text, els caràcters per als quals el nou tipus de lletra no té glif conserven el que tenien. + A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export. Un ressaltat rosa al llenç marca els glifs que les funcions OpenType han substituït, com les lligadures; no s’imprimeix ni s’exporta. + With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from. Amb l’eina de text, seleccionar un sol caràcter mostra al seu costat, al llenç, una fila dels seus glifs alternatius per triar-ne un. + A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export. Un ressaltat rosa al llenç marca el text dibuixat amb un tipus de lletra substitut perquè el seu falta; no s’imprimeix ni s’exporta. + New type made with a Type tool starts with placeholder text, selected, so typing replaces it. El text nou fet amb una eina de text comença amb text de farciment seleccionat, que el que escriviu substitueix. + Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list. Escriure un marcador de llista com 1. o * i després un espai a l’inici d’un paràgraf converteix el paràgraf en una llista. + Fonts in this folder show in the font menus and can be used without being installed. Els tipus de lletra d’aquesta carpeta apareixen als menús de tipus de lletra i es poden usar sense instal·lar-los. + Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows. Aplicar un estil gràfic a un text treu als caràcters el seu propi emplenament o traç on l’estil en té un, perquè es vegi la pintura de l’estil. + Align and Distribute measure point type by the ink of its glyphs instead of its em box. Alinea i Distribueix mesuren el text de punt per la tinta dels seus glifs en lloc de la seva caixa em. + Align and Distribute measure area type by the ink of its glyphs instead of its frame. Alinea i Distribueix mesuren el text d’àrea per la tinta dels seus glifs en lloc del seu marc. + The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box. El quadre delimitador i el tauler Transforma mesuren el text de punt per la tinta dels seus glifs en lloc de la seva caixa em. Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply. Ajusta el dibuix, el desplaçament i l’escalat a les subdivisions de la quadrícula, fins i tot quan la quadrícula està amagada; mentre està activat, Ajusta al píxel no s’aplica. The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead. El color de les guies no seleccionades; un tauler amb una Etiqueta de les guies dibuixa les seves guies amb el color de l’etiqueta. Draws guides as solid lines or as dots, including the guides already in the document. Dibuixa les guies com a línies contínues o com a punts, incloses les guies que ja són al document. @@ -3962,6 +4044,7 @@ digits Malayalam Malaiàlam Rotate… Gira… Rotation Rotació Rotation relative to: Rotació relativa a: + Hue Jitter: Variació del to: Rotation X Rotació X Rotation Y Rotació Y Rotation Z Rotació Z @@ -3982,8 +4065,10 @@ digits Malayalam Malaiàlam Rounded Rectangle Rectangle arrodonit Rounded Rectangle Tool Eina de rectangle arrodonit Rounded Rectangle… Rectangle arrodonit… + Roundness Arrodoniment Roundness: Arrodoniment: Row Size: Mida de la fila: + Rows Files Rows: Files: Ruby Rubí Ruby… Rubí… @@ -4217,6 +4302,9 @@ digits Malayalam Malaiàlam Search commands, tools, panels and effects… Cerca ordres, eines, panells i efectes… No commands match Cap ordre coincideix {pos} of {total}: {name} {pos} de {total}: {name} + No menu item Cap element de menú + Toolbar Barra d’eines + {toolbar}, in the {tool} group {toolbar}, al grup {tool} @plural {n} result|{n} results {n} resultat|{n} resultats @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} de {n} resultat. Continueu escrivint per reduir-los.|{shown} de {n} resultats. Continueu escrivint per reduir-los. Recent Commands Ordres recents @@ -4384,6 +4472,7 @@ digits Malayalam Malaiàlam Set Slice Rectangle Defineix el rectangle del tall Set Tab Stops Defineix les tabulacions Set Text Defineix el text + Set the current fill or stroke to the selected color Defineix el color seleccionat com a farciment o traç actual Set the selected color to the current color Defineix el color seleccionat com a color actual Set Zoom Defineix el zoom Set: Defineix: @@ -4530,7 +4619,7 @@ digits Malayalam Malaiàlam Show Vivid/Muted Mostra els vius/apagats Show Warm/Cool Mostra els càlids/freds Show {kind} Brushes Mostra els pinzells {kind} - Show/hide plate (Alt-click: only this plate) Mostra o amaga la planxa (Alt+clic: només aquesta planxa) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Mostra o amaga la planxa (Alt+clic: només aquesta planxa; Alt+clic de nou: totes les planxes) Show: Mostra: Shown with the optimised preview. Es mostra amb la previsualització optimitzada. Shrink Text to Fit Redueix el text perquè hi càpiga @@ -4894,7 +4983,7 @@ digits Malayalam Malaiàlam Composite Fonts Tipus de lletra compostos Export Composite Fonts Exporta tipus de lletra compostos Import Composite Fonts Importa tipus de lletra compostos -@msg each font must be {name, parts} cada tipus de lletra ha de ser {name, parts} +@msg each font must be {{name, parts}} cada tipus de lletra ha de ser {{name, parts}} @msg unknown key `{k}`; a font takes name and parts clau desconeguda `{k}`; un tipus de lletra admet name i parts @msg each font needs a name cada tipus de lletra necessita un nom @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` no pot anomenar un tipus de lletra compost (d’1 a {COMPOSITE_NAME_MAX} caràcters, sense caràcters de control) @@ -4907,7 +4996,10 @@ digits Malayalam Malaiàlam @msg two composite fonts are named `{_1}` dos tipus de lletra compostos es diuen `{_1}` @msg `{_1}` is the name of an installed font `{_1}` és el nom d’un tipus de lletra instal·lat @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2} usa `{font}`, un tipus de lletra compost -@msg give fonts: [{name, parts}…] indiqueu fonts: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] indiqueu fonts: [{{name, parts}}…] +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` ha de ser "document", {{artboards: [index, …]}} o {{layers: [id, …]}} +@msg numbers out of order in {{}} quantifier nombres desordenats al quantificador {{}} +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) la pintura no és un degradat de forma lliure (apliqueu-ne un amb paint.editGradient {{kind: "freeform"}}) @msg path is empty path és buit @msg fonts must be a list of composite fonts fonts ha de ser una llista de tipus de lletra compostos @msg names must be strings names ha de contenir cadenes @@ -5023,6 +5115,13 @@ digits Malayalam Malaiàlam TIFF (8-bit Color) TIFF (color de 8 bits) TIFF (Black & White) TIFF (blanc i negre) Tile Mosaic + Tile All Vertically Mosaic vertical de tot + Tile All Horizontally Mosaic horitzontal de tot + 2-Up Layout Disposició de 2 + 3-Up Layout Disposició de 3 + 4-Up Layout Disposició de 4 + 6-Up Layout Disposició de 6 + Arrange Documents Organitza els documents Tile Edge Color Color de la vora del mosaic Tile Edge Color… Color de la vora del mosaic… Tile Full Pages Mosaic de pàgines senceres @@ -5303,6 +5402,8 @@ digits Malayalam Malaiàlam Variable Options Opcions de variable Variable Options… Opcions de variable… Variable Width Profile Perfil d’amplada variable + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. El pinzell del traç manté la seva pròpia mida, de manera que un perfil d’amplada no el canvia. Traieu el pinzell per fer servir un perfil. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. El pinzell del traç manté la seva pròpia mida, de manera que un perfil d’amplada no el canvia. Traieu el pinzell per fer servir un perfil. Variables Variables Variation Variació Variation: Variació: @@ -5356,7 +5457,7 @@ digits Malayalam Malaiàlam Update While Dragging Actualitza mentre s’arrossega Video Thumbnail 1280×720 Miniatura de vídeo 1280×720 View Visualitza - View Artboard Only Visualitza només el tauler + View Artboard Contents Only Visualitza només el contingut del tauler View Opacity Mask Visualitza la màscara d’opacitat View PDF after saving Visualitza el PDF després de desar View {n} Vista {n} @@ -5430,6 +5531,7 @@ digits Malayalam Malaiàlam Write Layers Escriu les capes Writes, moves or deletes files Escriu, mou o suprimeix fitxers x Height Alçada de la x + Em Box Height Alçada de la caixa em X11 (XWayland) X11 (XWayland) X11 (XWayland) When a Pen Is Attached X11 (XWayland) quan hi ha un llapis connectat X: X: @@ -5555,6 +5657,8 @@ digits Malayalam Malaiàlam @msg a negative `aspect` applies to conic gradients un `aspect` negatiu s’aplica als degradats cònics @msg `focal` applies to radial gradients `focal` s’aplica als degradats radials @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` ha de ser grayscale, rgb, hsb, cmyk o websafe +@msg `view` must be wheel or box `view` ha de ser wheel o box +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` ha de ser hue, saturation, brightness, red, green o blue @msg `name` is empty `name` és buit @msg `newName` is empty `newName` és buit @msg `pathfinder` must be an object `pathfinder` ha de ser un objecte @@ -5702,6 +5806,9 @@ digits Malayalam Malaiàlam @msg automation path rejected: outside the read root {root}: {path} camí d’automatització rebutjat: fora de l’arrel de lectura {root}: {path} @msg automation path rejected: outside the read roots {roots}: {path} camí d’automatització rebutjat: fora de les arrels de lectura {roots}: {path} @msg a linked JavaScript file is outside the read roots un fitxer JavaScript enllaçat és fora de les arrels de lectura +@msg a linked image file is outside the read roots un fitxer d’imatge enllaçat és fora de les arrels de lectura +@msg a linked file's export folder is outside the read roots la carpeta d’exportació d’un fitxer enllaçat és fora de les arrels de lectura +@msg a linked file's editing data can't be read to check it against the read roots no es poden llegir les dades d’edició d’un fitxer enllaçat per comprovar-les amb les arrels de lectura @msg the library's file is outside the read roots el fitxer de la biblioteca és fora de les arrels de lectura @msg {file} names more than one linked JavaScript file {file} correspon a més d’un fitxer JavaScript enllaçat @msg automation path rejected: outside the write root {root}: {path} camí d’automatització rebutjat: fora de l’arrel d’escriptura {root}: {path} @@ -5720,6 +5827,7 @@ digits Malayalam Malaiàlam @msg bad trailer tràiler incorrecte @msg balance must be between 0 and 100 balance ha d’estar entre 0 i 100 @msg batch step {_1} (`{id}`) failed: {e} el pas de lot {_1} (`{id}`) ha fallat: {e} +@msg action step {_1} (`{id}`) failed: {reason} el pas {_1} de l’acció (`{id}`) ha fallat: {reason} @msg Batch: {count} processed Lot: {count} processats @msg Batch: {count} processed, {failed} failed Lot: {count} processats, {failed} fallits @msg before must name a panel before ha de nomenar un panell @@ -5754,6 +5862,7 @@ digits Malayalam Malaiàlam @msg Choose two nonzero angle arms Trieu dos braços d’angle no nuls @msg clipboard is empty el porta-retalls és buit @msg closing needs three anchors el tancament necessita tres punts d’ancoratge +@msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: almenys un color ha de quedar a la taula de colors @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` no és un color com "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: com a màxim {MAX_TABLE} colors @msg column docks a set as a dock column, with no anchor or icon column acobla un conjunt com a columna d’acoblament, sense àncora ni icona @@ -5772,6 +5881,13 @@ digits Malayalam Malaiàlam Show External Script Warning Mostra l'avís dels scripts externs A Script Is Running S'està executant un script Script Alert Avís de l'script + Script File Access Accés de l’script als fitxers + The script asks to read a file you choose. L’script demana llegir un fitxer que trieu. + The script asks to read and write a file you choose. L’script demana llegir i escriure un fitxer que trieu. + The script asks to read and write a folder you choose, with everything in it. L’script demana llegir i escriure una carpeta que trieu, amb tot el que conté. + Allow Once Permet un cop + Always Allow This Script Permet sempre aquest script + Deny Denega A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Un script pot canviar els documents oberts i escriure fitxers mitjançant les ordres que executa. Executeu només scripts de confiança. Do not show this warning again No tornis a mostrar aquest avís Stop the script and undo what it did? Then quit again. Voleu aturar l'script i desfer el que ha fet? Després, torneu a sortir. @@ -5788,6 +5904,8 @@ digits Malayalam Malaiàlam @msg the script is no longer in the Scripts folder l'script ja no és a la carpeta Scripts Some scripts were not listed Alguns scripts no s'han llistat The Scripts folder cannot be read No es pot llegir la carpeta Scripts + Loading scripts… S’estan carregant els scripts… + The Scripts folder is still being read Encara s’està llegint la carpeta Scripts @msg the script's run is no longer available l'execució de l'script ja no està disponible @msg a failed command changed undo steps that could not be put back, so the script was stopped una ordre fallida ha canviat passos de desfer que no s'han pogut restaurar, així que l'script s'ha aturat @msg a recovery copy could not be written, so the script was not run no s'ha pogut escriure una còpia de recuperació, per tant l'script no s'ha executat @@ -5800,8 +5918,6 @@ digits Malayalam Malaiàlam @msg Script file could not be read No s'ha pogut llegir el fitxer de l'script @msg Script folder has more than 2,048 entries La carpeta de l'script té més de 2.048 entrades @msg Script file open mode must be r, w, e or a El mode d'obertura del fitxer de l'script ha de ser r, w, e o a -@msg Script file writing is not available L'escriptura de fitxers de l'script no està disponible -@msg Script file dialogs are not available Els quadres de diàleg de fitxers de l'script no estan disponibles @msg Script files cannot be opened in another application Els fitxers de l'script no es poden obrir en una altra aplicació @msg Script file access is unavailable on the web L'accés als fitxers de l'script no està disponible al web @msg Script has 256 files open L'script té 256 fitxers oberts @@ -5940,8 +6056,37 @@ liquify-list-end {0}, {1} {0} i {1} @msg is a prompt's answer, whose `value` must be a string or null és la resposta d'un prompt, i el seu `value` ha de ser una cadena o null @msg must have `kind` alert, confirm or prompt ha de tenir `kind` alert, confirm o prompt @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` només és per a una execució sense ningú a qui preguntar: a l'aplicació, la persona respon cada quadre de diàleg +@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` ha de ser un nombre enter d’1 a {_1} +@msg `args{place}` is nested more than 64 levels deep `args{place}` està imbricat en més de 64 nivells +@msg `args` must be an object `args` ha de ser un objecte +@msg `args` is larger than 1 MiB `args` ocupa més d'1 MiB +@msg `path` is empty `path` és buit +@msg `installed` takes a `path`, not a `source` `installed` admet un `path`, no un `source` +@msg `path` must name a .js or .jsx file `path` ha d’indicar un fitxer .js o .jsx +@msg give exactly one of `path` and `source` indiqueu exactament un de `path` i `source` @msg Running a script S'està executant un script @msg Copied the script report S’ha copiat l’informe de l’script +@msg Script file access denied: {path} S’ha denegat l’accés de l’script als fitxers: {path} +@msg Script file access to the app's own folders is not allowed Els scripts no poden accedir a les carpetes pròpies de l’aplicació +@msg Script file cannot encode the text El fitxer de l’script no pot codificar el text +@msg Script file could not be written No s’ha pogut escriure el fitxer de l’script +@msg Script file dialogs need a person to answer them Els diàlegs de fitxers de l’script necessiten una persona que els respongui +@msg Script file is not open for writing El fitxer de l’script no està obert per escriure-hi +@msg Script file name is already in use El nom del fitxer de l’script ja està en ús +@msg Script file name must be a name without a folder El nom del fitxer de l’script ha de ser un nom sense carpeta +@msg Script file permission can be kept only for a script run from a file El permís de fitxers només es pot conservar per a un script executat des d’un fitxer +@msg Script file permission could not be saved No s’ha pogut desar el permís de fitxers de l’script +@msg Script folder is not empty La carpeta de l’script no és buida +@msg Script files cannot make aliases Els fitxers de l’script no poden crear àlies +@msg Script file hidden setting cannot be changed No es pot canviar l’opció d’ocult del fitxer de l’script +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: un diàleg de fitxers no es pot obrir dins d’una crida de retorn d’una funció integrada, d’un getter, d’una conversió o d’un fitxer que executa $.evalFile; crideu-lo des del codi propi de l’script +@msg the script wrote more file data than one run may write (32 MiB) l’script ha escrit més dades de fitxers de les que pot escriure una execució (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` per al diàleg de fitxers d’un script ha de ser un d’aquests: once, always, deny, stop +@msg choose a file or folder first, or deny trieu primer un fitxer o una carpeta, o denegueu +@msg the script file permissions could not be saved: {e} no s’han pogut desar els permisos de fitxers dels scripts: {e} +@msg this script's file access can be allowed only once l’accés als fitxers d’aquest script només es pot permetre una vegada +@msg Only the person at the keyboard can allow a script's file access Només la persona al teclat pot permetre l’accés als fitxers d’un script +@msg A script is given at most 2,048 files: the files picked after them were left out Un script rep com a màxim 2.048 fitxers: els fitxers triats després d’aquests s’han deixat fora @msg Copied the link info S’ha copiat la informació de l’enllaç @msg Corners edits the corners of a path Cantonades edita les cantonades d’un traçat @msg could not decode image: {0} no s’ha pogut descodificar la imatge: {0} @@ -6148,9 +6293,15 @@ liquify-list-end {0}, {1} {0} i {1} @msg New Window isn't available yet: a document opens in one window Finestra nova encara no està disponible: un document s’obre en una sola finestra @msg no active document no hi ha cap document actiu @msg no active perspective plane no hi ha cap pla de perspectiva actiu +@msg the perspective grid is hidden la quadrícula de perspectiva està oculta +@msg Automatic Plane Positioning is off: turn on anchorPoint or gridlineIntersection (perspective.widget.options) El posicionament automàtic del pla està desactivat: activeu anchorPoint o gridlineIntersection (perspective.widget.options) +@msg anchorPoint must be true or false anchorPoint ha de ser true o false +@msg gridlineIntersection must be true or false gridlineIntersection ha de ser true o false +@msg tolerance must be 0 or more tolerance ha de ser 0 o més +@msg give `at` or `clear`, not both indiqueu `at` o `clear`, no tots dos @msg no anchor points selected no hi ha cap punt d’ancoratge seleccionat -@msg `points` must be three [x, y] pairs of numbers `points` han de ser tres parells de nombres [x, y] -@msg direct-select three anchor points, or give `points` seleccioneu directament tres punts d’ancoratge o indiqueu `points` +@msg `points` must be two or three [x, y] pairs of numbers `points` han de ser dos o tres parells de nombres [x, y] +@msg direct-select two or three anchor points, or give `points` seleccioneu directament dos o tres punts d’ancoratge o indiqueu `points` @msg no circle passes through these points: two are the same or all three lie on one line cap cercle no passa per aquests punts: dos són iguals o tots tres són en una mateixa recta @msg no app to open files here aquí no hi ha cap aplicació per obrir fitxers @msg no artboard no hi ha tauler @@ -6274,6 +6425,9 @@ liquify-list-end {0}, {1} {0} i {1} @msg no such user library no existeix aquesta biblioteca d’usuari @msg no such view no existeix aquesta vista @msg no such width point no existeix aquest punt d’amplada +@msg `single` must be `incoming` or `outgoing` `single` ha de ser `incoming` o `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` i `outIndex` han de ser les dues meitats d’un mateix punt d’amplada discontinu +@msg a discontinuous width point keeps its place un punt d’amplada discontinu manté la seva posició @msg no swatch `{name}` no hi ha la mostra `{name}` @msg no swatch library `{l}` (see swatch.library.list) no hi ha la biblioteca de mostres `{l}` (vegeu swatch.library.list) @msg no symbol `{n}` no hi ha el símbol `{n}` @@ -6284,6 +6438,8 @@ liquify-list-end {0}, {1} {0} i {1} @msg no target object has an opacity mask: select one or give `id` no hi ha cap objecte de destinació amb màscara d’opacitat: seleccioneu-ne un o doneu `id` @msg no threaded text selected no hi ha cap text encadenat seleccionat @msg no user library folder here aquí no hi ha cap carpeta de biblioteca d’usuari +@msg `{file}` has no swatches of its own `{file}` no té mostres pròpies +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` té mostres de motius, que un fitxer .vcswatches no pot contenir @msg no user workspace `{from}` no hi ha l’espai de treball d’usuari `{from}` @msg node {_1} is not text el node {_1} no és text @msg node {_1} is on a locked artboard el node {_1} és en un tauler bloquejat @@ -6435,6 +6591,9 @@ liquify-list-end {0}, {1} {0} i {1} @msg Saved to User Defined: {_1} Desat a User Defined: {_1} @msg Saved {n} files beside {path} S’han desat {n} fitxers al costat de {path} @msg Saved {path} Desat {path} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} S’ha copiat amb {n} nota: {first}|S’ha copiat amb {n} notes: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} S’ha retallat amb {n} nota: {first}|S’ha retallat amb {n} notes: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} S’ha traçat la imatge amb {n} nota: {first}|S’ha traçat la imatge amb {n} notes: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} S’ha desat {path} amb {n} nota: {first}|S’ha desat {path} amb {n} notes: {first} @msg Saving S’està desant @msg Saving recovery data for {_1} S’estan desant les dades de recuperació de {_1} @@ -6508,6 +6667,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg shadings of more than 4096 patches or triangles were left out els ombrejats de més de 4096 pedaços o triangles s’han omès @msg shadings whose functions are of an unknown type are filled with their middle colour els ombrejats les funcions dels quals són d’un tipus desconegut s’omplen amb el seu color central @msg Shape Builder: no region under the pointer Constructor de formes: no hi ha cap regió sota el punter +@msg Shape Builder: select all paths you want to merge Constructor de formes: selecciona tots els traçats que vulguis combinar @msg Shape Builder: select paths or compound paths Constructor de formes: selecciona traçats o traçats compostos @msg shortcut for `{k}` must be a string la drecera de `{k}` ha de ser una cadena @msg Show All Hidden Attributes: nothing is hidden Mostra tots els atributs ocults: no hi ha res d’ocult @@ -6590,7 +6750,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg each of `{GRAPHICS}` must be an object cada element de `{GRAPHICS}` ha de ser un objecte @msg `{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}` les entrades de `{GRAPHICS}` admeten symbol, face, x, y, scale i rotation, no `{k}` @msg each of `{GRAPHICS}` needs `symbol`, the name of a symbol cada element de `{GRAPHICS}` necessita `symbol`, el nom d’un símbol -@msg `{GRAPHICS}` face must be front or back face de `{GRAPHICS}` ha de ser front o back +@msg `{GRAPHICS}` face must be front, back or side face de `{GRAPHICS}` ha de ser front, back o side @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} de `{GRAPHICS}` ha de ser un nombre de {lo} a {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` ha de ser una matriu @msg Graphics map onto the Plane, Extrude and Revolve object types Els gràfics s’apliquen als tipus d’objecte Pla, Extrusió i Revolució @@ -6763,6 +6923,8 @@ liquify-list-end {0}, {1} {0} i {1} @msg Trap: select two or more objects filled with solid colours Trap: selecciona dos o més objectes emplenats amb colors sòlids @msg truncated truncat @msg Unembedded to {_1} S’ha desincrustat a {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} S’ha desincrustat {n} imatge a {folder}|S’han desincrustat {n} imatges a {folder} +@msg every numbered name for {name} is taken in that folder tots els noms numerats per a {name} estan ocupats en aquesta carpeta @msg unknown command `{0}` ordre desconeguda `{0}` @msg step {step} of “{action}” runs the unknown command `{command}` el pas {step} de “{action}” executa l’ordre desconeguda `{command}` @msg unknown command `{0}`; did you mean `{1}`? ordre desconeguda `{0}`; volies dir `{1}`? @@ -6838,6 +7000,13 @@ liquify-list-end {0}, {1} {0} i {1} @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} més de {MAX_CSV_ROWS} conjunts de dades: Importa conjunts de dades en llegeix com a màxim {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} més de {MAX_CSV_COLS} variables: Importa conjunts de dades en llegeix com a màxim {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} les variables que no són text s’han omès: {kinds} +variable-kind Visibility Visibilitat +variable-kind Linked File Fitxer enllaçat +variable-kind Graph Data Dades del gràfic +variable-kind Unknown Desconegut +variable-list-two {0}, {1} {0} i {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} i {1} @msg a new document won't read these variables back with their kind: {names} un document nou no tornarà a llegir aquestes variables amb el seu tipus: {names} @msg a new document refuses this file because of these variables: {names} un document nou rebutja aquest fitxer a causa d'aquestes variables: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them la capçalera `{header}` de `{name}` es tornaria a llegir com la variable `{other}`: canvieu el nom d’una de les dues @@ -6891,6 +7060,8 @@ liquify-list-end {0}, {1} {0} i {1} @msg {label}: lost track of a shape's style {label}: s’ha perdut el rastre de l’estil d’una forma @msg {label}: select paths {label}: selecciona traçats @msg {label}: select paths, compound paths, groups or text {label}: selecciona traçats, traçats compostos, grups o text +@msg a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first una línia o un altre traçat obert que no tanca cap àrea no canvia la forma del resultat; per incloure’l, apliqueu-hi primer Objecte › Traçat › Contorneja el traç +@msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first {label} ha produït un resultat buit: una línia o un altre traçat obert no tanca cap àrea; per incloure’l, apliqueu-hi primer Objecte › Traçat › Contorneja el traç @msg {label}… {label}… @msg {name}: CRC mismatch {name}: CRC no coincideix @msg {name}: no local header {name}: no hi ha capçalera local @@ -6902,6 +7073,8 @@ liquify-list-end {0}, {1} {0} i {1} @msg {path}: {e} {path}: {e} @msg {status} ({e}) {status} ({e}) @msg {tool} isn't in a toolbar group of several tools {tool} no forma part d’un grup de diverses eines a la barra d’eines +@msg Presentation Mode hides the toolbars: change the screen mode to show them el Mode de presentació amaga les barres d’eines: canvieu el mode de pantalla per mostrar-les +@msg Tab has hidden the toolbars: press Tab to show them Tab ha amagat les barres d’eines: premeu Tab per mostrar-les @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants «{_1}» demana un pressupost elevat (cada execució fins a {minutes} minuts i {times} vegades les instruccions habituals): una persona l’ha d’aprovar a l’aplicació d’escriptori, o passa `allowHeavy: true` en una sessió iniciada amb --allow-plugin-grants # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters `name` ha de tenir 1-64 caràcters imprimibles @@ -7378,6 +7551,12 @@ anchor Points: Punts: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` ha de ser "free", "keepAngles" o "symmetric" @msg `{key}` must be [x, y] `{key}` ha de ser [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Convertidor d’unitats + Unit Converter Panel Tauler Convertidor d’unitats + Copy with Units Copia amb les unitats + From Selection De la selecció + # Color Effects add-on: Select by Color Kind. Select by Color Kind Selecciona per tipus de color Objects with Spot Colors Objectes amb colors directes @@ -7614,6 +7793,14 @@ breakText Glyphs Glifs Remove Gaps Elimina les separacions @msg that makes too many pieces (at most 100000): make the dashes longer això fa massa trossos (com a màxim 100000): allargueu els guions @msg select paths, or segments, to divide seleccioneu camins o segments per dividir +# Path Precision Tools add-on: Smooth Bridge. + Smooth Bridge… Pont suau… + Smooth Bridge Pont suau + Keep Originals Conserva els originals +@msg select two circles to bridge seleccioneu dos cercles per unir-los +@msg one circle is inside the other un cercle és dins de l’altre +@msg the circles are too far apart for this radius: raise the radius els cercles estan massa separats per a aquest radi: augmenteu el radi +@msg the circles are too far apart for this radius els cercles estan massa separats per a aquest radi # Path Precision Tools add-on: Common Tangents. Common Tangents… Tangents comunes… Common Tangents Tangents comunes @@ -8125,4 +8312,15 @@ breakText Glyphs Glifs @msg A panel is not joined to the rest by a crease. Un panell no està unit a la resta per cap línia d’hendit. @msg A fold line is on a non-printing layer. Una línia de plegat és en una capa que no s’imprimeix. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panells: {panels}, frontisses: {hinges}, errors: {errors}, avisos: {warnings} + Fold Preview Previsualització del plegat + Fold Plegat + Show Fold Lines Mostra les línies de plegat + Three-Quarter Tres quarts + Open a document to preview its folded shape. Obre un document per previsualitzar-ne la forma plegada. +@msg Check the fold lines first. Primer comprova les línies de plegat. +@msg Panels: {panels}, hinges: {hinges} Panells: {panels}, frontisses: {hinges} +@msg Other blanks not shown: {count} Altres troquelats no mostrats: {count} +@msg A joint does not close by {gap} pt. Una unió no es tanca per {gap} pt. +@msg Two panels pass through each other. Dos panells es travessen l’un a l’altre. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer ha de ser "singleLine", "everyLine", "standardSingleLine" o "standardEveryLine" +@msg text.{key} `{v}`: use "{_1}" or "{_2}" text.{key} `{v}`: utilitzeu "{_1}" o "{_2}" diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index a5d7bb948a..2ebf9b2358 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -173,6 +173,8 @@ Shear… Zkosit… Transform Each… Transformovat jednotlivě… Reset Bounding Box Obnovit ohraničovací rámeček + Rotate Bounding Box Otočit ohraničovací rámeček + Rotate Bounding Box… Otočit ohraničovací rámeček… Arrange Uspořádat Bring to Front Přenést do popředí Bring Forward Přenést blíž @@ -719,6 +721,13 @@ Previous Document Předchozí dokument Cascade Do kaskády Tile Vedle sebe + Tile All Vertically Vše vedle sebe svisle + Tile All Horizontally Vše vedle sebe vodorovně + 2-Up Layout Rozvržení po 2 + 3-Up Layout Rozvržení po 3 + 4-Up Layout Rozvržení po 4 + 6-Up Layout Rozvržení po 6 + Arrange Documents Uspořádat dokumenty Float in Window Uvolnit do samostatného okna Float All in Windows Uvolnit vše do samostatných oken Consolidate All Windows Sloučit všechna okna @@ -765,6 +774,11 @@ Saturation and brightness Sytost a jas Color field Barevné pole {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Zobrazení kola + Box View Zobrazení čtverce + Box Channel Kanál čtverce + Color box Barevný čtverec + Color Wheel Options Možnosti barevného kola CSS Properties Vlastnosti CSS Document Info Informace o dokumentu Flattener Preview Náhled sloučení @@ -994,7 +1008,7 @@ Free Transform Volná transformace Perspective Distort Perspektivní deformace -# Photoshop-style raster effects (Effect menu, their dialogs). +# Raster effects (Effect menu, their dialogs). Radial Blur… Radiální rozostření… Blur Center Střed rozostření Smart Blur… Chytré rozostření… @@ -1547,6 +1561,7 @@ lighting Light Světlo Play Current Selection Přehrát aktuální výběr Save Actions… Uložit akce… Load Actions… Načíst akce… + Replace Actions… Nahradit akce… Reset Actions Obnovit akce Replace the current actions with the default set? Nahradit aktuální akce výchozí sadou? Append adds the default set after the current sets instead. Tlačítko Připojit místo toho přidá výchozí sadu za aktuální sady. @@ -1708,7 +1723,7 @@ digits Malayalam Malajálamské Composite Fonts Složená písma Export Composite Fonts Exportovat složená písma Import Composite Fonts Importovat složená písma -@msg each font must be {name, parts} každé písmo musí být {name, parts} +@msg each font must be {{name, parts}} každé písmo musí být {{name, parts}} @msg unknown key `{k}`; a font takes name and parts neznámý klíč `{k}`; písmo přijímá name a parts @msg each font needs a name každé písmo potřebuje název @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` nemůže být názvem složeného písma (1 až {COMPOSITE_NAME_MAX} znaků, bez řídicích znaků) @@ -1721,7 +1736,7 @@ digits Malayalam Malajálamské @msg two composite fonts are named `{_1}` dvě složená písma se jmenují `{_1}` @msg `{_1}` is the name of an installed font `{_1}` je název nainstalovaného písma @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2} používá `{font}`, což je složené písmo -@msg give fonts: [{name, parts}…] zadejte fonts: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] zadejte fonts: [{{name, parts}}…] @msg path is empty path je prázdné @msg fonts must be a list of composite fonts fonts musí být seznam složených písem @msg names must be strings names musí být řetězce @@ -1764,6 +1779,7 @@ digits Malayalam Malajálamské Underline Podtržení Vertical Scale % Svislá změna velikosti % Axis Osa + Axis Angle Úhel osy ICF Top/Right ICF horní/pravý ICF Bottom/Left ICF dolní/levý Show Font Height Options Zobrazit možnosti výšky písma @@ -1806,6 +1822,7 @@ digits Malayalam Malajálamské Rule: Pravidlo: Save changes to {name} Uložit změny do {name} Save theme to My Themes Uložit motiv do Mých motivů + Set the current fill or stroke to the selected color Nastavit vybranou barvu jako aktuální výplň nebo tah Set the selected color to the current color Nastavit vybranou barvu jako aktuální barvu Copy All Styles Kopírovat všechny styly Exported {path} Exportováno: {path} @@ -2120,7 +2137,7 @@ digits Malayalam Malajálamské Stroke: click for swatches, Shift-click for the color mixer Tah: kliknutím otevřete vzorník, Shift+kliknutím míchání barev This panel is on the roadmap (see the parity plan). Tento panel je v plánu (viz plán parity). Open a document to navigate it. Otevřete dokument, abyste v něm mohli navigovat. - View Artboard Only Zobrazit jen pracovní plochu + View Artboard Contents Only Zobrazit jen obsah pracovní plochy Contextual Alternates Kontextové alternativy Default Figure Výchozí číslice Discretionary Ligatures Volitelné ligatury @@ -2270,7 +2287,7 @@ digits Malayalam Malajálamské Overprint Preview (separations) Náhled přetisků (separace) Show All Plates Zobrazit všechny desky Show all plates Zobrazit všechny desky - Show/hide plate (Alt-click: only this plate) Zobrazit/skrýt desku (Alt+kliknutí: jen tato deska) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Zobrazit/skrýt desku (Alt+kliknutí: jen tato deska; další Alt+kliknutí: všechny desky) Simulate Paper Simulovat papír Use Black Point Compensation Použít kompenzaci černého bodu Working CMYK (don't tag) Pracovní CMYK (neoznačovat) @@ -2310,6 +2327,8 @@ digits Malayalam Malajálamské Tip extends past the end point Hrot přesahuje koncový bod Tip on the end point Hrot na koncovém bodu Variable Width Profile Profil proměnné šířky + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Štětec tahu si zachovává vlastní velikost, takže ho profil šířky nemění. Chcete-li použít profil, odeberte štětec. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Štětec tahu si zachovává vlastní velikost, takže ho profil šířky nemění. Chcete-li použít profil, odeberte štětec. Weight: Tloušťka: Art using a deleted global swatch keeps its colour. Kresba, která používá odstraněnou globální položku vzorníku, si barvu ponechá. Color Group: {name} Skupina barev: {name} @@ -2419,6 +2438,10 @@ digits Malayalam Malajálamské Flip Horizontal Překlopit vodorovně Flip Vertical Překlopit svisle Polygon Properties: Vlastnosti mnohoúhelníku: + Line Properties: Vlastnosti čáry: + Line Length: Délka čáry: + Line Angle: Úhel čáry: + Constrain Pie Angle Zachovat úhel výseče Rectangle Properties: Vlastnosti obdélníku: Shape Properties: Vlastnosti tvaru: Shape Properties Vlastnosti tvaru @@ -2462,6 +2485,7 @@ digits Malayalam Malajálamské Scatter: Rozptyl: Rotation: Otočení: Rotation relative to: Otočení vzhledem k: + Hue Jitter: Kolísání odstínu: Brush Scale Options Možnosti velikosti štětce Scale Proportionately Měnit velikost proporcionálně Stretch to Fit Stroke Length Roztáhnout na délku tahu @@ -2500,6 +2524,7 @@ digits Malayalam Malajálamské Size: Velikost: Calligraphic Brush Options Možnosti kaligrafického štětce Bristle Brush Options Možnosti štětinového štětce + Roundness Zakulacení Roundness: Zakulacení: Shape: Tvar: Bristle Length: Délka štětin: @@ -2833,6 +2858,7 @@ digits Malayalam Malajálamské BLANK DOCUMENT PRESETS PŘEDNASTAVENÍ PRÁZDNÝCH DOKUMENTŮ Bleed Spadávka Change to Right-to-Left Layout Změnit na rozvržení zprava doleva + Columns Sloupce Columns: Sloupce: Documents you create appear here. Zde se zobrazí dokumenty, které vytvoříte. More Settings Další nastavení @@ -2966,6 +2992,9 @@ digits Malayalam Malajálamské Open a document to preview its pages Otevřete dokument, abyste viděli náhled jeho stránek Output › Mode Výstup › Režim Overprint and Transparency Flattener Options Možnosti přetisku a sloučení průhlednosti + Custom… Vlastní nastavení… + Custom Transparency Flattener Options Vlastní možnosti sloučení průhlednosti + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS nemá průhlednost alfa a Přetisky určují, zda se přetisky zachovají. Place the pages with the placement again Znovu rozmístit stránky podle umístění Placement: Umístění: Preserve CMYK Numbers Zachovat hodnoty CMYK @@ -3015,14 +3044,19 @@ digits Malayalam Malajálamské Around Object Kolem objektu Background: Pozadí: Changing these settings changes how raster effects look when exported, flattened or expanded. Změna těchto nastavení mění vzhled rastrových efektů při exportu, sloučení nebo rozložení. + Add Around Přidat kolem objektu + Anti Alias Vyhlazování + Color Model Barevný model Color Model: Barevný model: Create Clipping Mask Vytvořit ořezovou masku Preserve Spot Colors Zachovat přímé barvy + Resolution Rozlišení Resolution: Rozlišení: Transparent Průhledné Layout Order: Pořadí rozvržení: Change to Left-to-Right Layout Změnit na rozvržení zleva doprava Artboards: {n} Pracovní plochy: {n} + Rows Řádky Rows: Řádky: Assign Přiřadit Color Group: Skupina barev: @@ -3171,6 +3205,8 @@ antiAlias Sharp Ostré Every option matches {base}. Všechny možnosti odpovídají: {base}. Files of a PDF standard can't be password-protected. Soubory podle standardu PDF nelze chránit heslem. Files of this standard tag their colours with ICC profiles. Soubory tohoto standardu označují své barvy profily ICC. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Soubory tohoto standardu označují své barvy profily ICC, kromě barev CMYK v profilu výstupního záměru, které se zapisují jako DeviceCMYK. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. S volbou „Nezahrnovat profily“ a výstupním záměrem CMYK se každá barva CMYK zapíše jako DeviceCMYK, pokud se nepřevede do cíle CMYK s jiným profilem. Flattener preset: Přednastavení sloučení: General › Thumbnails Obecné › Miniatury Grayscale images Obrazy ve stupních šedi @@ -3390,6 +3426,12 @@ antiAlias Sharp Ostré LF (macOS, Linux) LF (macOS, Linux) CRLF (Windows) CRLF (Windows) Text Export Options Možnosti exportu textu + Chinese Big 5 Čínština Big 5 + Cyrillic Cyrilice + Greek Řečtina + Turkish Turečtina + Baltic Baltské jazyky + Central European Středoevropské jazyky Character Set: Znaková sada: Join the lines of each paragraph Spojit řádky každého odstavce Line Breaks Zalomení řádků @@ -3419,6 +3461,9 @@ antiAlias Sharp Ostré Variable Options Možnosti proměnné Define a variable first Nejprve definujte proměnnou Adjust Adjoining Width Points Upravit sousední body šířky + Incoming Příchozí + Outgoing Odchozí + Single Width Only Pouze jedna šířka Keep both sides the same width Zachovat stejnou šířku obou stran Side 1: Strana 1: Side 2: Strana 2: @@ -3532,9 +3577,17 @@ theme Appearance Motiv Break Link to Symbol Zrušit propojení se symbolem Brush Definition Definice štětce Brush Options… Možnosti štětce… + Options of Selected Object… Možnosti vybraného objektu… + Options of Selected Object Možnosti vybraného objektu +@msg no path painted with a brush is selected není vybrána žádná cesta malovaná štětcem +@msg the selected paths are painted with brushes of different types vybrané cesty jsou malovány štětci různých typů +@msg give `params` or `reset`, not both zadejte `params` nebo `reset`, ne obojí +@msg a bristle brush has no options of its own on a path štětinový štětec nemá na cestě vlastní možnosti Current Brush Aktuální štětec Current Symbol Aktuální symbol Delete Brush Odstranit štětec + Delete Color Odstranit barvu + Restore Generated Table Obnovit vygenerovanou tabulku Delete Symbol Odstranit symbol Delete the selected symbol? Odstranit vybraný symbol? Delete the selected symbols? Odstranit vybrané symboly? @@ -3662,6 +3715,11 @@ theme Appearance Motiv Objects Objekty Paths Cesty Path Length Délka cest + Grid Size Velikost mřížky + Grid Colors Barvy mřížky + Flattener Preset Přednastavení sloučení + X X + Y Y Add Guide Přidat vodítko Edit Selection Upravit výběr Recall Selection Vyvolat výběr @@ -3813,6 +3871,7 @@ theme Appearance Motiv Select Art Vybrat kresbu Set Current Layer Nastavit aktuální vrstvu Flatten Artwork Sloučit kresbu + Locate Layer Najít vrstvu Locate Object Najít objekt Lock Others Zamknout ostatní Merge Selected Sloučit vybrané @@ -3989,6 +4048,7 @@ theme Appearance Motiv 90° & 45° Angles Úhly 90° a 45° 90° Angles Úhly 90° Additional Plug-ins Folder Další složka zásuvných modulů + Plug-in Instruction Budget Rozpočet instrukcí zásuvných modulů Additional Fonts Folder Další složka písem Alignment Guides Vodítka zarovnání Anchor Points, Handle, and Bounding Box Display Zobrazení kotevních bodů, úchytů a ohraničovacího rámečku @@ -4015,6 +4075,7 @@ theme Appearance Motiv Data Recovery Obnovení dat Default Language Výchozí jazyk Disable Auto Add/Delete Vypnout automatické přidávání/odstraňování + Interpolate Control Points When Moving Anchors Interpolovat směrové úchyty při přesouvání kotevních bodů Display All Blacks Accurately Zobrazovat všechny černé přesně Display All Blacks as Rich Black Zobrazovat všechny černé jako sytou černou Display Bitmaps as Anti-aliased Images in Pixel Preview Zobrazovat bitmapy v náhledu obrazových bodů vyhlazené @@ -4031,6 +4092,7 @@ theme Appearance Motiv Enable Rubber Band for Povolit gumovou čáru pro Enable Touch Gestures Povolit dotyková gesta Switch Selection and Drawing Modes Přepnout mezi režimem výběru a kreslení + Select Last Selection Tool Vybrat poslední nástroj výběru Enable Touch Workspace Povolit dotykový pracovní prostor English: UK Angličtina: Spojené království Every (minutes) Každých (minut) @@ -4116,6 +4178,9 @@ theme Appearance Motiv Printing / Exporting Tisk / export Real-time Drawing and Editing Kreslení a úpravy v reálném čase Use Monitor Profile for Canvas Použít profil monitoru pro plátno + Refresh Monitor Profile Obnovit profil monitoru +@msg turn on Use Monitor Profile for Canvas first nejprve zapněte „Použít profil monitoru pro plátno“ +@msg this build doesn't read display profiles tato verze nečte profily displejů The canvas is drawn in sRGB. Plátno se vykresluje v sRGB. Canvas display profile: Profil displeje pro plátno: The system matches the window to the display's colors. Systém přizpůsobuje okno barvám displeje. @@ -4177,6 +4242,7 @@ theme Appearance Motiv Scroll Sideways with Cmd/Ctrl + Wheel Posouvat vodorovně kolečkem s Cmd/Ctrl Scrub Numeric Fields by Dragging Měnit číselné hodnoty tažením Linux Display Server Zobrazovací server Linuxu + Low-Latency Drawing Kreslení s nízkou latencí Print Preview Náhled tisku Print Setup Nastavení tisku Bitmap Bitmapa @@ -4385,6 +4451,8 @@ axis Both Obě Reset Tracking and Kerning Obnovit prostrkání a vyrovnání párů Reset Horizontal Scale Obnovit vodorovnou změnu velikosti Highlight Font Name Zvýraznit název písma + Highlight Font Size Zvýraznit velikost písma + Other… Jiná… Highlight Kerning Zvýraznit vyrovnání párů Highlight Tracking Zvýraznit prostrkání Step Type Krokovat text @@ -4520,6 +4588,9 @@ font-technology Variable Variabilní Search commands, tools, panels and effects… Hledat příkazy, nástroje, panely a efekty… No commands match Žádný příkaz neodpovídá {pos} of {total}: {name} {pos} z {total}: {name} + No menu item Žádná položka nabídky + Toolbar Panel nástrojů + {toolbar}, in the {tool} group {toolbar}, ve skupině {tool} @plural {n} result|{n} results {n} výsledek|{n} výsledky|{n} výsledků @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} z {n} výsledku. Pište dál a výsledky se zúží.|{shown} z {n} výsledků. Pište dál a výsledky se zúží.|{shown} z {n} výsledků. Pište dál a výsledky se zúží. Recent Commands Nedávné příkazy @@ -4556,6 +4627,7 @@ font-technology Variable Variabilní The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Kolečko myši s podrženou klávesou Cmd/Ctrl posouvá plátno do stran. Dragging sideways on a numeric field's label changes the field's value. Tažení do stran po popisku číselného pole mění hodnotu pole. A two-finger rotate gesture on a trackpad rotates the canvas view. Gesto otočení dvěma prsty na trackpadu otáčí zobrazení plátna. + When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Když přesouváte kotvové body, každá křivka s jedním přesunutým koncem si zachová tvar vůči svým koncům. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Podržení zkratky nástroje vybere nástroj, dokud ji nepustíte, a pak se znovu vybere předchozí nástroj. Shows the bounding box while you move the selection or draw a shape. Zobrazí ohraničovací rámeček, když přesouváte výběr nebo kreslíte tvar. Create Trim Marks draws Japanese-style marks instead of Roman ones. Vytvořit značky ořezu nakreslí značky v japonském stylu místo římských. @@ -4586,6 +4658,29 @@ font-technology Variable Variabilní The unit for East Asian type measurements, which no field uses yet. Jednotka pro míry východoasijského písma, kterou zatím žádné pole nepoužívá. When on, a number typed without a unit into a field in picas is read in points. Když je zapnuto, číslo zadané bez jednotky do pole v pica se čte v bodech. With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options. S volbou XML ID se názvy objektů zobrazují jako XML ID ve Vrstvách, Proměnných a Možnostech vrstvy. + The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl. Krok velikosti textu a prokladu: Cmd/Ctrl+Shift+. a Cmd/Ctrl+Shift+, změní velikost o jeden krok, s Alt o pět; ve vodorovném textu Alt se šipkou nahoru nebo dolů změní proklad o jeden krok, s Cmd/Ctrl o pět. + The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl. Krok prostrkání a vyrovnání párů, v tisícinách em: ve vodorovném textu Alt se šipkou doleva nebo doprava změní vyrovnání páru u kurzoru nebo prostrkání vybraného textu o jeden krok, s Cmd/Ctrl o pět. + The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. Krok posunu účaří: ve vodorovném textu Alt a Shift se šipkou nahoru nebo dolů posunou účaří o jeden krok, s Cmd/Ctrl o pět. + Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. Zobrazí možnosti japonského a jiného východoasijského textu v panelech Znak, Odstavec, OpenType a Glyfy a příkaz Složená písma. + Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. Zobrazí možnosti arabského, hebrejského a indického textu v panelech Znak a Odstavec, například směr odstavce, kašídy a číslice. + The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. Nástroje výběru vybírají text jen na jeho účaří, rámečku plošného textu nebo jeho cestě, ne kdekoli uvnitř jeho ohraničení. + Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. Nabídky písem uvádějí každé písmo pod anglickým názvem; po vypnutí písmo, které má i název ve vlastním jazyce, ukáže tento název. + New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. Nový plošný text začíná se zapnutou automatickou velikostí, takže obdélníkový rámeček vodorovného textu roste nebo se zmenšuje na výšku podle textu. + Font lists and the Type › Font menu show a sample of each font beside its name. Seznamy písem a nabídka Písmo zobrazují vedle názvu ukázku každého písma. + Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on. Ukázky písem se kreslí tmavým textem na bílé bez ohledu na jas rozhraní; platí to jen při zapnutých náhledech písem v nabídkách. + How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is. Jak vysoký je každý řádek v seznamech polí písma, například v panelu Znak, a tedy jak velká je každá ukázka. + How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first. Kolik naposledy použitých písem, od 1 do 15, zobrazují Nedávná písma a seznamy písem, nejnovější první. + When you change the font or font style of text, characters the new font has no glyph for keep the font they had. Když změníte písmo nebo řez písma textu, znaky, pro které nové písmo nemá glyf, si ponechají své dosavadní písmo. + A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export. Růžové zvýraznění na plátně označuje glyfy nahrazené funkcemi OpenType, například ligatury; netiskne se ani neexportuje. + With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from. S nástrojem Text výběr jednoho znaku zobrazí vedle něj na plátně řadu jeho alternativních glyfů k výběru. + A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export. Růžové zvýraznění na plátně označuje text vykreslený náhradním písmem, protože jeho písmo chybí; netiskne se ani neexportuje. + New type made with a Type tool starts with placeholder text, selected, so typing replaces it. Nový text vytvořený textovým nástrojem začíná vybraným zástupným textem, který psaní nahradí. + Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list. Napsání značky seznamu, například 1. nebo *, a pak mezery na začátku odstavce změní odstavec na seznam. + Fonts in this folder show in the font menus and can be used without being installed. Písma v této složce se zobrazí v nabídkách písem a lze je použít bez instalace. + Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows. Použití grafického stylu na text odebere znakům jejich vlastní výplň nebo tah tam, kde ho styl má, takže je vidět barva stylu. + Align and Distribute measure point type by the ink of its glyphs instead of its em box. Zarovnat a Rozmístit měří bodový text podle inkoustu jeho glyfů místo podle jeho čtverce em. + Align and Distribute measure area type by the ink of its glyphs instead of its frame. Zarovnat a Rozmístit měří plošný text podle inkoustu jeho glyfů místo podle jeho rámečku. + The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box. Ohraničovací rámeček a panel Transformace měří bodový text podle inkoustu jeho glyfů místo podle jeho čtverce em. Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply. Přichytává kreslení, přesouvání a změnu velikosti k dělení mřížky, i když je mřížka skrytá; dokud je zapnuto, Přichytávat k obrazovým bodům se neuplatní. The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead. Barva vodítek, která nejsou vybraná; pracovní plocha se Štítkem vodítek kreslí svá vodítka v barvě štítku. Draws guides as solid lines or as dots, including the guides already in the document. Kreslí vodítka jako plné čáry nebo jako tečky, včetně vodítek, která už v dokumentu jsou. @@ -4629,6 +4724,8 @@ font-technology Variable Variabilní Couldn't paste from the clipboard: {e} Nelze vložit ze schránky: {e} Channel Kanál Circle Kruh + Circle Tool Nástroj Kruh + Circle too large Kruh je příliš velký Clip to Art Oříznout podle kresby Colorize Obarvit Gamma Gama @@ -4863,6 +4960,13 @@ imageTrace Outline Obrys Show External Script Warning Zobrazit upozornění u externích skriptů A Script Is Running Běží skript Script Alert Upozornění skriptu + Script File Access Přístup skriptu k souborům + The script asks to read a file you choose. Skript žádá o čtení souboru, který vyberete. + The script asks to read and write a file you choose. Skript žádá o čtení a zápis souboru, který vyberete. + The script asks to read and write a folder you choose, with everything in it. Skript žádá o čtení a zápis složky, kterou vyberete, se vším, co obsahuje. + Allow Once Povolit jednou + Always Allow This Script Vždy povolit tento skript + Deny Zamítnout A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Skript může měnit otevřené dokumenty a prostřednictvím příkazů, které spouští, zapisovat soubory. Spouštějte jen skripty, kterým důvěřujete. Do not show this warning again Toto upozornění již nezobrazovat Stop the script and undo what it did? Then quit again. Zastavit skript a vrátit jeho změny? Potom aplikaci ukončete znovu. @@ -4879,6 +4983,8 @@ imageTrace Outline Obrys @msg the script is no longer in the Scripts folder skript už není ve složce Scripts Some scripts were not listed Některé skripty nebyly uvedeny The Scripts folder cannot be read Složku Scripts nelze přečíst + Loading scripts… Načítání skriptů… + The Scripts folder is still being read Složka Scripts se stále načítá @msg the script's run is no longer available běh skriptu již není k dispozici @msg a failed command changed undo steps that could not be put back, so the script was stopped neúspěšný příkaz změnil kroky zpět, které nebylo možné obnovit, proto byl skript zastaven @msg a recovery copy could not be written, so the script was not run záložní kopii se nepodařilo zapsat, proto skript nebyl spuštěn @@ -4891,8 +4997,6 @@ imageTrace Outline Obrys @msg Script file could not be read Soubor skriptu se nepodařilo přečíst @msg Script folder has more than 2,048 entries Složka skriptu má více než 2 048 položek @msg Script file open mode must be r, w, e or a Režim otevření souboru skriptu musí být r, w, e nebo a -@msg Script file writing is not available Zápis souborů skriptu není k dispozici -@msg Script file dialogs are not available Dialogy souborů skriptu nejsou k dispozici @msg Script files cannot be opened in another application Soubory skriptu nelze otevřít v jiné aplikaci @msg Script file access is unavailable on the web Přístup k souborům skriptu není na webu k dispozici @msg Script has 256 files open Skript má otevřeno 256 souborů @@ -5008,8 +5112,37 @@ liquify-list-end {0}, {1} {0} a {1} @msg the main script engine is new for each run and is never kept, so it cannot be dropped hlavní skriptovací jádro je pro každý běh nové a nikdy se neuchovává, proto je nelze zahodit @msg there is no script engine named {name} skriptovací jádro s názvem {name} neexistuje @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` je jen pro běh, kde se nemá koho zeptat: v aplikaci odpovídá na každý dialog uživatel +@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` musí být celé číslo od 1 do {_1} +@msg `args{place}` is nested more than 64 levels deep `args{place}` je vnořen hlouběji než 64 úrovní +@msg `args` must be an object `args` musí být objekt +@msg `args` is larger than 1 MiB `args` je větší než 1 MiB +@msg `path` is empty `path` je prázdný +@msg `installed` takes a `path`, not a `source` `installed` přijímá `path`, ne `source` +@msg `path` must name a .js or .jsx file `path` musí označovat soubor .js nebo .jsx +@msg give exactly one of `path` and `source` zadejte právě jedno z `path` a `source` @msg Running a script Běží skript @msg Copied the script report Zpráva o skriptu zkopírována +@msg Script file access denied: {path} Přístup skriptu k souborům byl odepřen: {path} +@msg Script file access to the app's own folders is not allowed Skript nemá povolen přístup k vlastním složkám aplikace +@msg Script file cannot encode the text Soubor skriptu nemůže zakódovat text +@msg Script file could not be written Soubor skriptu nelze zapsat +@msg Script file dialogs need a person to answer them Dialogy souborů skriptu potřebují osobu, která na ně odpoví +@msg Script file is not open for writing Soubor skriptu není otevřený pro zápis +@msg Script file name is already in use Název souboru skriptu se už používá +@msg Script file name must be a name without a folder Název souboru skriptu musí být název bez složky +@msg Script file permission can be kept only for a script run from a file Oprávnění k souborům lze zachovat jen pro skript spuštěný ze souboru +@msg Script file permission could not be saved Oprávnění skriptu k souborům nelze uložit +@msg Script folder is not empty Složka skriptu není prázdná +@msg Script files cannot make aliases Soubory skriptu nemohou vytvářet aliasy +@msg Script file hidden setting cannot be changed Nastavení skrytí souboru skriptu nelze změnit +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: dialog souboru nelze otevřít uvnitř zpětného volání vestavěné funkce, getteru, převodu ani souboru, který spouští $.evalFile; volejte jej z vlastního kódu skriptu +@msg the script wrote more file data than one run may write (32 MiB) skript zapsal více dat souborů, než smí zapsat jeden běh (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` pro dialog souboru skriptu musí být jedna z hodnot: once, always, deny, stop +@msg choose a file or folder first, or deny nejprve vyberte soubor nebo složku, nebo odmítněte +@msg the script file permissions could not be saved: {e} oprávnění skriptů k souborům nelze uložit: {e} +@msg this script's file access can be allowed only once přístup tohoto skriptu k souborům lze povolit jen jednou +@msg Only the person at the keyboard can allow a script's file access Přístup skriptu k souborům může povolit jen člověk u klávesnice +@msg A script is given at most 2,048 files: the files picked after them were left out Skript dostane nejvýše 2 048 souborů: soubory vybrané po nich byly vynechány @msg Copied the link info Informace o propojení zkopírovány @msg Corners edits the corners of a path Rohy upravuje rohy cesty @msg Couldn't copy to the system clipboard: {e} Nelze kopírovat do systémové schránky: {e} @@ -5085,6 +5218,7 @@ liquify-list-end {0}, {1} {0} a {1} @msg Saved {path} Uloženo: {path} @msg Select text or click into text with the Type tool to insert glyphs Glyfy vložíte, když vyberete text nebo do něj kliknete nástrojem Text @msg Shape Builder: no region under the pointer Tvorba tvarů: pod ukazatelem není žádná oblast +@msg Shape Builder: select all paths you want to merge Tvorba tvarů: vyberte všechny cesty, které chcete sloučit @msg Shape Builder: select paths or compound paths Tvorba tvarů: vyberte cesty nebo složené cesty @msg Show All Hidden Attributes: nothing is hidden Zobrazit všechny skryté atributy: nic není skryto @msg Split Into Grid: select paths large enough for the grid Rozdělit do mřížky: vyberte cesty dost velké pro mřížku @@ -5139,6 +5273,8 @@ liquify-list-end {0}, {1} {0} a {1} @msg `{min_key}` is greater than `{max_key}` `{min_key}` je větší než `{max_key}` @msg give at least one of `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` zadejte alespoň jeden z parametrů `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` musí být grayscale, rgb, hsb, cmyk nebo websafe +@msg `view` must be wheel or box `view` musí být wheel nebo box +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` musí být hue, saturation, brightness, red, green nebo blue @msg `{k}` must be [x, y] `{k}` musí být [x, y] @msg `{name}` has no options `{name}` nemá žádné možnosti @msg `{name}` is a built-in workspace; choose another name `{name}` je vestavěný pracovní prostor; zvolte jiný název @@ -5227,6 +5363,7 @@ liquify-list-end {0}, {1} {0} a {1} @msg bad trailer chybný trailer @msg balance must be between 0 and 100 balance musí být mezi 0 a 100 @msg batch step {_1} (`{id}`) failed: {e} krok dávky {_1} (`{id}`) selhal: {e} +@msg action step {_1} (`{id}`) failed: {reason} krok akce {_1} (`{id}`) selhal: {reason} @msg brightness must be dark|mediumDark|mediumLight|light brightness musí být dark|mediumDark|mediumLight|light @msg can't encode the document: {0} dokument nelze zakódovat: {0} @msg can't parse shortcut `{c}` klávesovou zkratku `{c}` nelze analyzovat @@ -5246,6 +5383,7 @@ liquify-list-end {0}, {1} {0} a {1} @msg choose a folder to export to zvolte složku pro export @msg choose a location for the package zvolte umístění balíčku @msg clipboard is empty schránka je prázdná +@msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: v tabulce barev musí zůstat alespoň jedna barva @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` není barva jako "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: nejvýše {MAX_TABLE} barev @msg command `{0}` is not available right now: {1} příkaz `{0}` nyní není k dispozici: {1} @@ -5313,9 +5451,15 @@ liquify-list-end {0}, {1} {0} a {1} @msg no PNG encoder chybí kodér PNG @msg no active document žádný aktivní dokument @msg no active perspective plane žádná aktivní perspektivní rovina +@msg the perspective grid is hidden perspektivní mřížka je skrytá +@msg Automatic Plane Positioning is off: turn on anchorPoint or gridlineIntersection (perspective.widget.options) Automatické umístění roviny je vypnuté: zapněte anchorPoint nebo gridlineIntersection (perspective.widget.options) +@msg anchorPoint must be true or false anchorPoint musí být true nebo false +@msg gridlineIntersection must be true or false gridlineIntersection musí být true nebo false +@msg tolerance must be 0 or more tolerance musí být 0 nebo více +@msg give `at` or `clear`, not both zadejte `at` nebo `clear`, ne obojí @msg no anchor points selected nejsou vybrány žádné kotevní body -@msg `points` must be three [x, y] pairs of numbers `points` musí být tři dvojice čísel [x, y] -@msg direct-select three anchor points, or give `points` vyberte přímým výběrem tři kotevní body, nebo zadejte `points` +@msg `points` must be two or three [x, y] pairs of numbers `points` musí být dvě nebo tři dvojice čísel [x, y] +@msg direct-select two or three anchor points, or give `points` vyberte přímým výběrem dva nebo tři kotevní body, nebo zadejte `points` @msg no circle passes through these points: two are the same or all three lie on one line těmito body neprochází žádná kružnice: dva jsou stejné nebo všechny tři leží na jedné přímce @msg no app to open files here zde chybí aplikace pro otevírání souborů @msg no artboard žádná pracovní plocha @@ -5417,6 +5561,9 @@ liquify-list-end {0}, {1} {0} a {1} @msg no such user library taková uživatelská knihovna neexistuje @msg no such view takové zobrazení neexistuje @msg no such width point takový bod šířky neexistuje +@msg `single` must be `incoming` or `outgoing` `single` musí být `incoming` nebo `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` a `outIndex` musí být dvě poloviny jednoho nespojitého bodu šířky +@msg a discontinuous width point keeps its place nespojitý bod šířky si zachovává své místo @msg no swatch `{name}` položka vzorníku `{name}` neexistuje @msg no swatch library `{l}` (see swatch.library.list) knihovna vzorníku `{l}` neexistuje (viz swatch.library.list) @msg no symbol instances selected nejsou vybrány žádné instance symbolů @@ -5675,6 +5822,13 @@ liquify-list-end {0}, {1} {0} a {1} @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} více než {MAX_CSV_ROWS} sad dat: Importovat sady dat načte nejvýše {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} více než {MAX_CSV_COLS} proměnných: Importovat sady dat načte nejvýše {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} proměnné, které nejsou textové, byly vynechány: {kinds} +variable-kind Visibility Viditelnost +variable-kind Linked File Propojený soubor +variable-kind Graph Data Data grafu +variable-kind Unknown Neznámý +variable-list-two {0}, {1} {0} a {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} a {1} @msg a new document won't read these variables back with their kind: {names} nový dokument tyto proměnné nenačte zpět s jejich druhem: {names} @msg a new document refuses this file because of these variables: {names} nový dokument tento soubor kvůli těmto proměnným odmítne: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them záhlaví `{header}` pro `{name}` by se načetlo jako proměnná `{other}`: jednu z nich přejmenujte @@ -5700,6 +5854,8 @@ liquify-list-end {0}, {1} {0} a {1} @msg {label}: lost track of a shape's style {label}: ztratil se styl tvaru @msg {label}: select paths {label}: vyberte cesty @msg {label}: select paths, compound paths, groups or text {label}: vyberte cesty, složené cesty, skupiny nebo text +@msg a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first čára nebo jiná otevřená cesta, která neohraničuje žádnou plochu, nemění tvar výsledku; chcete-li ji zahrnout, použijte na ni nejprve Objekt › Cesta › Převést tah na obrys +@msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first {label} vytvořil prázdný výsledek: čára nebo jiná otevřená cesta neohraničuje žádnou plochu; chcete-li ji zahrnout, použijte na ni nejprve Objekt › Cesta › Převést tah na obrys @msg {label}… {label}… @msg {name}: CRC mismatch {name}: nesouhlasí CRC @msg {name}: no local header {name}: chybí lokální hlavička @@ -5726,6 +5882,9 @@ liquify-list-end {0}, {1} {0} a {1} @msgplural Discarded {n} recovered document|Discarded {n} recovered documents Zahozen {n} obnovený dokument|Zahozeny {n} obnovené dokumenty|Zahozeno {n} obnovených dokumentů @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them Obnoven {n} dokument; pokud ho chcete zachovat, uložte ho|Obnoveny {n} dokumenty; pokud je chcete zachovat, uložte je|Obnoveno {n} dokumentů; pokud je chcete zachovat, uložte je @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} Otevřeno, {n} poznámka: {first}|Otevřeno, {n} poznámky: {first}|Otevřeno, {n} poznámek: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Zkopírováno, {n} poznámka: {first}|Zkopírováno, {n} poznámky: {first}|Zkopírováno, {n} poznámek: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Vyjmuto, {n} poznámka: {first}|Vyjmuto, {n} poznámky: {first}|Vyjmuto, {n} poznámek: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Obraz vektorizován, {n} poznámka: {first}|Obraz vektorizován, {n} poznámky: {first}|Obraz vektorizován, {n} poznámek: {first} @msgplural {notice}. Opened with {n} note: {first}|{notice}. Opened with {n} notes: {first} {notice}. Otevřeno, {n} poznámka: {first}|{notice}. Otevřeno, {n} poznámky: {first}|{notice}. Otevřeno, {n} poznámek: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} Uloženo: {path}, {n} poznámka: {first}|Uloženo: {path}, {n} poznámky: {first}|Uloženo: {path}, {n} poznámek: {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first Vložen {n} obrázek; chybí {missing}: nejprve je znovu propojte|Vloženy {n} obrázky; chybí {missing}: nejprve je znovu propojte|Vloženo {n} obrázků; chybí {missing}: nejprve je znovu propojte @@ -5752,6 +5911,8 @@ liquify-list-end {0}, {1} {0} a {1} @msg All colors are within the CMYK gamut Všechny barvy jsou v gamutu CMYK @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} barva je mimo gamut CMYK|{n} barvy jsou mimo gamut CMYK|{n} barev je mimo gamut CMYK @msg Unembedded to {_1} Vložení zrušeno, uloženo do: {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} Vložení zrušeno u {n} obrázku, uloženo do: {folder}|Vložení zrušeno u {n} obrázků, uloženo do: {folder}|Vložení zrušeno u {n} obrázků, uloženo do: {folder} +@msg every numbered name for {name} is taken in that folder v této složce jsou obsazena všechna číslovaná jména pro {name} @msg Reset {_1} Obnoveno: {_1} @msg Sent to {_1} Odesláno do {_1} @msg {_1} files Soubory {_1} @@ -5767,6 +5928,8 @@ liquify-list-end {0}, {1} {0} a {1} @msg Reload the page to go on (changes not saved yet may be lost). Pokračujte obnovením stránky (dosud neuložené změny se mohou ztratit). @msg tool (a tool id) is required tool (ID nástroje) je povinný @msg {tool} isn't in a toolbar group of several tools {tool} není ve skupině panelu nástrojů s více nástroji +@msg Presentation Mode hides the toolbars: change the screen mode to show them Režim prezentace skrývá panely nástrojů: zobrazíte je změnou režimu obrazovky +@msg Tab has hidden the toolbars: press Tab to show them Klávesa Tab skryla panely nástrojů: zobrazíte je stisknutím klávesy Tab @msg onto must name a panel floating in another group onto musí určovat panel plovoucí v jiné skupině @msg below and above must name a panel floating in another group below a above musí určovat panel plovoucí v jiné skupině @msg give only one of onto, below and above zadejte jen jedno z onto, below a above @@ -5855,6 +6018,9 @@ liquify-list-end {0}, {1} {0} a {1} @msg automation path rejected: outside the read root {root}: {path} cesta automatizace odmítnuta: mimo kořen pro čtení {root}: {path} @msg automation path rejected: outside the read roots {roots}: {path} cesta automatizace odmítnuta: mimo kořeny pro čtení {roots}: {path} @msg a linked JavaScript file is outside the read roots propojený soubor JavaScript je mimo kořeny pro čtení +@msg a linked image file is outside the read roots propojený soubor obrázku je mimo kořeny pro čtení +@msg a linked file's export folder is outside the read roots exportní složka propojeného souboru je mimo kořeny pro čtení +@msg a linked file's editing data can't be read to check it against the read roots editační data propojeného souboru nelze přečíst a ověřit vůči kořenům pro čtení @msg automation path rejected: outside the write root {root}: {path} cesta automatizace odmítnuta: mimo kořen pro zápis {root}: {path} @msg automation path rejected: outside the write roots {roots}: {path} cesta automatizace odmítnuta: mimo kořeny pro zápis {roots}: {path} @msg automation path rejected: path is empty cesta automatizace odmítnuta: cesta je prázdná @@ -6142,6 +6308,7 @@ liquify-list-end {0}, {1} {0} a {1} Ascent Výška nad účařím Cap Height Výška verzálek x Height Výška x + Em Box Height Výška čtverčíku Justify Do bloku First Baseline První účaří Vertical Align Svislé zarovnání @@ -6283,6 +6450,7 @@ mark-style Japanese Japonské Cove Žlábek Depth Hloubka Front Zepředu + Side Z boku Isometric Bottom Izometricky zdola Isometric Left Izometricky zleva Isometric Right Izometricky zprava @@ -6377,7 +6545,7 @@ mark-style Japanese Japonské @msg each of `{GRAPHICS}` must be an object každá položka `{GRAPHICS}` musí být objekt @msg `{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}` položky `{GRAPHICS}` přijímají symbol, face, x, y, scale a rotation, ne `{k}` @msg each of `{GRAPHICS}` needs `symbol`, the name of a symbol každá položka `{GRAPHICS}` potřebuje `symbol`, název symbolu -@msg `{GRAPHICS}` face must be front or back face v `{GRAPHICS}` musí být front nebo back +@msg `{GRAPHICS}` face must be front, back or side face v `{GRAPHICS}` musí být front, back nebo side @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} v `{GRAPHICS}` musí být číslo od {lo} do {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` musí být pole @msg Graphics map onto the Plane, Extrude and Revolve object types Grafika se mapuje na typy objektu Rovina, Vysunutí a Rotační těleso @@ -7380,6 +7548,12 @@ anchor Points: Body: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` musí být "free", "keepAngles" nebo "symmetric" @msg `{key}` must be [x, y] `{key}` musí být [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Převodník jednotek + Unit Converter Panel Panel Převodník jednotek + Copy with Units Kopírovat s jednotkami + From Selection Z výběru + # Color Effects add-on: Select by Color Kind. Select by Color Kind Vybrat podle druhu barvy Objects with Spot Colors Objekty s přímými barvami @@ -7604,6 +7778,14 @@ breakText Glyphs Glyfy Remove Gaps Odstranit mezery @msg that makes too many pieces (at most 100000): make the dashes longer tím vznikne příliš mnoho dílů (nejvýše 100000): prodlužte čárky @msg select paths, or segments, to divide vyberte cesty nebo segmenty k rozdělení +# Path Precision Tools add-on: Smooth Bridge. + Smooth Bridge… Hladký most… + Smooth Bridge Hladký most + Keep Originals Zachovat originály +@msg select two circles to bridge vyberte dva kruhy k propojení +@msg one circle is inside the other jeden kruh je uvnitř druhého +@msg the circles are too far apart for this radius: raise the radius kruhy jsou pro tento poloměr příliš daleko od sebe: zvětšete poloměr +@msg the circles are too far apart for this radius kruhy jsou pro tento poloměr příliš daleko od sebe # Path Precision Tools add-on: Common Tangents. Common Tangents… Společné tečny… Common Tangents Společné tečny @@ -8308,7 +8490,7 @@ breakText Glyphs Glyfy @msg `scale` must be a number from 0.001 to 1000 `scale` musí být číslo od 0.001 do 1000 @msg `scale` must be a number in (0, 100] `scale` musí být číslo v rozsahu (0, 100] @msg `scope.{key}` must be a non-empty array `scope.{key}` musí být neprázdné pole -@msg `scope` must be "document", {artboards} or {layers} `scope` musí být "document", {artboards} nebo {layers} +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` musí být "document", {{artboards: [index, …]}} nebo {{layers: [id, …]}} @msg `scope` must be "selection" or "document", not {other} `scope` musí být "selection" nebo "document", ne {other} @msg `script` must be a string `script` musí být řetězec @msg `seriesIndexes` is a non-empty list of series indexes `seriesIndexes` je neprázdný seznam indexů řad @@ -8387,6 +8569,8 @@ breakText Glyphs Glyfy @msg `{f}` is the copy of a document open now `{f}` je kopie právě otevřeného dokumentu @msg `{id}` is no writable format (see document.formats) `{id}` není formát, který lze zapisovat (viz document.formats) @msg `{id}` isn't a loaded library `{id}` není načtená knihovna +@msg `{file}` has no swatches of its own `{file}` nemá žádné vlastní vzorky +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` obsahuje vzorkové položky vzorníku, které soubor .vcswatches nepojme @msg `{key}` has no colours `{key}` neobsahuje žádné barvy @msg `{key}` holds more than {MAX_EDIT_WORDS} words `{key}` obsahuje více než {MAX_EDIT_WORDS} slov @msg `{key}` is a design name `{key}` je název návrhu @@ -8678,7 +8862,13 @@ breakText Glyphs Glyfy @msg colorModel must be {own} (the document's mode), grayscale or bitmap colorModel musí být {own} (režim dokumentu), grayscale nebo bitmap @msg colour groups can't go into colour groups skupiny barev nelze vkládat do skupin barev @msg colour, mode and spot apply to solid-colour swatches only colour, mode a spot platí jen pro položky vzorníku s plnou barvou -@msg column {column}: `{cell}` is a `%` column of graph data files, which are not read sloupec {column}: `{cell}` je sloupec `%` pro soubory dat grafu, které se nečtou +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path řádek {line}, sloupec {column}: soubor dat grafu `{path}` pro `{var}` je zadán relativní cestou: zadejte `base` nebo absolutní cestu +@msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} řádek {line}, sloupec {column}: soubor dat grafu pro `{var}` nelze přečíst: {e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` isn't followed: {r} řádek {line}, sloupec {column}: soubor dat grafu `{path}` pro `{var}` se nenačítá: {r} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes řádek {line}, sloupec {column}: soubor dat grafu `{path}` pro `{var}` je větší než {MAX_GRAPH_DATA_FILE} bajtů +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes řádek {line}, sloupec {column}: soubor dat grafu `{path}` pro `{var}` dává hodnotu grafu delší než {MAX_GRAPH_CSV} bajtů +@msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all řádek {line}, sloupec {column}: soubory dat grafu obsahují celkem více než {MAX_GRAPH_FILES_TOTAL} bajtů +@msg `base` is empty `base` je prázdné @msg column {column}: `{cell}` names `{name}`, which is a {_1} variable sloupec {column}: `{cell}` uvádí `{name}`, což je proměnná typu {_1} @msg column {column}: `{cell}` names no variable sloupec {column}: `{cell}` neuvádí žádnou proměnnou @msg column {column}: the variable name is longer than {MAX_NAME} characters sloupec {column}: název proměnné je delší než {MAX_NAME} znaků @@ -8689,6 +8879,7 @@ breakText Glyphs Glyfy @msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes složené tvary přijímají cesty, složené cesty, skupiny, složené tvary, text, prolnutí a obálky @msg compound {_1} must contain exactly one open path to join složený objekt {_1} musí ke spojení obsahovat právě jednu otevřenou cestu @msg connect needs a path other than the one extended connect vyžaduje jinou cestu než tu prodlužovanou +@msg connect needs extend connect vyžaduje extend @msg connect needs id connect vyžaduje id @msg connect path has no open end cesta v connect nemá žádný otevřený konec @msg continuation must be an array of path chunks continuation musí být pole úseků cesty @@ -9201,7 +9392,7 @@ breakText Glyphs Glyfy @msg nothing to print: every artboard picked is blank není co tisknout: každá zvolená pracovní plocha je prázdná @msg nothing to print: the document has no art that prints není co tisknout: dokument nemá žádnou kresbu, která se tiskne @msg nothing to repeat není co opakovat -@msg numbers out of order in {_1} quantifier čísla v kvantifikátoru {_1} jsou ve špatném pořadí +@msg numbers out of order in {{}} quantifier čísla v kvantifikátoru {{}} jsou ve špatném pořadí @msg object is not a path objekt není cesta @msg object transparency cannot be sampled onto highlighted characters; disable Transparency in Eyedropper Options or select the whole object průhlednost objektu nelze nabrat na zvýrazněné znaky; vypněte Průhlednost ve volbách kapátka nebo vyberte celý objekt @msg object {_1} can't be set as point type objekt {_1} nelze nastavit jako bodový text @@ -9561,7 +9752,7 @@ breakText Glyphs Glyfy @msg the page has no area stránka nemá plochu @msg the page's type in an unread object's box isn't in its page art text stránky v rámečku nepřečteného objektu není v kresbě jeho stránky @msg the paint behind the proxy is not a gradient nátěr za aktivním políčkem není přechod -@msg the paint is not a freeform gradient (apply one with paint.editGradient {kind}) nátěr není volný přechod (použijte ho pomocí paint.editGradient {kind}) +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) nátěr není volný přechod (použijte ho pomocí paint.editGradient {{kind: "freeform"}}) @msg the parameters or body do not form one function parametry nebo tělo netvoří jednu funkci @msg the parent must be a layer or sublayer nadřazený prvek musí být vrstva nebo podvrstva @msg the pasted SVG filter {name} draws differently from the document's filter of that name, and no free name fits it vložený filtr SVG {name} se vykresluje jinak než filtr dokumentu s tímto názvem a nehodí se pro něj žádný volný název @@ -9917,3 +10108,13 @@ breakText Glyphs Glyfy @msg A panel is not joined to the rest by a crease. Panel není se zbytkem spojen žádnou linií bigu. @msg A fold line is on a non-printing layer. Linie skladu je na netisknutelné vrstvě. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panely: {panels}, panty: {hinges}, chyby: {errors}, upozornění: {warnings} + Fold Preview Náhled skládání + Fold Složení + Show Fold Lines Zobrazit linie skladu + Three-Quarter Tři čtvrtě + Open a document to preview its folded shape. Otevřete dokument, abyste zobrazili náhled jeho složeného tvaru. +@msg Check the fold lines first. Nejprve zkontrolujte linie skladu. +@msg Panels: {panels}, hinges: {hinges} Panely: {panels}, panty: {hinges} +@msg Other blanks not shown: {count} Další přířezy nejsou zobrazeny: {count} +@msg A joint does not close by {gap} pt. Spoj se nezavírá o {gap} pt. +@msg Two panels pass through each other. Dva panely procházejí jeden druhým. diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 08100f593f..d5d909f8df 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -75,14 +75,33 @@ @msg Script file could not be read Scriptfilen kunne ikke læses @msg Script folder has more than 2,048 entries Scriptmappen har mere end 2.048 elementer @msg Script file open mode must be r, w, e or a Scriptfilens åbningstilstand skal være r, w, e eller a -@msg Script file writing is not available Skrivning af scriptfiler er ikke tilgængelig -@msg Script file dialogs are not available Scriptfildialoger er ikke tilgængelige @msg Script files cannot be opened in another application Scriptfiler kan ikke åbnes i et andet program @msg Script file access is unavailable on the web Scriptets filadgang er ikke tilgængelig på nettet @msg Script has 256 files open Scriptet har 256 filer åbne @msg Script file path exceeds 32,767 characters Scriptfilens sti er længere end 32.767 tegn @msg Script folder mask takes too many steps to match Scriptmappens maske kræver for mange trin at matche @msg the script opened more file data than one run may open (32 MiB) scriptet åbnede flere fildata, end én kørsel må åbne (32 MiB) +@msg Script file access denied: {path} Scriptets filadgang blev nægtet: {path} +@msg Script file access to the app's own folders is not allowed Scripts må ikke få adgang til programmets egne mapper +@msg Script file cannot encode the text Scriptfilen kan ikke kode teksten +@msg Script file could not be written Scriptfilen kunne ikke skrives +@msg Script file dialogs need a person to answer them Scriptets fildialoger skal besvares af en person +@msg Script file is not open for writing Scriptfilen er ikke åben for skrivning +@msg Script file name is already in use Scriptfilens navn er allerede i brug +@msg Script file name must be a name without a folder Scriptfilens navn skal være et navn uden en mappe +@msg Script file permission can be kept only for a script run from a file Filtilladelsen kan kun beholdes for et script, der køres fra en fil +@msg Script file permission could not be saved Scriptets filtilladelse kunne ikke gemmes +@msg Script folder is not empty Scriptmappen er ikke tom +@msg Script files cannot make aliases Scriptfiler kan ikke oprette aliasser +@msg Script file hidden setting cannot be changed Scriptfilens indstilling for skjult kan ikke ændres +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: en fildialog kan ikke åbnes i et callback fra en indbygget funktion, en getter, en konvertering eller en fil, som $.evalFile kører; kald den fra scriptets egen kode +@msg the script wrote more file data than one run may write (32 MiB) scriptet skrev flere fildata, end én kørsel må skrive (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` for et scripts fildialog skal være en af: once, always, deny, stop +@msg choose a file or folder first, or deny vælg først en fil eller mappe, eller afvis +@msg the script file permissions could not be saved: {e} scriptets filtilladelser kunne ikke gemmes: {e} +@msg this script's file access can be allowed only once dette scripts filadgang kan kun tillades én gang +@msg Only the person at the keyboard can allow a script's file access Kun personen ved tastaturet kan tillade et scripts filadgang +@msg A script is given at most 2,048 files: the files picked after them were left out Et script får højst 2.048 filer: de filer, der blev valgt derefter, blev udeladt @msg File.seek: takes a position and a mode File.seek: tager en position og en tilstand @msg vc.run: give a command id, as a string vc.run: angiv et kommando-id som en streng @msg vc.run: takes a command id and an object of parameters vc.run: tager et kommando-id og et objekt med parametre @@ -216,6 +235,14 @@ liquify-list-end {0}, {1} {0} og {1} @msg is a prompt's answer, whose `value` must be a string or null er svaret på en prompt, hvis `value` skal være en streng eller null @msg must have `kind` alert, confirm or prompt skal have `kind` alert, confirm eller prompt @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` er kun til en kørsel uden nogen at spørge: i appen besvarer personen hver dialog +@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` skal være et heltal fra 1 til {_1} +@msg `args{place}` is nested more than 64 levels deep `args{place}` er indlejret mere end 64 niveauer dybt +@msg `args` must be an object `args` skal være et objekt +@msg `args` is larger than 1 MiB `args` er større end 1 MiB +@msg `path` is empty `path` er tom +@msg `installed` takes a `path`, not a `source` `installed` tager en `path`, ikke en `source` +@msg `path` must name a .js or .jsx file `path` skal angive en .js- eller .jsx-fil +@msg give exactly one of `path` and `source` angiv præcis én af `path` og `source` @msg Running a script Kører et script @msg Data Recovery can't keep copies in {path}: {e} Datagendannelse kan ikke opbevare kopier i {path}: {e} @msg Plug-ins can't be loaded from {path}: {e} Plug-ins kan ikke indlæses fra {path}: {e} @@ -406,7 +433,7 @@ liquify-list-end {0}, {1} {0} og {1} @msg each of `{GRAPHICS}` must be an object hvert element i `{GRAPHICS}` skal være et objekt @msg `{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}` elementer i `{GRAPHICS}` tager symbol, face, x, y, scale og rotation, ikke `{k}` @msg each of `{GRAPHICS}` needs `symbol`, the name of a symbol hvert element i `{GRAPHICS}` kræver `symbol`, navnet på et symbol -@msg `{GRAPHICS}` face must be front or back `{GRAPHICS}`: face skal være front eller back +@msg `{GRAPHICS}` face must be front, back or side `{GRAPHICS}`: face skal være front, back eller side @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} `{GRAPHICS}`: {key} skal være et tal fra {lo} til {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` skal være et array @msg Graphics map onto the Plane, Extrude and Revolve object types Grafik kortlægges på objekttyperne Plan, Ekstrudér og Omdrej @@ -766,6 +793,8 @@ liquify-list-end {0}, {1} {0} og {1} Check Script Kontrollér script Some scripts were not listed Nogle scripter blev ikke vist The Scripts folder cannot be read Mappen Scripts kan ikke læses + Loading scripts… Indlæser scripter… + The Scripts folder is still being read Mappen Scripts læses stadig Other Script… Andet script… Document Setup… Dokumentopsætning… Switch Units Skift enheder @@ -869,6 +898,8 @@ liquify-list-end {0}, {1} {0} og {1} Shear… Skæv… Transform Each… Transformér hver for sig… Reset Bounding Box Nulstil afgrænsningsramme + Rotate Bounding Box Rotér afgrænsningsramme + Rotate Bounding Box… Rotér afgrænsningsramme… Arrange Arrangér Bring to Front Anbring forrest Bring Forward Flyt fremad @@ -1277,6 +1308,8 @@ liquify-list-end {0}, {1} {0} og {1} @msg `{f}` is the copy of a document open now `{f}` er kopien af et dokument, der er åbent nu @msg `{id}` is no writable format (see document.formats) `{id}` er ikke et skrivbart format (se document.formats) @msg `{id}` isn't a loaded library `{id}` er ikke et indlæst bibliotek +@msg `{file}` has no swatches of its own `{file}` har ingen egne farveprøver +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` har mønsterprøver, som en .vcswatches-fil ikke kan indeholde @msg `{key}` has no colours `{key}` har ingen farver @msg `{key}` holds more than {MAX_EDIT_WORDS} words `{key}` indeholder mere end {MAX_EDIT_WORDS} ord @msg `{key}` is a design name `{key}` er et designnavn @@ -1405,6 +1438,8 @@ liquify-list-end {0}, {1} {0} og {1} @msg a line needs at least two points en linje kræver mindst to punkter @msg a linked JavaScript file is outside the read roots en linket JavaScript-fil ligger uden for læserødderne @msg a linked image file is outside the read roots en linket billedfil ligger uden for læserødderne +@msg a linked file's export folder is outside the read roots eksportmappen for en linket fil ligger uden for læserødderne +@msg a linked file's editing data can't be read to check it against the read roots redigeringsdataene for en linket fil kan ikke læses for at kontrollere dem mod læserødderne @msg a name names one asset: give multiple: false, or one object et navn angiver ét aktiv: angiv multiple: false eller ét objekt @msg a namespace declaration uses a reserved prefix or URI en navnerumserklæring bruger et reserveret præfiks eller en reserveret URI @msg a namespace qualifier is undefined en navnerumskvalifikator er udefineret @@ -1610,6 +1645,7 @@ liquify-list-end {0}, {1} {0} og {1} @msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes sammensatte figurer tager kurver, sammensatte kurver, grupper, sammensatte figurer, tekst, blandinger og konvolutter @msg compound {_1} must contain exactly one open path to join sammensat {_1} skal indeholde præcis én åben kurve at sammenføje @msg connect needs a path other than the one extended connect kræver en anden kurve end den, der forlænges +@msg connect needs extend connect kræver extend @msg connect needs id connect kræver id @msg connect path has no open end connect-kurven har ingen åben ende @msg continuation must be an array of path chunks continuation skal være et array af kurvestykker @@ -3364,6 +3400,13 @@ liquify-list-end {0}, {1} {0} og {1} Previous Document Forrige dokument Cascade Kaskade Tile Fliselæg + Tile All Vertically Fliselæg alle lodret + Tile All Horizontally Fliselæg alle vandret + 2-Up Layout Layout med 2 + 3-Up Layout Layout med 3 + 4-Up Layout Layout med 4 + 6-Up Layout Layout med 6 + Arrange Documents Arrangér dokumenter Float in Window Flyd i vindue Float All in Windows Flyd alle i vinduer Consolidate All Windows Saml alle vinduer @@ -3409,6 +3452,11 @@ liquify-list-end {0}, {1} {0} og {1} Saturation and brightness Mætning og lysstyrke Color field Farvefelt {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Hjulvisning + Box View Kvadratvisning + Box Channel Kvadratets kanal + Color box Farvekvadrat + Color Wheel Options Indstillinger for farvehjul CSS Properties CSS-egenskaber Document Info Dokumentoplysninger Flattener Preview Udjævningsforhåndsvisning @@ -4145,6 +4193,7 @@ lighting Light Lys Play Current Selection Afspil aktuel markering Save Actions… Gem handlinger… Load Actions… Indlæs handlinger… + Replace Actions… Erstat handlinger… Reset Actions Nulstil handlinger Replace the current actions with the default set? Vil du erstatte de aktuelle handlinger med standardsættet? Append adds the default set after the current sets instead. Tilføj tilføjer i stedet standardsættet efter de aktuelle sæt. @@ -4305,7 +4354,6 @@ digits Malayalam Malayalam Composite Fonts Sammensatte skrifttyper Export Composite Fonts Eksportér sammensatte skrifttyper Import Composite Fonts Importér sammensatte skrifttyper -@msg each font must be {name, parts} hver skrifttype skal være {name, parts} @msg unknown key `{k}`; a font takes name and parts ukendt nøgle `{k}`; en skrifttype tager name og parts @msg each font needs a name hver skrifttype skal have et navn @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` kan ikke være navnet på en sammensat skrifttype (1 til {COMPOSITE_NAME_MAX} tegn, ingen kontroltegn) @@ -4318,7 +4366,6 @@ digits Malayalam Malayalam @msg two composite fonts are named `{_1}` to sammensatte skrifttyper hedder `{_1}` @msg `{_1}` is the name of an installed font `{_1}` er navnet på en installeret skrifttype @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2} er sat med `{font}`, en sammensat skrifttype -@msg give fonts: [{name, parts}…] angiv fonts: [{name, parts}…] @msg path is empty path er tom @msg fonts must be a list of composite fonts fonts skal være en liste med sammensatte skrifttyper @msg names must be strings names skal være strenge @@ -4361,6 +4408,7 @@ digits Malayalam Malayalam Underline Understreget Vertical Scale % Lodret skalering % Axis Akse + Axis Angle Aksevinkel ICF Top/Right ICF øverst/højre ICF Bottom/Left ICF nederst/venstre Show Font Height Options Vis indstillinger for skrifthøjde @@ -4403,6 +4451,7 @@ digits Malayalam Malayalam Rule: Regel: Save changes to {name} Gem ændringer i {name} Save theme to My Themes Gem tema i Mine temaer + Set the current fill or stroke to the selected color Sæt den aktuelle udfyldning eller streg til den markerede farve Set the selected color to the current color Sæt den markerede farve til den aktuelle farve Copy All Styles Kopiér alle typografier Exported {path} Eksporterede {path} @@ -4618,7 +4667,7 @@ digits Malayalam Malayalam Stroke: click for swatches, Shift-click for the color mixer Kontur: klik for farveprøver, Skift-klik for farveblanderen This panel is on the roadmap (see the parity plan). Dette panel er på vejkortet (se paritetsplanen). Open a document to navigate it. Åbn et dokument for at navigere i det. - View Artboard Only Vis kun tegnebræt + View Artboard Contents Only Vis kun tegnebrættets indhold Contextual Alternates Kontekstuelle alternativer Default Figure Standardcifre Discretionary Ligatures Valgfrie ligaturer @@ -4761,7 +4810,7 @@ digits Malayalam Malayalam Overprint Preview (separations) Forhåndsvisning af overtryk (separationer) Show All Plates Vis alle plader Show all plates Vis alle plader - Show/hide plate (Alt-click: only this plate) Vis/skjul plade (Alt-klik: kun denne plade) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Vis/skjul plade (Alt-klik: kun denne plade; Alt-klik igen: alle plader) Simulate Paper Simulér papir Use Black Point Compensation Brug sortpunktskompensation Working CMYK (don't tag) Arbejds-CMYK (mærk ikke) @@ -4801,6 +4850,8 @@ digits Malayalam Malayalam Tip extends past the end point Spidsen rager ud over endepunktet Tip on the end point Spidsen på endepunktet Variable Width Profile Variabel breddeprofil + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Stregens pensel beholder sin egen størrelse, så et breddeprofil ændrer den ikke. Fjern penslen for at bruge et profil. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Stregens pensel beholder sin egen størrelse, så et breddeprofil ændrer den ikke. Fjern penslen for at bruge et profil. Weight: Vægt: Art using a deleted global swatch keeps its colour. Grafik, der bruger en slettet global farveprøve, bevarer sin farve. Color Group: {name} Farvegruppe: {name} @@ -4910,6 +4961,10 @@ digits Malayalam Malayalam Flip Horizontal Spejl vandret Flip Vertical Spejl lodret Polygon Properties: Polygonegenskaber: + Line Properties: Linjeegenskaber: + Line Length: Linjelængde: + Line Angle: Linjevinkel: + Constrain Pie Angle Fasthold udsnittets vinkel Rectangle Properties: Rektangelegenskaber: Shape Properties: Figuregenskaber: Shape Properties Figuregenskaber @@ -4951,6 +5006,7 @@ digits Malayalam Malayalam Scatter: Spredning: Rotation: Rotation: Rotation relative to: Rotation i forhold til: + Hue Jitter: Nuancevariation: Brush Scale Options Indstillinger for penselskalering Scale Proportionately Skalér proportionalt Stretch to Fit Stroke Length Stræk til konturens længde @@ -4989,6 +5045,7 @@ digits Malayalam Malayalam Size: Størrelse: Calligraphic Brush Options Indstillinger for kalligrafipensel Bristle Brush Options Indstillinger for børstepensel + Roundness Rundhed Roundness: Rundhed: Shape: Form: Bristle Length: Børstelængde: @@ -5306,6 +5363,7 @@ digits Malayalam Malayalam BLANK DOCUMENT PRESETS TOMME DOKUMENTFORUDINDSTILLINGER Bleed Beskæring Change to Right-to-Left Layout Skift til højre-til-venstre-layout + Columns Kolonner Columns: Kolonner: Documents you create appear here. Dokumenter, du opretter, vises her. More Settings Flere indstillinger @@ -5439,6 +5497,9 @@ digits Malayalam Malayalam Open a document to preview its pages Åbn et dokument for at forhåndsvise dets sider Output › Mode Output › Tilstand Overprint and Transparency Flattener Options Indstillinger for overtryk og udfladning af gennemsigtighed + Custom… Brugerdefineret… + Custom Transparency Flattener Options Brugerdefinerede indstillinger for udfladning af gennemsigtighed + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS har ingen alfa-gennemsigtighed, og Overtryk bestemmer, om overtryk bevares. Place the pages with the placement again Placér siderne igen med placeringen Placement: Placering: Preserve CMYK Numbers Bevar CMYK-tal @@ -5488,14 +5549,19 @@ digits Malayalam Malayalam Around Object Omkring objektet Background: Baggrund: Changing these settings changes how raster effects look when exported, flattened or expanded. Ændring af disse indstillinger ændrer, hvordan rastereffekter ser ud, når de eksporteres, udflades eller udvides. + Add Around Tilføj omkring objektet + Anti Alias Antialiasering + Color Model Farvemodel Color Model: Farvemodel: Create Clipping Mask Opret klipemaske Preserve Spot Colors Bevar spotfarver + Resolution Opløsning Resolution: Opløsning: Transparent Gennemsigtig Layout Order: Layoutrækkefølge: Change to Left-to-Right Layout Skift til venstre-til-højre-layout Artboards: {n} Tegnebrætter: {n} + Rows Rækker Rows: Rækker: Assign Tildel Color Group: Farvegruppe: @@ -5644,6 +5710,8 @@ antiAlias Sharp Skarp Every option matches {base}. Alle indstillinger matcher {base}. Files of a PDF standard can't be password-protected. Filer med en PDF-standard kan ikke beskyttes med adgangskode. Files of this standard tag their colours with ICC profiles. Filer med denne standard mærker deres farver med ICC-profiler. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Filer med denne standard mærker deres farver med ICC-profiler, undtagen CMYK-farver i outputintentens profil, som skrives som DeviceCMYK. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. Med »Medtag ikke profiler« og en CMYK-outputintent skrives alle CMYK-farver som DeviceCMYK, medmindre de konverteres til en CMYK-destination med en anden profil. Flattener preset: Forudindstilling til fladgøring: General › Thumbnails Generelt › Miniaturer Grayscale images Gråtonebilleder @@ -5827,6 +5895,12 @@ antiAlias Sharp Skarp LF (macOS, Linux) LF (macOS, Linux) CRLF (Windows) CRLF (Windows) Text Export Options Indstillinger for teksteksport + Chinese Big 5 Kinesisk Big 5 + Cyrillic Kyrillisk + Greek Græsk + Turkish Tyrkisk + Baltic Baltisk + Central European Centraleuropæisk Character Set: Tegnsæt: Join the lines of each paragraph Forbind linjerne i hvert afsnit Line Breaks Linjeskift @@ -5856,6 +5930,9 @@ antiAlias Sharp Skarp Variable Options Indstillinger for variabel Define a variable first Definér først en variabel Adjust Adjoining Width Points Justér tilstødende breddepunkter + Incoming Indgående + Outgoing Udgående + Single Width Only Kun én bredde Keep both sides the same width Bevar samme bredde på begge sider Side 1: Side 1: Side 2: Side 2: @@ -5956,9 +6033,17 @@ theme Appearance Udseende Break Link to Symbol Bryd link til symbol Brush Definition Penseldefinition Brush Options… Penselindstillinger… + Options of Selected Object… Indstillinger for markeret objekt… + Options of Selected Object Indstillinger for markeret objekt +@msg no path painted with a brush is selected ingen sti malet med en pensel er markeret +@msg the selected paths are painted with brushes of different types de markerede stier er malet med pensler af forskellige typer +@msg give `params` or `reset`, not both angiv `params` eller `reset`, ikke begge +@msg a bristle brush has no options of its own on a path en børstepensel har ingen egne indstillinger på en sti Current Brush Aktuel pensel Current Symbol Aktuelt symbol Delete Brush Slet pensel + Delete Color Slet farve + Restore Generated Table Gendan genereret tabel Delete Symbol Slet symbol Delete the selected symbol? Vil du slette det markerede symbol? Delete the selected symbols? Vil du slette de markerede symboler? @@ -6235,6 +6320,7 @@ theme Appearance Udseende Select Art Markér grafik Set Current Layer Angiv aktuelt lag Flatten Artwork Fladgør grafik + Locate Layer Lokalisér lag Locate Object Lokalisér objekt Lock Others Lås andre Merge Selected Flet valgte @@ -6411,6 +6497,7 @@ theme Appearance Udseende 90° & 45° Angles 90° & 45°-vinkler 90° Angles 90°-vinkler Additional Plug-ins Folder Yderligere mappe med plug-ins + Plug-in Instruction Budget Instruktionsbudget for plug-ins Additional Fonts Folder Yderligere mappe med skrifttyper Alignment Guides Justeringshjælpelinjer Anchor Points, Handle, and Bounding Box Display Visning af ankerpunkter, håndtag og afgrænsningsboks @@ -6437,6 +6524,7 @@ theme Appearance Udseende Data Recovery Datgendannelse Default Language Standardsprog Disable Auto Add/Delete Deaktivér automatisk tilføjelse/sletning + Interpolate Control Points When Moving Anchors Interpolér retningshåndtag ved flytning af ankerpunkter Display All Blacks Accurately Vis alle sorte nøjagtigt Display All Blacks as Rich Black Vis alle sorte som rich black Display Bitmaps as Anti-aliased Images in Pixel Preview Vis bitmaps som antialiaserede billeder i pixelforhåndsvisning @@ -6453,6 +6541,7 @@ theme Appearance Udseende Enable Rubber Band for Aktivér gummibånd for Enable Touch Gestures Aktivér berøringsbevægelser Switch Selection and Drawing Modes Skift mellem markerings- og tegnetilstand + Select Last Selection Tool Vælg det seneste markeringsværktøj Enable Touch Workspace Aktivér touch-arbejdsområde English: UK Engelsk: UK Every (minutes) Hvert (minut) @@ -6524,6 +6613,9 @@ theme Appearance Udseende Printing / Exporting Udskrivning / eksport Real-time Drawing and Editing Tegning og redigering i realtid Use Monitor Profile for Canvas Brug skærmprofil til canvas + Refresh Monitor Profile Opdatér skærmprofil +@msg turn on Use Monitor Profile for Canvas first slå først „Brug skærmprofil til canvas“ til +@msg this build doesn't read display profiles denne version læser ikke skærmprofiler The canvas is drawn in sRGB. Canvasset tegnes i sRGB. Canvas display profile: Canvassets skærmprofil: The system matches the window to the display's colors. Systemet tilpasser vinduet til skærmens farver. @@ -6585,6 +6677,7 @@ theme Appearance Udseende Scroll Sideways with Cmd/Ctrl + Wheel Rul vandret med Cmd/Ctrl + musehjul Scrub Numeric Fields by Dragging Juster numeriske felter ved at trække Linux Display Server Linux-visningsserver + Low-Latency Drawing Tegning med lav latens Print Preview Udskriftsvisning Print Setup Udskriftsopsætning Bitmap Bitmap @@ -6919,6 +7012,9 @@ font-technology Variable Variable Search commands, tools, panels and effects… Søg i kommandoer, værktøjer, paneler og effekter… No commands match Ingen kommandoer passer {pos} of {total}: {name} {pos} af {total}: {name} + No menu item Intet menupunkt + Toolbar Værktøjslinje + {toolbar}, in the {tool} group {toolbar}, i gruppen {tool} @plural {n} result|{n} results {n} resultat|{n} resultater @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} af {n} resultat. Skriv videre for at indsnævre dem.|{shown} af {n} resultater. Skriv videre for at indsnævre dem. Recent Commands Seneste kommandoer @@ -6955,6 +7051,7 @@ font-technology Variable Variable The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Musehjulet med Cmd/Ctrl holdt nede ruller lærredet sidelæns. Dragging sideways on a numeric field's label changes the field's value. Når du trækker sidelæns på et talfelts etiket, ændres feltets værdi. A two-finger rotate gesture on a trackpad rotates the canvas view. En rotationsbevægelse med to fingre på en pegeplade roterer visningen af lærredet. + When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Når du flytter ankerpunkter, beholder hver kurve med ét flyttet endepunkt sin form i forhold til sine endepunkter. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Når du holder et værktøjs genvejstast nede, er værktøjet valgt, indtil du slipper, og derefter vælges det forrige værktøj igen. Shows the bounding box while you move the selection or draw a shape. Viser afgrænsningsboksen, mens du flytter markeringen eller tegner en form. Create Trim Marks draws Japanese-style marks instead of Roman ones. Opret beskæringsmærker tegner mærker i japansk stil i stedet for romerske. @@ -6985,6 +7082,29 @@ font-technology Variable Variable The unit for East Asian type measurements, which no field uses yet. Enheden for mål i østasiatisk tekst, som intet felt bruger endnu. When on, a number typed without a unit into a field in picas is read in points. Når den er slået til, læses et tal, der skrives uden enhed i et felt i pica, i punkter. With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options. Med XML-id vises objektnavne som XML-id'er i Lag, Variabler og Lagindstillinger. + The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl. Trinnet for tekststørrelse og linjeafstand: Cmd/Ctrl+Skift+. og Cmd/Ctrl+Skift+, ændrer størrelsen ét trin, eller fem med Alt også; i vandret tekst ændrer Alt med pil op eller ned linjeafstanden ét trin, eller fem med Cmd/Ctrl. + The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl. Trinnet for sporing og knibning, i tusindedele em: i vandret tekst ændrer Alt med pil venstre eller højre knibningen ved markøren eller sporingen af den markerede tekst ét trin, eller fem med Cmd/Ctrl. + The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. Trinnet for forskydning af grundlinjen: i vandret tekst flytter Alt og Skift med pil op eller ned grundlinjen ét trin, eller fem med Cmd/Ctrl. + Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. Viser indstillingerne for japansk og anden østasiatisk tekst i panelerne Tegn, Afsnit, OpenType og Glyffer samt kommandoen Sammensatte skrifttyper. + Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. Viser indstillingerne for arabisk, hebraisk og indisk tekst i panelerne Tegn og Afsnit, for eksempel afsnitsretning, kashidaer og cifre. + The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. Markeringsværktøjerne markerer kun tekst på dens grundlinje, områdetekstens ramme eller dens sti, ikke hvor som helst inden for dens boks. + Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. Skrifttypemenuerne viser hver skrifttype med dens engelske navn; slået fra viser en skrifttype, der også har et navn på sit eget sprog, det navn. + New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. Ny områdetekst starter med Automatisk størrelse slået til, så en rektangulær ramme med vandret tekst vokser eller skrumper i højden, så teksten passer. + Font lists and the Type › Font menu show a sample of each font beside its name. Skrifttypelister og menuen Skrifttype viser en prøve på hver skrifttype ved siden af dens navn. + Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on. Skrifttypeprøver tegnes med mørk tekst på hvidt uanset grænsefladens lysstyrke; det gælder kun, mens forhåndsvisninger af skrifttyper i menuer er slået til. + How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is. Hvor høj hver række er i listerne for skrifttypefelter, som det i panelet Tegn, og dermed hvor stor hver prøve er. + How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first. Hvor mange af de senest brugte skrifttyper, fra 1 til 15, Seneste skrifttyper og skrifttypelisterne viser, den nyeste først. + When you change the font or font style of text, characters the new font has no glyph for keep the font they had. Når du skifter skrifttype eller skriftsnit for tekst, beholder tegn, som den nye skrifttype ikke har en glyf til, den skrifttype, de havde. + A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export. En lyserød fremhævning på lærredet markerer glyffer, som OpenType-funktioner har erstattet, for eksempel ligaturer; den udskrives og eksporteres ikke. + With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from. Med tekstværktøjet viser markering af et enkelt tegn en række af dets alternative glyffer ved siden af det på lærredet at vælge imellem. + A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export. En lyserød fremhævning på lærredet markerer tekst, der tegnes med en erstatningsskrifttype, fordi dens skrifttype mangler; den udskrives og eksporteres ikke. + New type made with a Type tool starts with placeholder text, selected, so typing replaces it. Ny tekst, der laves med et tekstværktøj, starter med markeret pladsholdertekst, som det, du skriver, erstatter. + Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list. Hvis du skriver en listemarkør som 1. eller * og derefter et mellemrum i starten af et afsnit, bliver afsnittet en liste. + Fonts in this folder show in the font menus and can be used without being installed. Skrifttyper i denne mappe vises i skrifttypemenuerne og kan bruges uden at være installeret. + Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows. Når en grafisk stil anvendes på tekst, fjernes tegnenes egen udfyldning eller streg, hvor stilen har en, så stilens maling ses. + Align and Distribute measure point type by the ink of its glyphs instead of its em box. Justér og Fordel måler punkttekst efter glyffernes blæk i stedet for dens em-boks. + Align and Distribute measure area type by the ink of its glyphs instead of its frame. Justér og Fordel måler områdetekst efter glyffernes blæk i stedet for dens ramme. + The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box. Afgrænsningsboksen og panelet Transformér måler punkttekst efter glyffernes blæk i stedet for dens em-boks. Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply. Fastgør tegning, flytning og skalering til gitterets underinddelinger, også mens gitteret er skjult; mens den er slået til, gælder Fastgør til pixel ikke. The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead. Farven på hjælpelinjer, der ikke er markeret; en kunstplade med en hjælpelinjeetiket tegner sine egne hjælpelinjer i etikettens farve. Draws guides as solid lines or as dots, including the guides already in the document. Tegner hjælpelinjer som hele linjer eller som prikker, også de hjælpelinjer, der allerede er i dokumentet. @@ -7028,6 +7148,8 @@ font-technology Variable Variable Couldn't paste from the clipboard: {e} Kunne ikke indsætte fra udklipsholderen: {e} Channel Kanal Circle Cirkel + Circle Tool Cirkelværktøj + Circle too large Cirklen er for stor Clip to Art Beskær til grafik Colorize Farvelæg Gamma Gamma @@ -7244,6 +7366,13 @@ imageTrace Outline Kontur Show External Script Warning Vis advarsel om eksterne scripts A Script Is Running Et script kører Script Alert Scriptadvarsel + Script File Access Scriptadgang til filer + The script asks to read a file you choose. Scriptet beder om at læse en fil, du vælger. + The script asks to read and write a file you choose. Scriptet beder om at læse og skrive en fil, du vælger. + The script asks to read and write a folder you choose, with everything in it. Scriptet beder om at læse og skrive en mappe, du vælger, med alt indhold. + Allow Once Tillad én gang + Always Allow This Script Tillad altid dette script + Deny Afvis A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Et script kan ændre de åbne dokumenter og skrive filer gennem de kommandoer, det kører. Kør kun scripts, du stoler på. Do not show this warning again Vis ikke denne advarsel igen Stop the script and undo what it did? Then quit again. Stop scriptet og fortryd det, det har gjort? Afslut derefter igen. @@ -7319,6 +7448,7 @@ imageTrace Outline Kontur @msg Saved {path} Gemte {path} @msg Select text or click into text with the Type tool to insert glyphs Markér tekst, eller klik i tekst med tekstværktøjet, for at indsætte glyffer @msg Shape Builder: no region under the pointer Figurbygger: intet område under markøren +@msg Shape Builder: select all paths you want to merge Figurbygger: markér alle kurver, du vil flette @msg Shape Builder: select paths or compound paths Figurbygger: markér kurver eller sammensatte kurver @msg Show All Hidden Attributes: nothing is hidden Vis alle skjulte attributter: intet er skjult @msg Split Into Grid: select paths large enough for the grid Opdel i gitter: markér kurver, der er store nok til gitteret @@ -7429,6 +7559,7 @@ imageTrace Outline Kontur @msg bad trailer ugyldig trailer @msg balance must be between 0 and 100 balance skal være mellem 0 og 100 @msg batch step {_1} (`{id}`) failed: {e} batchtrin {_1} (`{id}`) mislykkedes: {e} +@msg action step {_1} (`{id}`) failed: {reason} handlingstrin {_1} (`{id}`) mislykkedes: {reason} @msg brightness must be dark|mediumDark|mediumLight|light brightness skal være dark|mediumDark|mediumLight|light @msg can't encode the document: {0} kan ikke kode dokumentet: {0} @msg can't parse shortcut `{c}` kan ikke parse genvejen `{c}` @@ -7446,6 +7577,7 @@ imageTrace Outline Kontur @msg choose a folder to export to vælg en mappe at eksportere til @msg choose a location for the package vælg en placering til pakken @msg clipboard is empty udklipsholderen er tom +@msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: mindst én farve skal blive i farvetabellen @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` er ikke en farve som "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: højst {MAX_TABLE} farver @msg command `{0}` is not available right now: {1} kommandoen `{0}` er ikke tilgængelig lige nu: {1} @@ -7503,8 +7635,8 @@ imageTrace Outline Kontur @msg no active document intet aktivt dokument @msg no active perspective plane intet aktivt perspektivplan @msg no anchor points selected ingen ankerpunkter er markeret -@msg `points` must be three [x, y] pairs of numbers `points` skal være tre talpar [x, y] -@msg direct-select three anchor points, or give `points` direkte markér tre ankerpunkter, eller angiv `points` +@msg `points` must be two or three [x, y] pairs of numbers `points` skal være to eller tre talpar [x, y] +@msg direct-select two or three anchor points, or give `points` direkte markér to eller tre ankerpunkter, eller angiv `points` @msg no circle passes through these points: two are the same or all three lie on one line ingen cirkel går gennem disse punkter: to er ens, eller alle tre ligger på én linje @msg no app to open files here ingen app til at åbne filer her @msg no artboard ingen tegneflade @@ -7595,6 +7727,9 @@ imageTrace Outline Kontur @msg no such user library intet sådant brugerbibliotek @msg no such view ingen sådan visning @msg no such width point intet sådant breddepunkt +@msg `single` must be `incoming` or `outgoing` `single` skal være `incoming` eller `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` og `outIndex` skal være de to halvdele af ét diskontinuert breddepunkt +@msg a discontinuous width point keeps its place et diskontinuert breddepunkt bevarer sin placering @msg no swatch `{name}` ingen farveprøve `{name}` @msg no swatch library `{l}` (see swatch.library.list) intet farveprøvebibliotek `{l}` (se swatch.library.list) @msg no symbol instances selected ingen symbolforekomster markeret @@ -7831,6 +7966,8 @@ imageTrace Outline Kontur @msg {label}: lost track of a shape's style {label}: mistede styr på en forms stil @msg {label}: select paths {label}: markér stier @msg {label}: select paths, compound paths, groups or text {label}: markér stier, sammensatte stier, grupper eller tekst +@msg a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first en linje eller anden åben kurve, der ikke omslutter noget område, ændrer ikke resultatets form; anvend først Objekt › Kurve › Streg til kontur på den for at tage den med +@msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first {label} gav et tomt resultat: en linje eller anden åben kurve omslutter intet område; anvend først Objekt › Kurve › Streg til kontur på den for at tage den med @msg {label}… {label}… @msg {name}: CRC mismatch {name}: CRC matcher ikke @msg {name}: no local header {name}: ingen lokal header @@ -7857,6 +7994,9 @@ imageTrace Outline Kontur @msgplural Discarded {n} recovered document|Discarded {n} recovered documents Kasserede {n} gendannet dokument|Kasserede {n} gendannede dokumenter @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them Gendannede {n} dokument: gem det for at beholde det|Gendannede {n} dokumenter: gem dem for at beholde dem @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} Åbnede med {n} note: {first}|Åbnede med {n} noter: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Kopierede med {n} note: {first}|Kopierede med {n} noter: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Klippede med {n} note: {first}|Klippede med {n} noter: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Sporede billedet med {n} note: {first}|Sporede billedet med {n} noter: {first} @msgplural {notice}. Opened with {n} note: {first}|{notice}. Opened with {n} notes: {first} {notice}. Åbnede med {n} note: {first}|{notice}. Åbnede med {n} noter: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} Gemte {path} med {n} note: {first}|Gemte {path} med {n} noter: {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first Indlejrede {n} billede; {missing} mangler: link dem igen først|Indlejrede {n} billeder; {missing} mangler: link dem igen først @@ -7883,6 +8023,8 @@ imageTrace Outline Kontur @msg All colors are within the CMYK gamut Alle farver er inden for CMYK-farveomfanget @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} farve er uden for CMYK-farveomfanget|{n} farver er uden for CMYK-farveomfanget @msg Unembedded to {_1} Fjernede indlejring til {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} Fjernede indlejring af {n} billede til {folder}|Fjernede indlejring af {n} billeder til {folder} +@msg every numbered name for {name} is taken in that folder alle nummererede navne til {name} er optaget i den mappe @msg Reset {_1} Nulstillede {_1} @msg Sent to {_1} Sendte til {_1} @msg {_1} files {_1}-filer @@ -7896,6 +8038,8 @@ imageTrace Outline Kontur @msg Reload the page to go on (changes not saved yet may be lost). Genindlæs siden for at fortsætte (ændringer, der endnu ikke er gemt, kan gå tabt). @msg tool (a tool id) is required tool (et værktøj-id) er påkrævet @msg {tool} isn't in a toolbar group of several tools {tool} er ikke i en værktøjsgruppe med flere værktøjer +@msg Presentation Mode hides the toolbars: change the screen mode to show them Præsentationstilstand skjuler værktøjslinjerne: skift skærmtilstand for at vise dem +@msg Tab has hidden the toolbars: press Tab to show them Tab har skjult værktøjslinjerne: tryk på Tab for at vise dem @msg onto must name a panel floating in another group onto skal angive et panel, der flyder i en anden gruppe @msg below and above must name a panel floating in another group below og above skal angive et panel, der flyder i en anden gruppe @msg give only one of onto, below and above angiv kun én af onto, below og above @@ -8238,6 +8382,7 @@ imageTrace Outline Kontur Ascent Overhøjde Cap Height Versalhøjde x Height x-højde + Em Box Height Em-felthøjde Justify Justér First Baseline Første basislinje Vertical Align Lodret justering @@ -8345,6 +8490,7 @@ mark-style Japanese Japansk Cove Cove Depth Dybde Front Forfra + Side Siden Isometric Bottom Isometrisk bund Isometric Left Isometrisk venstre Isometric Right Isometrisk højre @@ -8563,6 +8709,8 @@ mark-style Japanese Japansk Reset Tracking and Kerning Nulstil sporing og kerning Reset Horizontal Scale Nulstil vandret skalering Highlight Font Name Fremhæv skrifttypenavn + Highlight Font Size Fremhæv skriftstørrelse + Other… Anden… Highlight Kerning Fremhæv kerning Highlight Tracking Fremhæv sporing @msg span must be "object" or "selection", got {v} span skal være "object" eller "selection", fik {v} @@ -8583,6 +8731,13 @@ mark-style Japanese Japansk @msg {k} has control characters {k} indeholder kontroltegn @msg {k} has control characters or line breaks {k} indeholder kontroltegn eller linjeskift @msg variables that aren't text were left out: {kinds} variabler, der ikke er tekst, blev udeladt: {kinds} +variable-kind Visibility Synlighed +variable-kind Linked File Koblet fil +variable-kind Graph Data Grafdata +variable-kind Unknown Ukendt +variable-list-two {0}, {1} {0} og {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} og {1} @msg a new document won't read these variables back with their kind: {names} et nyt dokument læser ikke disse variabler tilbage med deres type: {names} @msg a new document refuses this file because of these variables: {names} et nyt dokument afviser denne fil på grund af disse variabler: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them overskriften `{header}` for `{name}` ville blive læst som variablen `{other}`: omdøb en af dem @@ -8628,6 +8783,11 @@ mark-style Japanese Japansk Edge Only Kun kant Overlay Edge Overlæg kant Path Length Stilængde + Grid Size Gitterstørrelse + Grid Colors Gitterfarver + Flattener Preset Forudindstilling til fladgøring + X X + Y Y @msg the file's layers weren't read ({_1}): it comes in as its page, in one layer filens lag blev ikke læst ({_1}): den kommer ind som sin side, i ét lag @msg the file's layers weren't read from its editing data ({_1}): they come from its PDF part filens lag blev ikke læst fra dens redigeringsdata ({_1}): de kommer fra dens PDF-del @msg the file's variable bindings weren't all read (bindings skipped: {_1}): those objects aren't bound to their variables ikke alle filens variabelbindinger blev læst (udeladte bindinger: {_1}): de objekter er ikke bundet til deres variabler @@ -8635,6 +8795,8 @@ mark-style Japanese Japansk @msg the file's variable library couldn't be read: the Variables panel doesn't list it filens variabelbibliotek kunne ikke læses: variabelpanelet viser det ikke @msg a variable of unknown kind can't be bound to objects en variabel af ukendt type kan ikke bindes til objekter @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` skal være grayscale, rgb, hsb, cmyk eller websafe +@msg `view` must be wheel or box `view` skal være wheel eller box +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` skal være hue, saturation, brightness, red, green eller blue @msg the Color Picker is not open farvevælgeren er ikke åben @msg the screen color sampler is already open skærmfarvesampleren er allerede åben @msg this system has no screen color sampler dette system har ingen skærmfarvesampler @@ -9463,6 +9625,12 @@ anchor Points: Punkter: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` skal være "free", "keepAngles" eller "symmetric" @msg `{key}` must be [x, y] `{key}` skal være [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Enhedsomregner + Unit Converter Panel Panelet Enhedsomregner + Copy with Units Kopiér med enheder + From Selection Fra markering + # Color Effects add-on: Select by Color Kind. Select by Color Kind Markér efter farvetype Objects with Spot Colors Objekter med spotfarver @@ -9664,6 +9832,14 @@ breakText Glyphs Glyffer Remove Gaps Fjern mellemrum @msg that makes too many pieces (at most 100000): make the dashes longer det giver for mange stykker (højst 100000): gør stregerne længere @msg select paths, or segments, to divide vælg stier eller segmenter, der skal opdeles +# Path Precision Tools add-on: Smooth Bridge. + Smooth Bridge… Blød bro… + Smooth Bridge Blød bro + Keep Originals Behold originaler +@msg select two circles to bridge vælg to cirkler, der skal forbindes +@msg one circle is inside the other den ene cirkel er inden i den anden +@msg the circles are too far apart for this radius: raise the radius cirklerne er for langt fra hinanden til denne radius: gør radius større +@msg the circles are too far apart for this radius cirklerne er for langt fra hinanden til denne radius # Path Precision Tools add-on: Common Tangents. Common Tangents… Fælles tangenter… Common Tangents Fælles tangenter @@ -10024,4 +10200,14 @@ breakText Glyphs Glyffer @msg A panel is not joined to the rest by a crease. Et panel er ikke forbundet med resten af en rillelinje. @msg A fold line is on a non-printing layer. En foldelinje ligger på et lag, der ikke udskrives. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneler: {panels}, hængsler: {hinges}, fejl: {errors}, advarsler: {warnings} + Fold Preview Forhåndsvisning af foldning + Fold Foldning + Show Fold Lines Vis foldelinjer + Three-Quarter Trekvart + Open a document to preview its folded shape. Åbn et dokument for at se dets foldede form. +@msg Check the fold lines first. Kontrollér foldelinjerne først. +@msg Panels: {panels}, hinges: {hinges} Paneler: {panels}, hængsler: {hinges} +@msg Other blanks not shown: {count} Andre emner vises ikke: {count} +@msg A joint does not close by {gap} pt. En samling lukker ikke med {gap} pt. +@msg Two panels pass through each other. To paneler går gennem hinanden. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer skal være "singleLine", "everyLine", "standardSingleLine" eller "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 10147b2d45..501406ef1e 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -18,7 +18,7 @@ # `untranslated_report` lists gaps) — and the status and error messages. Left in English on purpose (`MENU_KEEP_AS_IS` in the # tests): the product name, language names, OpenType, the built-in workspace names and the bracketed # perspective grid preset names; `de-DE`, `de-AT`, `de-CH` and every other `de-*` locale resolve here. -# Photoshop-style raster effects (Effect menu, their dialogs). +# Raster effects (Effect menu, their dialogs). Glowing Edges… Leuchtende Konturen… Glowing Edges Leuchtende Konturen Edge Width Kantenbreite @@ -94,6 +94,7 @@ Add Anchor Point Ankerpunkt hinzufügen Add Anchor Point Tool Ankerpunkt-hinzufügen-Werkzeug Add Anchor Points Ankerpunkte hinzufügen + Add Around Um das Objekt hinzufügen Add Effect Effekt hinzufügen Add Freeform Line Freiformlinie hinzufügen Add Freeform Point Freiformpunkt hinzufügen @@ -115,8 +116,12 @@ Add to Swatches Zu Farbfeldern hinzufügen Add Used Colors Verwendete Farben hinzufügen Additional Plug-ins Folder Zusätzlicher Plug-in-Ordner + Plug-in Instruction Budget Anweisungsbudget für Plug-ins Additional Fonts Folder Zusätzlicher Schriftenordner Adjust Adjoining Width Points Angrenzende Breitenpunkte anpassen + Incoming Eingehend + Outgoing Ausgehend + Single Width Only Nur eine Breite Adjust Color Balance… Farbbalance anpassen… Adjust Colors Farben anpassen Adjust Options: Anpassungsoptionen: @@ -171,6 +176,7 @@ Angle: Winkel: Angles Winkel Animated Zoom Animierter Zoom + Anti Alias Glättung Anti-alias Glätten Anti-Alias Glätten Anti-alias Rasters Pixelbilder glätten @@ -338,6 +344,12 @@ font-technology Variable Variabel Brush Definition Pinseldefinition Brush Libraries Pinsel-Bibliotheken Brush Options… Pinseloptionen… + Options of Selected Object… Optionen für ausgewähltes Objekt… + Options of Selected Object Optionen für ausgewähltes Objekt +@msg no path painted with a brush is selected kein mit einem Pinsel gemalter Pfad ausgewählt +@msg the selected paths are painted with brushes of different types die ausgewählten Pfade sind mit Pinseln verschiedener Typen gemalt +@msg give `params` or `reset`, not both `params` oder `reset` angeben, nicht beides +@msg a bristle brush has no options of its own on a path ein Borstenpinsel hat auf einem Pfad keine eigenen Optionen Brush Strokes Pinselstriche Brushes Pinsel Built-in Libraries Integrierte Bibliotheken @@ -394,6 +406,12 @@ font-technology Variable Variabel Character Alignment Zeichenausrichtung Character / Paragraph Zeichen / Absatz Character Rotation Zeichendrehung + Chinese Big 5 Chinesisch Big 5 + Cyrillic Kyrillisch + Greek Griechisch + Turkish Türkisch + Baltic Baltisch + Central European Mitteleuropäisch Character Set: Zeichensatz: Character Style Zeichenformat Character Style Options Zeichenformatoptionen @@ -456,6 +474,8 @@ font-technology Variable Variabel Choose a folder Ordner wählen Choose… Wählen… Circle Kreis + Circle Tool Kreis-Werkzeug + Circle too large Kreis zu groß Classic Defaults Klassische Standardwerte Clean Up… Aufräumen… Clear Löschen @@ -534,6 +554,7 @@ font-technology Variable Variabel Color Mixer (Shift-click the chip) Farbmischer (Shift-Klick auf das Farbfeld) Color Mode Farbmodus Color Mode: Farbmodus: + Color Model Farbmodell Color Model: Farbmodell: Color Models Farbmodelle Color Picker Farbwähler @@ -554,12 +575,18 @@ font-technology Variable Variabel Saturation and brightness Sättigung und Helligkeit Color field Farbauswahlfeld {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Kreisansicht + Box View Quadratansicht + Box Channel Kanal des Quadrats + Color box Farbquadrat + Color Wheel Options Optionen für den Farbkreis Color Type: Farbart: Color: Farbe: Colorize Einfärben Colors Farben Colors: Farben: Column Graph Tool Säulendiagramm-Werkzeug + Columns Spalten Columns: Spalten: Column… Säule… Combine Slices Slices kombinieren @@ -771,6 +798,8 @@ font-technology Variable Variabel Delete Artboard Zeichenfläche löschen Delete Artboards Zeichenflächen löschen Delete Brush Pinsel löschen + Delete Color Farbe löschen + Restore Generated Table Generierte Tabelle wiederherstellen Delete Character Style Zeichenformat löschen Delete Empty Artboards Leere Zeichenflächen löschen Delete Freeform Point Freiformpunkt löschen @@ -839,6 +868,7 @@ font-technology Variable Variabel Direct Selection Tool Direktauswahl-Werkzeug Direction Handles Richtungsgriffe Disable Auto Add/Delete Automatisches Hinzufügen/Löschen deaktivieren + Interpolate Control Points When Moving Anchors Richtungsgriffe beim Verschieben von Ankerpunkten interpolieren Disable Opacity Mask Deckkraftmaske deaktivieren Discard Verwerfen Preserve Beibehalten @@ -1051,6 +1081,7 @@ font-technology Variable Variabel Enable text access for screen readers Textzugriff für Bildschirmlesegeräte zulassen Enable Touch Gestures Touch-Gesten aktivieren Switch Selection and Drawing Modes Zwischen Auswahl- und Zeichenmodus wechseln + Select Last Selection Tool Zuletzt verwendetes Auswahl-Werkzeug wählen Enable Touch Workspace Touch-Arbeitsbereich aktivieren Encoding Kodierung Encoding: Kodierung: @@ -1231,6 +1262,8 @@ font-technology Variable Variabel Files Dateien Files of a PDF standard can't be password-protected. Dateien eines PDF-Standards können nicht mit einem Kennwort geschützt werden. Files of this standard tag their colours with ICC profiles. Dateien dieses Standards kennzeichnen ihre Farben mit ICC-Profilen. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Dateien dieses Standards kennzeichnen ihre Farben mit ICC-Profilen, außer CMYK-Farben im Profil der Ausgabemethode, die als DeviceCMYK geschrieben werden. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. Mit „Profile nicht einschließen“ und einer CMYK-Ausgabemethode wird jede CMYK-Farbe als DeviceCMYK geschrieben, sofern sie nicht in ein CMYK-Ziel mit einem anderen Profil konvertiert wird. Fill Fläche Fill & Stroke Fläche und Kontur Fill (X), double-click for the Color Picker Fläche (X), Doppelklick öffnet den Farbwähler @@ -1280,6 +1313,8 @@ font-technology Variable Variabel Reset Tracking and Kerning Laufweite und Kerning zurücksetzen Reset Horizontal Scale Horizontale Skalierung zurücksetzen Highlight Font Name Schriftname hervorheben + Highlight Font Size Schriftgrad hervorheben + Other… Andere… Highlight Kerning Kerning hervorheben Highlight Tracking Laufweite hervorheben Spacing Abstand @@ -2031,6 +2066,7 @@ file-filter Templates Vorlagen Load SVG into Clipboard SVG in die Zwischenablage laden Load Text into Clipboard Text in die Zwischenablage laden Local Libraries Lokale Bibliotheken + Locate Layer Ebene ausfindig machen Locate Object Objekt ausfindig machen Locate Selected Objects Ausgewählte Objekte ausfindig machen Location Speicherort @@ -2219,6 +2255,7 @@ file-filter Templates Vorlagen New Bristle Brush Neuer Borstenpinsel Calligraphic Brush Options Optionen für Kalligrafiepinsel Bristle Brush Options Optionen für Borstenpinsel + Roundness Rundheit Roundness: Rundheit: Fixed Fest Pressure Druck @@ -2524,6 +2561,9 @@ file-filter Templates Vorlagen Overprint Überdrucken Overprint and Transparency Flattener Überdrucken und Transparenzreduzierung Overprint and Transparency Flattener Options Optionen für Überdrucken und Transparenzreduzierung + Custom… Benutzerdefiniert… + Custom Transparency Flattener Options Benutzerdefinierte Optionen für Transparenzreduzierung + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS hat keine Alphatransparenz, und „Überdrucken“ legt fest, ob Überdrucken erhalten bleibt. Overprint Black… Schwarz überdrucken… Overprint Fill Fläche überdrucken Overprint Preview Überdruckenvorschau @@ -2573,6 +2613,13 @@ file-filter Templates Vorlagen Pathfinders: Pathfinder: Paths Pfade Path Length Pfadlänge + Grid Size Rastergröße + Grid Colors Rasterfarben + Flattener Preset Reduzierungsvorgabe + X X + Y Y + Orange Orange + Purple Lila Paths: {paths} Anchors: {anchors} Colors: {colors} Pfade: {paths} Ankerpunkte: {anchors} Farben: {colors} Pattern Muster Pattern Editing Musterbearbeitung @@ -2632,6 +2679,7 @@ diagnostics ui Oberfläche Play Current Selection Aktuelle Auswahl abspielen Save Actions… Aktionen speichern… Load Actions… Aktionen laden… + Replace Actions… Aktionen ersetzen… Reset Actions Aktionen zurücksetzen Replace the current actions with the default set? Aktuelle Aktionen durch den Standardsatz ersetzen? Append adds the default set after the current sets instead. Mit „Anhängen“ wird der Standardsatz stattdessen nach den aktuellen Sätzen hinzugefügt. @@ -2647,6 +2695,10 @@ diagnostics ui Oberfläche Polar Grid Tool Radiales-Raster-Werkzeug Polygon Polygon Polygon Properties: Polygoneigenschaften: + Line Properties: Linieneigenschaften: + Line Length: Linienlänge: + Line Angle: Linienwinkel: + Constrain Pie Angle Winkel des Kreissegments beibehalten Polygon Tool Polygon-Werkzeug Portrait Hochformat Power Saving (integrated) Energiesparen (integriert) @@ -2808,6 +2860,9 @@ digits Malayalam Malayalam Real World: Reale Welt: Real-time Drawing and Editing Zeichnen und Bearbeiten in Echtzeit Use Monitor Profile for Canvas Monitorprofil für Arbeitsfläche verwenden + Refresh Monitor Profile Monitorprofil aktualisieren +@msg turn on Use Monitor Profile for Canvas first aktivieren Sie zuerst „Monitorprofil für Arbeitsfläche verwenden“ +@msg this build doesn't read display profiles diese Version liest keine Bildschirmprofile The canvas is drawn in sRGB. Die Arbeitsfläche wird in sRGB dargestellt. Canvas display profile: Bildschirmprofil der Arbeitsfläche: The system matches the window to the display's colors. Das System passt das Fenster an die Farben des Bildschirms an. @@ -3000,6 +3055,8 @@ digits Malayalam Malayalam Reselect Erneut auswählen Reset Zurücksetzen Reset Bounding Box Begrenzungsrahmen zurücksetzen + Rotate Bounding Box Begrenzungsrahmen drehen + Rotate Bounding Box… Begrenzungsrahmen drehen… Reset Envelope Mesh Hüllengitter zurücksetzen Reset Envelope Shape Hüllenform zurücksetzen Reset Essentials Essentials zurücksetzen @@ -3041,6 +3098,7 @@ digits Malayalam Malayalam Reshape Segment Segmentform ändern Reshape Tool Form-ändern-Werkzeug Reshape Type Area Form der Textfläche ändern + Resolution Auflösung Resolution: Auflösung: Responsive Responsiv Restore Wiederherstellen @@ -3067,6 +3125,7 @@ digits Malayalam Malayalam The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Mit gedrückter Befehls-/Strg-Taste scrollt das Mausrad die Arbeitsfläche seitwärts. Dragging sideways on a numeric field's label changes the field's value. Seitliches Ziehen auf der Beschriftung eines Zahlenfelds ändert den Wert des Felds. A two-finger rotate gesture on a trackpad rotates the canvas view. Eine Drehgeste mit zwei Fingern auf einem Trackpad dreht die Ansicht der Arbeitsfläche. + When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Wenn Sie Ankerpunkte verschieben, behält jede Kurve mit einem verschobenen Ende ihre Form relativ zu ihren Enden. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Solange Sie das Tastaturkürzel eines Werkzeugs gedrückt halten, ist dieses Werkzeug gewählt; danach wird wieder das vorherige gewählt. Shows the bounding box while you move the selection or draw a shape. Zeigt den Begrenzungsrahmen an, während Sie die Auswahl verschieben oder eine Form zeichnen. Create Trim Marks draws Japanese-style marks instead of Roman ones. „Schnittmarken erstellen“ zeichnet japanische statt römische Marken. @@ -3097,6 +3156,29 @@ digits Malayalam Malayalam The unit for East Asian type measurements, which no field uses yet. Die Einheit für Maße in ostasiatischem Text, die noch kein Feld verwendet. When on, a number typed without a unit into a field in picas is read in points. Wenn aktiviert, wird eine ohne Einheit eingegebene Zahl in einem Feld in Pica als Punkt gelesen. With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options. Mit XML-ID werden Objektnamen in „Ebenen“, „Variablen“ und „Ebenenoptionen“ als XML-IDs angezeigt. + The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl. Der Schritt für Schriftgröße und Zeilenabstand: Cmd/Ctrl+Umschalt+. und Cmd/Ctrl+Umschalt+, ändern die Größe um einen Schritt, zusätzlich mit Alt um fünf; in horizontalem Text ändert Alt mit Pfeil nach oben oder unten den Zeilenabstand um einen Schritt, mit Cmd/Ctrl um fünf. + The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl. Der Schritt für Laufweite und Kerning, in Tausendstel Geviert: In horizontalem Text ändert Alt mit Pfeil nach links oder rechts das Kerning an der Einfügemarke oder die Laufweite des ausgewählten Texts um einen Schritt, mit Cmd/Ctrl um fünf. + The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. Der Schritt für den Grundlinienversatz: In horizontalem Text verschieben Alt und Umschalt mit Pfeil nach oben oder unten die Grundlinie um einen Schritt, mit Cmd/Ctrl um fünf. + Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. Blendet die Optionen für japanischen und anderen ostasiatischen Text in den Bedienfeldern „Zeichen“, „Absatz“, „OpenType“ und „Glyphen“ sowie den Befehl „Zusammengesetzte Schriften“ ein. + Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. Blendet die Optionen für arabischen, hebräischen und indischen Text in den Bedienfeldern „Zeichen“ und „Absatz“ ein, etwa Absatzrichtung, Kashidas und Ziffern. + The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. Die Auswahlwerkzeuge wählen Text nur auf seiner Grundlinie, dem Rahmen des Flächentexts oder seinem Pfad aus, nicht an jeder Stelle innerhalb seines Begrenzungsrahmens. + Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. Schriftmenüs zeigen jede Schrift mit ihrem englischen Namen; ausgeschaltet zeigt eine Schrift, die auch einen Namen in ihrer eigenen Sprache hat, diesen Namen. + New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. Neuer Flächentext beginnt mit eingeschalteter automatischer Größe, sodass ein rechteckiger Rahmen mit horizontalem Text in der Höhe wächst oder schrumpft, bis der Text hineinpasst. + Font lists and the Type › Font menu show a sample of each font beside its name. Schriftlisten und das Menü „Schrift“ zeigen neben jedem Namen ein Muster der Schrift. + Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on. Schriftmuster werden unabhängig von der Helligkeit der Oberfläche in dunkler Schrift auf Weiß gezeichnet; das gilt nur, solange Schriftvorschauen in Menüs eingeschaltet sind. + How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is. Wie hoch jede Zeile in den Schriftlisten der Schriftfelder ist, etwa im Bedienfeld „Zeichen“, und damit wie groß jedes Muster ist. + How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first. Wie viele der zuletzt verwendeten Schriften, von 1 bis 15, „Zuletzt verwendete Schriften“ und die Schriftlisten zeigen, die neueste zuerst. + When you change the font or font style of text, characters the new font has no glyph for keep the font they had. Wenn Sie die Schrift oder den Schriftschnitt eines Texts ändern, behalten Zeichen, für die die neue Schrift keine Glyphe hat, ihre bisherige Schrift. + A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export. Eine rosa Hervorhebung auf der Zeichenfläche markiert Glyphen, die OpenType-Funktionen ersetzt haben, etwa Ligaturen; sie wird nicht gedruckt oder exportiert. + With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from. Wählen Sie mit dem Text-Werkzeug ein einzelnes Zeichen aus, erscheint daneben auf der Zeichenfläche eine Reihe seiner alternativen Glyphen zur Auswahl. + A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export. Eine rosa Hervorhebung auf der Zeichenfläche markiert Text in einer Ersatzschrift, weil seine Schrift fehlt; sie wird nicht gedruckt oder exportiert. + New type made with a Type tool starts with placeholder text, selected, so typing replaces it. Neuer Text, der mit einem Text-Werkzeug erstellt wird, beginnt mit ausgewähltem Platzhaltertext, den Ihre Eingabe ersetzt. + Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list. Ein Listenzeichen wie 1. oder * und danach ein Leerzeichen, am Anfang eines Absatzes getippt, macht den Absatz zu einer Liste. + Fonts in this folder show in the font menus and can be used without being installed. Schriften in diesem Ordner erscheinen in den Schriftmenüs und lassen sich ohne Installation verwenden. + Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows. Wird ein Grafikstil auf Text angewendet, verlieren die Zeichen ihre eigene Fläche oder Kontur, wo der Stil eine hat, sodass die Farbe des Stils sichtbar wird. + Align and Distribute measure point type by the ink of its glyphs instead of its em box. Ausrichten und Verteilen messen Punkttext an den sichtbaren Formen seiner Glyphen statt an seinem Geviert. + Align and Distribute measure area type by the ink of its glyphs instead of its frame. Ausrichten und Verteilen messen Flächentext an den sichtbaren Formen seiner Glyphen statt an seinem Rahmen. + The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box. Der Begrenzungsrahmen und das Bedienfeld „Transformieren“ messen Punkttext an den sichtbaren Formen seiner Glyphen statt an seinem Geviert. Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply. Richtet Zeichnen, Verschieben und Skalieren an den Unterteilungen des Rasters aus, auch wenn das Raster ausgeblendet ist; solange die Option an ist, wirkt „An Pixel ausrichten“ nicht. The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead. Die Farbe nicht ausgewählter Hilfslinien; eine Zeichenfläche mit einer „Farbmarkierung der Hilfslinien“ zeichnet ihre eigenen Hilfslinien stattdessen in dieser Farbe. Draws guides as solid lines or as dots, including the guides already in the document. Zeichnet Hilfslinien als durchgezogene Linien oder als Punkte, auch die Hilfslinien, die bereits im Dokument sind. @@ -3178,6 +3260,7 @@ digits Malayalam Malayalam Rounded Rectangle Tool Abgerundetes-Rechteck-Werkzeug Rounded Rectangle… Abgerundetes Rechteck… Row Size: Zeilengröße: + Rows Zeilen Rows: Zeilen: Rule: Regel: Rulers Lineale @@ -3354,6 +3437,11 @@ digits Malayalam Malayalam Search commands, tools, panels and effects… Befehle, Werkzeuge, Bedienfelder und Effekte suchen… No commands match Keine passenden Befehle {pos} of {total}: {name} {pos} von {total}: {name} + No menu item Kein Menüeintrag + Toolbar Werkzeugleiste + {toolbar}, in the {tool} group {toolbar}, in der Gruppe „{tool}“ + Tool Werkzeug + Command Befehl @plural {n} result|{n} results {n} Ergebnis|{n} Ergebnisse @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} von {n} Ergebnis. Tippen Sie weiter, um sie einzugrenzen.|{shown} von {n} Ergebnissen. Tippen Sie weiter, um sie einzugrenzen. Recent Commands Zuletzt verwendete Befehle @@ -3434,6 +3522,7 @@ digits Malayalam Malayalam Set Slice Rectangle Slice-Rechteck festlegen Set Tab Stops Tabstopps festlegen Set Text Text festlegen + Set the current fill or stroke to the selected color Aktuelle Fläche oder Kontur auf die ausgewählte Farbe setzen Set the selected color to the current color Ausgewählte Farbe auf die aktuelle Farbe setzen Set Zoom Zoom festlegen Settings… Einstellungen… @@ -3557,7 +3646,7 @@ digits Malayalam Malayalam Show Vivid/Muted Lebhaft/Gedeckt einblenden Show Warm/Cool Warm/Kalt einblenden Show {kind} Brushes {kind}pinsel einblenden - Show/hide plate (Alt-click: only this plate) Platte ein-/ausblenden (Alt-Klick: nur diese Platte) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Platte ein-/ausblenden (Alt-Klick: nur diese Platte; erneuter Alt-Klick: alle Platten) Show: Anzeigen: Shown with the optimised preview. Wird mit der optimierten Vorschau angezeigt. Side 1: Seite 1: @@ -3849,7 +3938,7 @@ effect Points Punkte Composite Fonts Zusammengesetzte Schriften Export Composite Fonts Zusammengesetzte Schriften exportieren Import Composite Fonts Zusammengesetzte Schriften importieren -@msg each font must be {name, parts} jede Schrift muss {name, parts} sein +@msg each font must be {{name, parts}} jede Schrift muss {{name, parts}} sein @msg unknown key `{k}`; a font takes name and parts unbekannter Schlüssel `{k}`; eine Schrift nimmt name und parts @msg each font needs a name jede Schrift braucht einen Namen @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` kann keine zusammengesetzte Schrift benennen (1 bis {COMPOSITE_NAME_MAX} Zeichen, keine Steuerzeichen) @@ -3862,7 +3951,7 @@ effect Points Punkte @msg two composite fonts are named `{_1}` zwei zusammengesetzte Schriften heißen `{_1}` @msg `{_1}` is the name of an installed font `{_1}` ist der Name einer installierten Schrift @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2} ist in `{font}` gesetzt, einer zusammengesetzten Schrift -@msg give fonts: [{name, parts}…] geben Sie fonts an: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] geben Sie fonts an: [{{name, parts}}…] @msg path is empty path ist leer @msg fonts must be a list of composite fonts fonts muss eine Liste zusammengesetzter Schriften sein @msg names must be strings names müssen Zeichenketten sein @@ -3945,6 +4034,13 @@ effect Points Punkte Thumbnail View Miniaturansicht Thumbnails: Miniaturen: Tile Nebeneinander + Tile All Vertically Alle vertikal nebeneinander + Tile All Horizontally Alle horizontal nebeneinander + 2-Up Layout Layout mit 2 + 3-Up Layout Layout mit 3 + 4-Up Layout Layout mit 4 + 6-Up Layout Layout mit 6 + Arrange Documents Dokumente anordnen Tile Edge Color Farbe der Kachelkante Tile Edge Color… Farbe der Kachelkante… Tile Full Pages Ganze Seiten aufteilen @@ -4139,6 +4235,8 @@ effect Points Punkte V Spacing: V-Abstand: V: V: Variable Width Profile Variables Breitenprofil + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Der Pinsel der Kontur behält seine eigene Größe, daher ändert ein Breitenprofil die Kontur nicht. Entfernen Sie den Pinsel, um ein Profil zu verwenden. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Der Pinsel der Kontur behält seine eigene Größe, daher ändert ein Breitenprofil die Kontur nicht. Entfernen Sie den Pinsel, um ein Profil zu verwenden. Variables Variablen Variation: Variation: Vector Effects Vektoreffekte @@ -4169,7 +4267,7 @@ effect Points Punkte Vertical: Vertikal: Very High Sehr hoch View Ansicht - View Artboard Only Nur Zeichenfläche anzeigen + View Artboard Contents Only Nur Inhalt der Zeichenfläche anzeigen View Opacity Mask Deckkraftmaske anzeigen View PDF after saving PDF nach dem Speichern anzeigen View {n} Ansicht {n} @@ -4387,6 +4485,7 @@ imageTrace Outline Kontur Bevel Abgeflacht Offset Versatz Axis Achse + Axis Angle Achsenwinkel axis Horizontal Horizontal axis Vertical Vertikal axis Both Beide @@ -4464,6 +4563,13 @@ theme Appearance Erscheinungsbild Show External Script Warning Warnung bei externen Skripten anzeigen A Script Is Running Ein Skript wird ausgeführt Script Alert Skriptmeldung + Script File Access Dateizugriff des Skripts + The script asks to read a file you choose. Das Skript möchte eine Datei lesen, die Sie auswählen. + The script asks to read and write a file you choose. Das Skript möchte eine Datei lesen und schreiben, die Sie auswählen. + The script asks to read and write a folder you choose, with everything in it. Das Skript möchte einen Ordner, den Sie auswählen, mit seinem gesamten Inhalt lesen und schreiben. + Allow Once Einmal erlauben + Always Allow This Script Dieses Skript immer erlauben + Deny Ablehnen A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Ein Skript kann die geöffneten Dokumente ändern und über die ausgeführten Befehle Dateien schreiben. Führen Sie nur Skripte aus, denen Sie vertrauen. Do not show this warning again Diese Warnung nicht mehr anzeigen Stop the script and undo what it did? Then quit again. Skript stoppen und seine Änderungen rückgängig machen? Beenden Sie danach erneut. @@ -4480,6 +4586,8 @@ theme Appearance Erscheinungsbild @msg the script is no longer in the Scripts folder das Skript befindet sich nicht mehr im Ordner „Scripts“ Some scripts were not listed Einige Skripte wurden nicht aufgeführt The Scripts folder cannot be read Der Ordner „Scripts“ kann nicht gelesen werden + Loading scripts… Skripte werden geladen… + The Scripts folder is still being read Der Ordner „Scripts“ wird noch gelesen @msg the script's run is no longer available der Lauf des Skripts ist nicht mehr verfügbar @msg a failed command changed undo steps that could not be put back, so the script was stopped ein fehlgeschlagener Befehl hat Rückgängig-Schritte geändert, die nicht wiederhergestellt werden konnten, daher wurde das Skript angehalten @msg a recovery copy could not be written, so the script was not run eine Wiederherstellungskopie konnte nicht geschrieben werden, daher wurde das Skript nicht ausgeführt @@ -4492,8 +4600,6 @@ theme Appearance Erscheinungsbild @msg Script file could not be read Die Skriptdatei konnte nicht gelesen werden @msg Script folder has more than 2,048 entries Der Skriptordner hat mehr als 2.048 Einträge @msg Script file open mode must be r, w, e or a Der Öffnungsmodus der Skriptdatei muss r, w, e oder a sein -@msg Script file writing is not available Das Schreiben von Skriptdateien ist nicht verfügbar -@msg Script file dialogs are not available Dateidialoge für Skripte sind nicht verfügbar @msg Script files cannot be opened in another application Skriptdateien können nicht in einer anderen Anwendung geöffnet werden @msg Script file access is unavailable on the web Der Zugriff auf Skriptdateien ist im Web nicht verfügbar @msg Script has 256 files open Das Skript hat 256 Dateien geöffnet @@ -4610,6 +4716,27 @@ liquify-list-end {0}, {1} {0} und {1} @msg there is no script engine named {name} es gibt keine Skript-Engine namens {name} @msg Running a script Skript wird ausgeführt @msg Copied the script report Skriptbericht kopiert +@msg Script file access denied: {path} Dateizugriff des Skripts verweigert: {path} +@msg Script file access to the app's own folders is not allowed Skripte dürfen nicht auf die eigenen Ordner der App zugreifen +@msg Script file cannot encode the text Skriptdatei kann den Text nicht kodieren +@msg Script file could not be written Skriptdatei konnte nicht geschrieben werden +@msg Script file dialogs need a person to answer them Dateidialoge von Skripten brauchen eine Person, die sie beantwortet +@msg Script file is not open for writing Skriptdatei ist nicht zum Schreiben geöffnet +@msg Script file name is already in use Name der Skriptdatei wird bereits verwendet +@msg Script file name must be a name without a folder Name der Skriptdatei muss ein Name ohne Ordner sein +@msg Script file permission can be kept only for a script run from a file Dateiberechtigung kann nur für ein Skript behalten werden, das aus einer Datei ausgeführt wird +@msg Script file permission could not be saved Dateiberechtigung des Skripts konnte nicht gespeichert werden +@msg Script folder is not empty Skriptordner ist nicht leer +@msg Script files cannot make aliases Skriptdateien können keine Aliasse erstellen +@msg Script file hidden setting cannot be changed Ausgeblendet-Einstellung der Skriptdatei kann nicht geändert werden +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: ein Dateidialog kann nicht in einem Callback einer eingebauten Funktion, eines Getters, einer Umwandlung oder einer Datei geöffnet werden, die $.evalFile ausführt; rufen Sie ihn aus dem eigenen Code des Skripts auf +@msg the script wrote more file data than one run may write (32 MiB) das Skript hat mehr Dateidaten geschrieben, als ein Lauf schreiben darf (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` für den Dateidialog eines Skripts muss einer der folgenden Werte sein: once, always, deny, stop +@msg choose a file or folder first, or deny wählen Sie zuerst eine Datei oder einen Ordner aus oder lehnen Sie ab +@msg the script file permissions could not be saved: {e} die Dateiberechtigungen der Skripte konnten nicht gespeichert werden: {e} +@msg this script's file access can be allowed only once der Dateizugriff dieses Skripts kann nur einmal erlaubt werden +@msg Only the person at the keyboard can allow a script's file access Nur die Person an der Tastatur kann den Dateizugriff eines Skripts erlauben +@msg A script is given at most 2,048 files: the files picked after them were left out Ein Skript erhält höchstens 2.048 Dateien: Die danach ausgewählten Dateien wurden weggelassen @msg Copied the link info Verknüpfungsinformationen kopiert @msg Corners edits the corners of a path „Ecken“ bearbeitet die Ecken eines Pfads @msg Couldn't copy to the system clipboard: {e} In die Systemzwischenablage konnte nicht kopiert werden: {e} @@ -4685,6 +4812,7 @@ liquify-list-end {0}, {1} {0} und {1} @msg Saved {path} {path} gespeichert @msg Select text or click into text with the Type tool to insert glyphs Wählen Sie Text aus oder klicken Sie mit dem Text-Werkzeug in einen Text, um Glyphen einzufügen @msg Shape Builder: no region under the pointer Formerstellung: kein Bereich unter dem Zeiger +@msg Shape Builder: select all paths you want to merge Formerstellung: Wählen Sie alle Pfade aus, die Sie zusammenfügen möchten @msg Shape Builder: select paths or compound paths Formerstellung: Wählen Sie Pfade oder zusammengesetzte Pfade aus @msg Show All Hidden Attributes: nothing is hidden Alle ausgeblendeten Attribute einblenden: Es ist nichts ausgeblendet @msg Split Into Grid: select paths large enough for the grid In Raster teilen: Wählen Sie Pfade aus, die groß genug für das Raster sind @@ -4740,6 +4868,8 @@ liquify-list-end {0}, {1} {0} und {1} @msg `{min_key}` is greater than `{max_key}` `{min_key}` ist größer als `{max_key}` @msg give at least one of `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` geben Sie mindestens einen der Parameter `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` an @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` muss grayscale, rgb, hsb, cmyk oder websafe sein +@msg `view` must be wheel or box `view` muss wheel oder box sein +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` muss hue, saturation, brightness, red, green oder blue sein @msg `{k}` must be [x, y] `{k}` muss [x, y] sein @msg `{name}` has no options `{name}` hat keine Optionen @msg `{name}` is a built-in workspace; choose another name `{name}` ist ein integrierter Arbeitsbereich; wählen Sie einen anderen Namen @@ -4828,6 +4958,7 @@ liquify-list-end {0}, {1} {0} und {1} @msg bad trailer fehlerhafter Trailer @msg balance must be between 0 and 100 balance muss zwischen 0 und 100 liegen @msg batch step {_1} (`{id}`) failed: {e} Stapelschritt {_1} (`{id}`) ist fehlgeschlagen: {e} +@msg action step {_1} (`{id}`) failed: {reason} Aktionsschritt {_1} (`{id}`) ist fehlgeschlagen: {reason} @msg brightness must be dark|mediumDark|mediumLight|light brightness muss dark|mediumDark|mediumLight|light sein @msg can't encode the document: {0} das Dokument kann nicht kodiert werden: {0} @msg can't parse shortcut `{c}` Tastaturbefehl `{c}` kann nicht ausgewertet werden @@ -4847,6 +4978,7 @@ liquify-list-end {0}, {1} {0} und {1} @msg choose a folder to export to wählen Sie einen Ordner für den Export @msg choose a location for the package wählen Sie einen Speicherort für das Paket @msg clipboard is empty die Zwischenablage ist leer +@msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: Mindestens eine Farbe muss in der Farbtabelle bleiben @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` ist keine Farbe wie "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: höchstens {MAX_TABLE} Farben @msg command `{0}` is not available right now: {1} der Befehl `{0}` ist derzeit nicht verfügbar: {1} @@ -4914,9 +5046,15 @@ liquify-list-end {0}, {1} {0} und {1} @msg no PNG encoder kein PNG-Encoder @msg no active document kein aktives Dokument @msg no active perspective plane keine aktive Perspektivebene +@msg the perspective grid is hidden das Perspektivenraster ist ausgeblendet +@msg Automatic Plane Positioning is off: turn on anchorPoint or gridlineIntersection (perspective.widget.options) Die automatische Ebenenpositionierung ist ausgeschaltet: Schalten Sie anchorPoint oder gridlineIntersection ein (perspective.widget.options) +@msg anchorPoint must be true or false anchorPoint muss true oder false sein +@msg gridlineIntersection must be true or false gridlineIntersection muss true oder false sein +@msg tolerance must be 0 or more tolerance muss 0 oder größer sein +@msg give `at` or `clear`, not both geben Sie `at` oder `clear` an, nicht beides @msg no anchor points selected keine Ankerpunkte ausgewählt -@msg `points` must be three [x, y] pairs of numbers `points` muss aus drei Zahlenpaaren [x, y] bestehen -@msg direct-select three anchor points, or give `points` wählen Sie drei Ankerpunkte direkt aus oder geben Sie `points` an +@msg `points` must be two or three [x, y] pairs of numbers `points` muss aus zwei oder drei Zahlenpaaren [x, y] bestehen +@msg direct-select two or three anchor points, or give `points` wählen Sie zwei oder drei Ankerpunkte direkt aus oder geben Sie `points` an @msg no circle passes through these points: two are the same or all three lie on one line durch diese Punkte verläuft kein Kreis: zwei sind gleich oder alle drei liegen auf einer Linie @msg no app to open files here hier gibt es keine App zum Öffnen von Dateien @msg no artboard keine Zeichenfläche @@ -5019,6 +5157,9 @@ liquify-list-end {0}, {1} {0} und {1} @msg no such user library keine solche Benutzerbibliothek @msg no such view keine solche Ansicht @msg no such width point kein solcher Breitenpunkt +@msg `single` must be `incoming` or `outgoing` `single` muss `incoming` oder `outgoing` sein +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` und `outIndex` müssen die beiden Hälften eines unterbrochenen Breitenpunkts sein +@msg a discontinuous width point keeps its place ein unterbrochener Breitenpunkt behält seine Position @msg no swatch `{name}` kein Farbfeld `{name}` @msg no swatch library `{l}` (see swatch.library.list) keine Farbfeldbibliothek `{l}` (siehe swatch.library.list) @msg no symbol instances selected keine Symbolinstanzen ausgewählt @@ -5278,6 +5419,13 @@ liquify-list-end {0}, {1} {0} und {1} @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} mehr als {MAX_CSV_ROWS} Datensätze: „Datensätze importieren“ liest höchstens {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} mehr als {MAX_CSV_COLS} Variablen: „Datensätze importieren“ liest höchstens {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} die Variablen, die kein Text sind, wurden ausgelassen: {kinds} +variable-kind Visibility Sichtbarkeit +variable-kind Linked File Verknüpfte Datei +variable-kind Graph Data Diagrammdaten +variable-kind Unknown Unbekannt +variable-list-two {0}, {1} {0} und {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} und {1} @msg a new document won't read these variables back with their kind: {names} ein neues Dokument liest diese Variablen nicht mit ihrer Art zurück: {names} @msg a new document refuses this file because of these variables: {names} ein neues Dokument lehnt diese Datei wegen dieser Variablen ab: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them die Kopfzeile `{header}` für `{name}` würde als die Variable `{other}` gelesen: Benennen Sie eine der beiden um @@ -5303,6 +5451,8 @@ liquify-list-end {0}, {1} {0} und {1} @msg {label}: lost track of a shape's style {label}: Der Stil einer Form ging verloren @msg {label}: select paths {label}: Wählen Sie Pfade aus @msg {label}: select paths, compound paths, groups or text {label}: Wählen Sie Pfade, zusammengesetzte Pfade, Gruppen oder Text aus +@msg a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first eine Linie oder ein anderer offener Pfad, der keine Fläche umschließt, ändert die Form des Ergebnisses nicht; um ihn einzubeziehen, wenden Sie zuerst Objekt › Pfad › Konturlinie darauf an +@msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first {label} hat ein leeres Ergebnis geliefert: eine Linie oder ein anderer offener Pfad umschließt keine Fläche; um ihn einzubeziehen, wenden Sie zuerst Objekt › Pfad › Konturlinie darauf an @msg {label}… {label}… @msg {name}: CRC mismatch {name}: CRC stimmt nicht überein @msg {name}: no local header {name}: kein lokaler Header @@ -5329,6 +5479,9 @@ liquify-list-end {0}, {1} {0} und {1} @msgplural Discarded {n} recovered document|Discarded {n} recovered documents {n} wiederhergestelltes Dokument verworfen|{n} wiederhergestellte Dokumente verworfen @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them {n} wiederhergestelltes Dokument geöffnet: Speichern Sie es, um es zu behalten|{n} wiederhergestellte Dokumente geöffnet: Speichern Sie sie, um sie zu behalten @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} Mit {n} Hinweis geöffnet: {first}|Mit {n} Hinweisen geöffnet: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Mit {n} Hinweis kopiert: {first}|Mit {n} Hinweisen kopiert: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Mit {n} Hinweis ausgeschnitten: {first}|Mit {n} Hinweisen ausgeschnitten: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Mit {n} Hinweis nachgezeichnet: {first}|Mit {n} Hinweisen nachgezeichnet: {first} @msgplural {notice}. Opened with {n} note: {first}|{notice}. Opened with {n} notes: {first} {notice}. Mit {n} Hinweis geöffnet: {first}|{notice}. Mit {n} Hinweisen geöffnet: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} {path} mit {n} Hinweis gespeichert: {first}|{path} mit {n} Hinweisen gespeichert: {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first {n} Bild eingebettet; {missing} fehlen: Verknüpfen Sie sie zuerst neu|{n} Bilder eingebettet; {missing} fehlen: Verknüpfen Sie sie zuerst neu @@ -5355,6 +5508,8 @@ liquify-list-end {0}, {1} {0} und {1} @msg All colors are within the CMYK gamut Alle Farben liegen im CMYK-Farbumfang @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} Farbe liegt außerhalb des CMYK-Farbumfangs|{n} Farben liegen außerhalb des CMYK-Farbumfangs @msg Unembedded to {_1} Einbettung aufgehoben, gespeichert unter {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} Einbettung von {n} Bild aufgehoben, gespeichert unter {folder}|Einbettung von {n} Bildern aufgehoben, gespeichert unter {folder} +@msg every numbered name for {name} is taken in that folder alle nummerierten Namen für {name} sind in diesem Ordner bereits vergeben @msg Reset {_1} {_1} zurückgesetzt @msg Sent to {_1} An {_1} gesendet @msg {_1} files {_1}-Dateien @@ -5370,6 +5525,8 @@ liquify-list-end {0}, {1} {0} und {1} @msg Reload the page to go on (changes not saved yet may be lost). Laden Sie die Seite neu, um fortzufahren (noch nicht gespeicherte Änderungen können verloren gehen). @msg tool (a tool id) is required tool (eine Werkzeug-ID) ist erforderlich @msg {tool} isn't in a toolbar group of several tools {tool} gehört zu keiner Werkzeuggruppe mit mehreren Werkzeugen +@msg Presentation Mode hides the toolbars: change the screen mode to show them der Präsentationsmodus blendet die Werkzeugleisten aus: Ändern Sie den Bildschirmmodus, um sie anzuzeigen +@msg Tab has hidden the toolbars: press Tab to show them die Tabulatortaste hat die Werkzeugleisten ausgeblendet: Drücken Sie die Tabulatortaste, um sie anzuzeigen @msg onto must name a panel floating in another group onto muss ein Bedienfeld nennen, das in einer anderen Gruppe schwebt @msg below and above must name a panel floating in another group below und above müssen ein Bedienfeld nennen, das in einer anderen Gruppe schwebt @msg give only one of onto, below and above nur eines von onto, below und above angeben @@ -5484,6 +5641,9 @@ liquify-list-end {0}, {1} {0} und {1} Cap Height Versalhöhe x-Height x-Höhe ICF Box ICF-Rahmen + Ascent Oberlänge + x Height x-Höhe + Em Box Height Gevierthöhe Show Sample Muster einblenden Hide Sample Muster ausblenden Max Ascent/Descent Max. Höhe/Tiefe @@ -5573,6 +5733,7 @@ liquify-list-end {0}, {1} {0} und {1} Scatter: Streuung: Rotation: Drehung: Rotation relative to: Drehung relativ zu: + Hue Jitter: Farbtonvariation: Side Tile Seitenkachel Outer Corner Tile Äußere Eckkachel Inner Corner Tile Innere Eckkachel @@ -5795,6 +5956,7 @@ lighting Light Licht @msg missing panel layout Bedienfeldanordnung fehlt @msg unsupported native docking operation Nicht unterstützte native Docking-Operation Linux Display Server Linux-Anzeigeserver + Low-Latency Drawing Zeichnen mit geringer Latenz X11 (XWayland) When a Pen Is Attached X11 (XWayland), wenn ein Stift angeschlossen ist If a drawing tablet's pen doesn't draw, choose an X11 (XWayland) option. Wenn der Stift eines Grafiktabletts nicht zeichnet, wählen Sie eine Option mit X11 (XWayland). X11 (XWayland) X11 (XWayland) @@ -5856,6 +6018,7 @@ lighting Light Licht Cove Hohlkehle Depth Tiefe Front Vorne + Side Seite Isometric Bottom Isometrisch unten Isometric Left Isometrisch links Isometric Right Isometrisch rechts @@ -5950,7 +6113,7 @@ lighting Light Licht @msg each of `{GRAPHICS}` must be an object jeder Eintrag von `{GRAPHICS}` muss ein Objekt sein @msg `{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}` `{GRAPHICS}`-Einträge nehmen symbol, face, x, y, scale und rotation an, nicht `{k}` @msg each of `{GRAPHICS}` needs `symbol`, the name of a symbol jeder Eintrag von `{GRAPHICS}` braucht `symbol`, den Namen eines Symbols -@msg `{GRAPHICS}` face must be front or back face in `{GRAPHICS}` muss front oder back sein +@msg `{GRAPHICS}` face must be front, back or side face in `{GRAPHICS}` muss front, back oder side sein @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} in `{GRAPHICS}` muss eine Zahl von {lo} bis {hi} sein @msg `{GRAPHICS}` must be an array `{GRAPHICS}` muss ein Array sein @msg Graphics map onto the Plane, Extrude and Revolve object types Grafiken werden auf die Objekttypen Ebene, Extrudieren und Kreiseln abgebildet @@ -6972,6 +7135,12 @@ anchor Points: Punkte: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` muss "free", "keepAngles" oder "symmetric" sein @msg `{key}` must be [x, y] `{key}` muss [x, y] sein +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Einheitenumrechner + Unit Converter Panel Einheitenumrechner-Bedienfeld + Copy with Units Mit Einheiten kopieren + From Selection Aus Auswahl + # Color Effects add-on: Select by Color Kind. Select by Color Kind Nach Farbart auswählen Objects with Spot Colors Objekte mit Volltonfarben @@ -7197,6 +7366,14 @@ breakText Glyphs Glyphen Remove Gaps Lücken entfernen @msg that makes too many pieces (at most 100000): make the dashes longer das ergibt zu viele Teile (höchstens 100000): machen Sie die Striche länger @msg select paths, or segments, to divide wählen Sie Pfade oder Segmente zum Aufteilen aus +# Path Precision Tools add-on: Smooth Bridge. + Smooth Bridge… Weiche Brücke… + Smooth Bridge Weiche Brücke + Keep Originals Originale beibehalten +@msg select two circles to bridge wählen Sie zwei Kreise zum Verbinden aus +@msg one circle is inside the other ein Kreis liegt im anderen +@msg the circles are too far apart for this radius: raise the radius die Kreise liegen für diesen Radius zu weit auseinander: vergrößern Sie den Radius +@msg the circles are too far apart for this radius die Kreise liegen für diesen Radius zu weit auseinander # Path Precision Tools add-on: Common Tangents. Common Tangents… Gemeinsame Tangenten… Common Tangents Gemeinsame Tangenten @@ -7563,6 +7740,14 @@ breakText Glyphs Glyphen @msg `answers` has more than {MAX_ANSWERS} answers `answers` hat mehr als {MAX_ANSWERS} Antworten @msg `answers` is larger than 1 MiB `answers` ist größer als 1 MiB @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` ist nur für einen Lauf ohne jemanden, der gefragt werden kann: In der App beantwortet die Person jeden Dialog +@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` muss eine ganze Zahl von 1 bis {_1} sein +@msg `args{place}` is nested more than 64 levels deep `args{place}` ist mehr als 64 Ebenen tief verschachtelt +@msg `args` must be an object `args` muss ein Objekt sein +@msg `args` is larger than 1 MiB `args` ist größer als 1 MiB +@msg `path` is empty `path` ist leer +@msg `installed` takes a `path`, not a `source` `installed` nimmt einen `path`, keine `source` +@msg `path` must name a .js or .jsx file `path` muss eine .js- oder .jsx-Datei angeben +@msg give exactly one of `path` and `source` geben Sie genau eines von `path` und `source` an @msg `answers` must be a list of answers `answers` muss eine Liste von Antworten sein @msg `artboard` must be the index of an artboard of the document `artboard` muss der Index einer Zeichenfläche des Dokuments sein @msg `artboardsAt` must be [x, y] `artboardsAt` muss [x, y] sein @@ -7603,7 +7788,7 @@ breakText Glyphs Glyphen @msg `rows` must be lists of numbers or nulls, not {r} `rows` müssen Listen aus Zahlen oder null-Werten sein, nicht {r} @msg `scale` must be a number from 0.001 to 1000 `scale` muss eine Zahl von 0,001 bis 1000 sein @msg `scope.{key}` must be a non-empty array `scope.{key}` muss ein nicht leeres Array sein -@msg `scope` must be "document", {artboards} or {layers} `scope` muss „document“, {artboards} oder {layers} sein +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` muss "document", {{artboards: [index, …]}} oder {{layers: [id, …]}} sein @msg `side` must be "left", "right", "top" or "bottom" `side` muss „left“, „right“, „top“ oder „bottom“ sein @msg `side` places the artboard: leave out x, y, width and height `side` platziert die Zeichenfläche: Lassen Sie x, y, width und height weg @msg `source` is the only path in series group `target` `source` ist der einzige Pfad in der Reihengruppe `target` @@ -7783,7 +7968,7 @@ breakText Glyphs Glyphen @msg not a regular expression kein regulärer Ausdruck @msg not an action set: the text doesn't start with /version and a number kein Aktionssatz: Der Text beginnt nicht mit /version und einer Zahl @msg nothing to repeat nichts zu wiederholen -@msg numbers out of order in {_1} quantifier Zahlen in falscher Reihenfolge im Quantifizierer {_1} +@msg numbers out of order in {{}} quantifier Zahlen in falscher Reihenfolge im Quantifizierer {{}} @msg object {_1} needs a 3D effect Objekt {_1} braucht einen 3D-Effekt @msg object {_1}: a hollow Extrude & Bevel has no caps: turn on Cap to map a graphic Objekt {_1}: Ein hohles „Extrudieren und abgeflachte Kante“ hat keine Deckflächen: Aktivieren Sie „Deckflächen“, um eine Grafik zuzuweisen @msg object {_1}: with a depth of 0 the object has one face: map its graphics onto the front Objekt {_1}: Bei einer Tiefe von 0 hat das Objekt nur eine Fläche: Weisen Sie seine Grafiken der Vorderseite zu @@ -7851,7 +8036,7 @@ breakText Glyphs Glyphen @msg the guide is hidden or locked die Hilfslinie ist ausgeblendet oder gesperrt @msg the library's file is outside the read roots die Datei der Bibliothek liegt außerhalb der Lesestammordner @msg the method needs an XML value die Methode braucht einen XML-Wert -@msg the paint is not a freeform gradient (apply one with paint.editGradient {kind}) die Farbe ist kein Freiformverlauf (wenden Sie einen mit paint.editGradient {kind} an) +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) die Farbe ist kein Freiformverlauf (wenden Sie einen mit paint.editGradient {{kind: "freeform"}} an) @msg the parameters or body do not form one function die Parameter oder der Rumpf bilden keine einzelne Funktion @msg the pasted SVG filter {name} draws differently from the document's filter of that name, and no free name fits it der eingefügte SVG-Filter {name} zeichnet anders als der gleichnamige Filter des Dokuments, und kein freier Name passt zu ihm @msg the pen table holds more than 255 pens die Stifttabelle enthält mehr als 255 Stifte @@ -8135,6 +8320,8 @@ breakText Glyphs Glyphen @msg `{f}` is the copy of a document open now `{f}` ist die Kopie eines gerade geöffneten Dokuments @msg `{id}` is no writable format (see document.formats) `{id}` ist kein beschreibbares Format (siehe document.formats) @msg `{id}` isn't a loaded library `{id}` ist keine geladene Bibliothek +@msg `{file}` has no swatches of its own `{file}` hat keine eigenen Farbfelder +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` enthält Musterfelder, die eine .vcswatches-Datei nicht aufnehmen kann @msg `{key}` has no colours `{key}` hat keine Farben @msg `{key}` is a design name `{key}` ist ein Designname @msg `{key}` is a design name or a list of them `{key}` ist ein Designname oder eine Liste davon @@ -8357,7 +8544,13 @@ breakText Glyphs Glyphen @msg colorModel must be {own} (the document's mode), grayscale or bitmap colorModel muss {own} (der Modus des Dokuments), grayscale oder bitmap sein @msg colour groups can't go into colour groups Farbgruppen können nicht in Farbgruppen eingefügt werden @msg colour, mode and spot apply to solid-colour swatches only colour, mode und spot gelten nur für Vollfarbfelder -@msg column {column}: `{cell}` is a `%` column of graph data files, which are not read Spalte {column}: `{cell}` ist eine `%`-Spalte von Diagrammdatendateien, die nicht gelesen werden +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path Zeile {line}, Spalte {column}: die Diagrammdatendatei `{path}` für `{var}` ist ein relativer Pfad: Geben Sie `base` oder einen absoluten Pfad an +@msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} Zeile {line}, Spalte {column}: die Diagrammdatendatei für `{var}` kann nicht gelesen werden: {e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` isn't followed: {r} Zeile {line}, Spalte {column}: der Diagrammdatendatei `{path}` für `{var}` wird nicht gefolgt: {r} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes Zeile {line}, Spalte {column}: die Diagrammdatendatei `{path}` für `{var}` ist größer als {MAX_GRAPH_DATA_FILE} Byte +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes Zeile {line}, Spalte {column}: die Diagrammdatendatei `{path}` für `{var}` ergibt einen Diagrammwert, der länger als {MAX_GRAPH_CSV} Byte ist +@msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all Zeile {line}, Spalte {column}: die Diagrammdatendateien enthalten insgesamt mehr als {MAX_GRAPH_FILES_TOTAL} Byte +@msg `base` is empty `base` ist leer @msg column {column}: `{cell}` names `{name}`, which is a {_1} variable Spalte {column}: `{cell}` nennt `{name}`, eine Variable vom Typ {_1} @msg column {column}: `{cell}` names no variable Spalte {column}: `{cell}` nennt keine Variable @msg column {column}: the variable name is longer than {MAX_NAME} characters Spalte {column}: Der Variablenname ist länger als {MAX_NAME} Zeichen @@ -8369,6 +8562,7 @@ breakText Glyphs Glyphen @msg compound {_1} must contain exactly one open path to join zusammengesetzter Pfad {_1} muss genau einen offenen Pfad zum Zusammenfügen enthalten @msg connect end must be "start" or "end" connect end muss „start“ oder „end“ sein @msg connect needs a path other than the one extended connect braucht einen anderen Pfad als den verlängerten +@msg connect needs extend connect braucht extend @msg connect needs id connect braucht id @msg connect path has no open end der connect-Pfad hat kein offenes Ende @msg copy needs path: the file to copy into the document's folder copy braucht path: die Datei, die in den Ordner des Dokuments kopiert werden soll @@ -9392,6 +9586,8 @@ breakText Glyphs Glyphen @msg a line needs at least two points eine Linie braucht mindestens zwei Punkte @msg a linked JavaScript file is outside the read roots eine verknüpfte JavaScript-Datei liegt außerhalb der Lesestammordner @msg a linked image file is outside the read roots eine verknüpfte Bilddatei liegt außerhalb der Lesestammordner +@msg a linked file's export folder is outside the read roots der Exportordner einer verknüpften Datei liegt außerhalb der Lesestammordner +@msg a linked file's editing data can't be read to check it against the read roots die Bearbeitungsdaten einer verknüpften Datei können nicht gelesen werden, um sie mit den Lesestammordnern abzugleichen @msg a number cannot be read eine Zahl kann nicht gelesen werden @msg a swatch exchange block is too long ein Block der Farbfeld-Austauschdatei ist zu lang @msg a swatch exchange name is too long ein Name in der Farbfeld-Austauschdatei ist zu lang @@ -9516,3 +9712,13 @@ breakText Glyphs Glyphen @msg A panel is not joined to the rest by a crease. Ein Feld ist durch keine Rilllinie mit den übrigen verbunden. @msg A fold line is on a non-printing layer. Eine Faltlinie liegt auf einer nicht druckbaren Ebene. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Felder: {panels}, Scharniere: {hinges}, Fehler: {errors}, Warnungen: {warnings} + Fold Preview Faltvorschau + Fold Falten + Show Fold Lines Faltlinien einblenden + Three-Quarter Dreiviertelansicht + Open a document to preview its folded shape. Öffnen Sie ein Dokument, um seine gefaltete Form in der Vorschau zu sehen. +@msg Check the fold lines first. Prüfen Sie zuerst die Faltlinien. +@msg Panels: {panels}, hinges: {hinges} Felder: {panels}, Scharniere: {hinges} +@msg Other blanks not shown: {count} Weitere Zuschnitte nicht angezeigt: {count} +@msg A joint does not close by {gap} pt. Eine Verbindung schließt um {gap} pt nicht. +@msg Two panels pass through each other. Zwei Felder durchdringen einander. diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 1ebf6e5684..26202d14fa 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -99,6 +99,7 @@ Add Anchor Point Προσθήκη σημείου αγκύρωσης Add Anchor Point Tool Εργαλείο προσθήκης σημείου αγκύρωσης (Add Anchor Point Tool) Add Anchor Points Προσθήκη σημείων αγκύρωσης + Add Around Προσθήκη γύρω από το αντικείμενο Add Effect Προσθήκη εφέ Add Freeform Line Προσθήκη ελεύθερης γραμμής Add Freeform Point Προσθήκη ελεύθερου σημείου @@ -120,8 +121,12 @@ Add to Swatches Προσθήκη στα δείγματα χρωμάτων Add Used Colors Προσθήκη των χρησιμοποιημένων χρωμάτων Additional Plug-ins Folder Πρόσθετος φάκελος επεκτάσεων + Plug-in Instruction Budget Προϋπολογισμός εντολών επεκτάσεων Additional Fonts Folder Πρόσθετος φάκελος γραμματοσειρών Adjust Adjoining Width Points Ρύθμιση γειτονικών σημείων πλάτους + Incoming Εισερχόμενο + Outgoing Εξερχόμενο + Single Width Only Μόνο ένα πλάτος Adjust Color Balance… Ρύθμιση ισορροπίας χρωμάτων… Adjust Colors Ρύθμιση χρωμάτων Adjust Options: Επιλογές ρύθμισης: @@ -176,6 +181,7 @@ Angle: Γωνία: Angles Γωνίες Animated Zoom Κινούμενη μεγέθυνση + Anti Alias Εξομάλυνση ακμών Anti-alias Εξομάλυνση ακμών Anti-Alias Εξομάλυνση ακμών Anti-alias Rasters Εξομάλυνση ακμών εικόνων ράστερ @@ -339,6 +345,12 @@ font-technology Variable Μεταβλητές Brush Definition Ορισμός πινέλου Brush Libraries Βιβλιοθήκες πινέλων Brush Options… Επιλογές πινέλου… + Options of Selected Object… Επιλογές επιλεγμένου αντικειμένου… + Options of Selected Object Επιλογές επιλεγμένου αντικειμένου +@msg no path painted with a brush is selected δεν έχει επιλεγεί διαδρομή βαμμένη με πινέλο +@msg the selected paths are painted with brushes of different types οι επιλεγμένες διαδρομές είναι βαμμένες με πινέλα διαφορετικών τύπων +@msg give `params` or `reset`, not both δώστε `params` ή `reset`, όχι και τα δύο +@msg a bristle brush has no options of its own on a path ένα πινέλο με τρίχες δεν έχει δικές του επιλογές σε διαδρομή Brush Strokes Πινελιές Brushes Πινέλα Built-in Libraries Ενσωματωμένες βιβλιοθήκες @@ -390,6 +402,12 @@ font-technology Variable Μεταβλητές Character Alignment Στοίχιση χαρακτήρων Character / Paragraph Χαρακτήρας / Παράγραφος Character Rotation Περιστροφή χαρακτήρων + Chinese Big 5 Κινεζικά Big 5 + Cyrillic Κυριλλικά + Greek Ελληνικά + Turkish Τουρκικά + Baltic Βαλτικά + Central European Κεντρικής Ευρώπης Character Set: Σύνολο χαρακτήρων: Character Style Στυλ χαρακτήρων Character Style Options Επιλογές στυλ χαρακτήρων @@ -449,6 +467,8 @@ font-technology Variable Μεταβλητές Choose a folder Επιλογή φακέλου Choose… Επιλογή… Circle Κύκλος + Circle Tool Εργαλείο κύκλου + Circle too large Ο κύκλος είναι πολύ μεγάλος Classic Defaults Κλασικές προεπιλογές Clean Up… Εκκαθάριση… Clear Εκκαθάριση @@ -514,6 +534,7 @@ font-technology Variable Μεταβλητές Color Mixer (Shift-click the chip) Μείκτης χρωμάτων (Shift-κλικ στο δείγμα) Color Mode Λειτουργία χρώματος Color Mode: Λειτουργία χρώματος: + Color Model Μοντέλο χρώματος Color Model: Μοντέλο χρώματος: Color Models Μοντέλα χρώματος Color Picker Επιλογέας χρώματος @@ -534,12 +555,18 @@ font-technology Variable Μεταβλητές Saturation and brightness Κορεσμός και φωτεινότητα Color field Πεδίο χρώματος {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Προβολή τροχού + Box View Προβολή τετραγώνου + Box Channel Κανάλι τετραγώνου + Color box Τετράγωνο χρώματος + Color Wheel Options Επιλογές χρωματικού τροχού Color Type: Τύπος χρώματος: Color: Χρώμα: Colorize Χρωματισμός Colors Χρώματα Colors: Χρώματα: Column Graph Tool Γράφημα στηλών (Column Graph Tool) + Columns Στήλες Columns: Στήλες: Column… Στήλη… Combine Slices Συνδυασμός τομών @@ -749,6 +776,8 @@ font-technology Variable Μεταβλητές Delete Artboard Διαγραφή πίνακα σχεδίασης Delete Artboards Διαγραφή πινάκων σχεδίασης Delete Brush Διαγραφή πινέλου + Delete Color Διαγραφή χρώματος + Restore Generated Table Επαναφορά του παραγόμενου πίνακα Delete Character Style Διαγραφή στυλ χαρακτήρων Delete Empty Artboards Διαγραφή κενών πινάκων σχεδίασης Delete Freeform Point Διαγραφή ελεύθερου σημείου @@ -817,6 +846,7 @@ font-technology Variable Μεταβλητές Direct Selection Tool Άμεση επιλογή (Direct Selection Tool) Direction Handles Λαβές κατεύθυνσης Disable Auto Add/Delete Απενεργοποίηση αυτόματης προσθήκης/διαγραφής + Interpolate Control Points When Moving Anchors Παρεμβολή λαβών κατεύθυνσης κατά τη μετακίνηση σημείων αγκύρωσης Disable Opacity Mask Απενεργοποίηση μάσκας αδιαφάνειας Discard Απόρριψη Discard Empty Type Απόρριψη κενού κειμένου @@ -1017,6 +1047,7 @@ font-technology Variable Μεταβλητές Enable text access for screen readers Ενεργοποίηση πρόσβασης κειμένου για αναγνώστες οθόνης Enable Touch Gestures Ενεργοποίηση χειρονομιών αφής Switch Selection and Drawing Modes Εναλλαγή λειτουργιών επιλογής και σχεδίασης + Select Last Selection Tool Επιλογή του τελευταίου εργαλείου επιλογής Enable Touch Workspace Ενεργοποίηση χώρου εργασίας αφής Encoding Κωδικοποίηση Encoding: Κωδικοποίηση: @@ -1193,6 +1224,8 @@ font-technology Variable Μεταβλητές Files Αρχεία Files of a PDF standard can't be password-protected. Τα αρχεία αυτού του προτύπου PDF δεν μπορούν να προστατεύονται με κωδικό. Files of this standard tag their colours with ICC profiles. Τα αρχεία αυτού του προτύπου χαρακτηρίζουν τα χρώματά τους με προφίλ ICC. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Τα αρχεία αυτού του προτύπου χαρακτηρίζουν τα χρώματά τους με προφίλ ICC, εκτός από τα χρώματα CMYK στο προφίλ προορισμού εξόδου, τα οποία γράφονται ως DeviceCMYK. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. Με «Να μη συμπεριληφθούν προφίλ» και προορισμό εξόδου CMYK, κάθε χρώμα CMYK γράφεται ως DeviceCMYK, εκτός αν μετατραπεί σε προορισμό CMYK άλλου προφίλ. Fill Γέμισμα Fill & Stroke Γέμισμα και περίγραμμα Fill (X), double-click for the Color Picker Γέμισμα (X), διπλό κλικ για τον επιλογέα χρώματος @@ -1906,6 +1939,7 @@ font-technology Variable Μεταβλητές Rotation: Περιστροφή: Flip: Αναστροφή: Fit Προσαρμογή + Roundness Στρογγυλότητα Roundness: Στρογγυλότητα: Fixed Σταθερό Pressure Πίεση @@ -2099,6 +2133,7 @@ font-technology Variable Μεταβλητές Search Preferences Αναζήτηση στις προτιμήσεις No settings found Δεν βρέθηκαν ρυθμίσεις Reset to Default Επαναφορά προεπιλογής + Resolution Ανάλυση Resolution: Ανάλυση: Restore Επαναφορά Revert Επαναφορά αποθηκευμένης έκδοσης @@ -2119,6 +2154,7 @@ font-technology Variable Μεταβλητές Show Bounding Box While Moving and Drawing Εμφάνιση πλαισίου οριοθέτησης κατά τη μετακίνηση και τη σχεδίαση Rotate… Περιστροφή… Rotation Περιστροφή + Rows Γραμμές Rows: Γραμμές: Rulers Χάρακες Rulers & Grids Χάρακες και πλέγματα @@ -2262,6 +2298,13 @@ font-technology Variable Μεταβλητές Templates Πρότυπα Threshold Κατώφλι Tile Παράθεση + Tile All Vertically Παράθεση όλων κατακόρυφα + Tile All Horizontally Παράθεση όλων οριζόντια + 2-Up Layout Διάταξη ανά 2 + 3-Up Layout Διάταξη ανά 3 + 4-Up Layout Διάταξη ανά 4 + 6-Up Layout Διάταξη ανά 6 + Arrange Documents Διάταξη εγγράφων Tint Χρωματική απόχρωση Fill Tint Χρωματική απόχρωση γεμίσματος Stroke Tint Χρωματική απόχρωση περιγράμματος @@ -2438,6 +2481,13 @@ axis Both Και τα δύο Show External Script Warning Εμφάνιση προειδοποίησης για εξωτερικά σενάρια A Script Is Running Εκτελείται ένα σενάριο Script Alert Ειδοποίηση σεναρίου + Script File Access Πρόσβαση σεναρίου σε αρχεία + The script asks to read a file you choose. Το σενάριο ζητά να διαβάσει ένα αρχείο που θα επιλέξετε. + The script asks to read and write a file you choose. Το σενάριο ζητά να διαβάσει και να γράψει ένα αρχείο που θα επιλέξετε. + The script asks to read and write a folder you choose, with everything in it. Το σενάριο ζητά να διαβάσει και να γράψει έναν φάκελο που θα επιλέξετε, με όλο το περιεχόμενό του. + Allow Once Να επιτραπεί μία φορά + Always Allow This Script Να επιτρέπεται πάντα αυτό το σενάριο + Deny Άρνηση A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Ένα σενάριο μπορεί να αλλάξει τα ανοιχτά έγγραφα και να γράψει αρχεία μέσω των εντολών που εκτελεί. Εκτελείτε μόνο σενάρια που εμπιστεύεστε. Do not show this warning again Να μην εμφανιστεί ξανά αυτή η προειδοποίηση Stop the script and undo what it did? Then quit again. Διακοπή του σεναρίου και αναίρεση όσων έκανε; Έπειτα κάντε ξανά έξοδο. @@ -2454,6 +2504,8 @@ axis Both Και τα δύο @msg the script is no longer in the Scripts folder το σενάριο δεν βρίσκεται πλέον στον φάκελο Scripts Some scripts were not listed Ορισμένα σενάρια δεν εμφανίζονται στη λίστα The Scripts folder cannot be read Δεν είναι δυνατή η ανάγνωση του φακέλου Scripts + Loading scripts… Φόρτωση σεναρίων… + The Scripts folder is still being read Ο φάκελος Scripts διαβάζεται ακόμα @msg the script's run is no longer available η εκτέλεση του σεναρίου δεν είναι πλέον διαθέσιμη @msg a failed command changed undo steps that could not be put back, so the script was stopped μια εντολή που απέτυχε άλλαξε βήματα αναίρεσης που δεν ήταν δυνατό να επαναφερθούν, οπότε το σενάριο σταμάτησε @msg a recovery copy could not be written, so the script was not run δεν ήταν δυνατή η εγγραφή αντιγράφου ανάκτησης, οπότε το σενάριο δεν εκτελέστηκε @@ -2466,8 +2518,6 @@ axis Both Και τα δύο @msg Script file could not be read Δεν ήταν δυνατή η ανάγνωση του αρχείου σεναρίου @msg Script folder has more than 2,048 entries Ο φάκελος σεναρίου έχει περισσότερες από 2.048 καταχωρίσεις @msg Script file open mode must be r, w, e or a Ο τρόπος ανοίγματος του αρχείου σεναρίου πρέπει να είναι r, w, e ή a -@msg Script file writing is not available Η εγγραφή αρχείων σεναρίου δεν είναι διαθέσιμη -@msg Script file dialogs are not available Τα παράθυρα διαλόγου αρχείων σεναρίου δεν είναι διαθέσιμα @msg Script files cannot be opened in another application Τα αρχεία σεναρίου δεν μπορούν να ανοίξουν σε άλλη εφαρμογή @msg Script file access is unavailable on the web Η πρόσβαση σε αρχεία σεναρίου δεν είναι διαθέσιμη στο web @msg Script has 256 files open Το σενάριο έχει 256 ανοιχτά αρχεία @@ -2607,8 +2657,37 @@ liquify-list-end {0}, {1} {0} και {1} @msg is a prompt's answer, whose `value` must be a string or null είναι απάντηση σε prompt, οπότε το `value` πρέπει να είναι συμβολοσειρά ή null @msg must have `kind` alert, confirm or prompt πρέπει να έχει `kind` alert, confirm ή prompt @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog το `answers` είναι μόνο για εκτέλεση χωρίς κανέναν να ερωτηθεί: στην εφαρμογή, το άτομο απαντά σε κάθε παράθυρο διαλόγου +@msg `maxFuel` must be a whole number from 1 to {_1} το `maxFuel` πρέπει να είναι ακέραιος από 1 έως {_1} +@msg `args{place}` is nested more than 64 levels deep το `args{place}` έχει ένθεση μεγαλύτερη των 64 επιπέδων +@msg `args` must be an object το `args` πρέπει να είναι αντικείμενο +@msg `args` is larger than 1 MiB το `args` είναι μεγαλύτερο από 1 MiB +@msg `path` is empty το `path` είναι κενό +@msg `installed` takes a `path`, not a `source` το `installed` δέχεται `path`, όχι `source` +@msg `path` must name a .js or .jsx file το `path` πρέπει να ορίζει αρχείο .js ή .jsx +@msg give exactly one of `path` and `source` δώστε ακριβώς ένα από τα `path` και `source` @msg Running a script Εκτελείται σενάριο @msg Copied the script report Η αναφορά του σεναρίου αντιγράφηκε +@msg Script file access denied: {path} Η πρόσβαση του σεναρίου σε αρχεία απορρίφθηκε: {path} +@msg Script file access to the app's own folders is not allowed Δεν επιτρέπεται η πρόσβαση σεναρίων στους φακέλους της ίδιας της εφαρμογής +@msg Script file cannot encode the text Το αρχείο του σεναρίου δεν μπορεί να κωδικοποιήσει το κείμενο +@msg Script file could not be written Δεν ήταν δυνατή η εγγραφή του αρχείου του σεναρίου +@msg Script file dialogs need a person to answer them Τα παράθυρα διαλόγου αρχείων του σεναρίου χρειάζονται ένα άτομο για να απαντήσει +@msg Script file is not open for writing Το αρχείο του σεναρίου δεν είναι ανοιχτό για εγγραφή +@msg Script file name is already in use Το όνομα του αρχείου του σεναρίου χρησιμοποιείται ήδη +@msg Script file name must be a name without a folder Το όνομα του αρχείου του σεναρίου πρέπει να είναι όνομα χωρίς φάκελο +@msg Script file permission can be kept only for a script run from a file Η άδεια αρχείων μπορεί να διατηρηθεί μόνο για σενάριο που εκτελείται από αρχείο +@msg Script file permission could not be saved Δεν ήταν δυνατή η αποθήκευση της άδειας αρχείων του σεναρίου +@msg Script folder is not empty Ο φάκελος του σεναρίου δεν είναι κενός +@msg Script files cannot make aliases Τα αρχεία του σεναρίου δεν μπορούν να δημιουργήσουν ψευδώνυμα +@msg Script file hidden setting cannot be changed Η ρύθμιση απόκρυψης του αρχείου του σεναρίου δεν μπορεί να αλλάξει +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: ένα παράθυρο διαλόγου αρχείων δεν μπορεί να ανοίξει μέσα σε callback ενσωματωμένης συνάρτησης, getter, μετατροπής ή αρχείου που εκτελεί το $.evalFile· καλέστε το από τον κώδικα του ίδιου του σεναρίου +@msg the script wrote more file data than one run may write (32 MiB) το σενάριο έγραψε περισσότερα δεδομένα αρχείων από όσα επιτρέπεται να γράψει μία εκτέλεση (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop το `answer` για το παράθυρο διαλόγου αρχείων ενός σεναρίου πρέπει να είναι ένα από: once, always, deny, stop +@msg choose a file or folder first, or deny επιλέξτε πρώτα ένα αρχείο ή έναν φάκελο, ή απορρίψτε +@msg the script file permissions could not be saved: {e} δεν ήταν δυνατή η αποθήκευση των αδειών αρχείων των σεναρίων: {e} +@msg this script's file access can be allowed only once η πρόσβαση αυτού του σεναρίου σε αρχεία μπορεί να επιτραπεί μόνο μία φορά +@msg Only the person at the keyboard can allow a script's file access Μόνο το άτομο στο πληκτρολόγιο μπορεί να επιτρέψει την πρόσβαση ενός σεναρίου σε αρχεία +@msg A script is given at most 2,048 files: the files picked after them were left out Ένα σενάριο λαμβάνει το πολύ 2.048 αρχεία: τα αρχεία που επιλέχθηκαν μετά από αυτά παραλείφθηκαν @msg Copied the link info Οι πληροφορίες συνδέσμου αντιγράφηκαν @msg Corners edits the corners of a path Η εντολή Γωνίες επεξεργάζεται τις γωνίες μιας διαδρομής @msg Couldn't copy to the system clipboard: {e} Δεν ήταν δυνατή η αντιγραφή στο πρόχειρο συστήματος: {e} @@ -2684,6 +2763,7 @@ liquify-list-end {0}, {1} {0} και {1} @msg Saved {path} Αποθηκεύτηκε το {path} @msg Select text or click into text with the Type tool to insert glyphs Επιλέξτε κείμενο ή κάντε κλικ μέσα σε κείμενο με το εργαλείο κειμένου για εισαγωγή γλύφων @msg Shape Builder: no region under the pointer Δημιουργία σχημάτων: δεν υπάρχει περιοχή κάτω από τον δείκτη +@msg Shape Builder: select all paths you want to merge Δημιουργία σχημάτων: επιλέξτε όλες τις διαδρομές που θέλετε να συγχωνεύσετε @msg Shape Builder: select paths or compound paths Δημιουργία σχημάτων: επιλέξτε διαδρομές ή σύνθετες διαδρομές @msg Show All Hidden Attributes: nothing is hidden Εμφάνιση όλων των κρυφών χαρακτηριστικών: δεν υπάρχουν κρυφά χαρακτηριστικά @msg Split Into Grid: select paths large enough for the grid Διαίρεση σε πλέγμα: επιλέξτε αρκετά μεγάλες διαδρομές για το πλέγμα @@ -3110,6 +3190,7 @@ theme Appearance Εμφάνιση Load SVG into Clipboard Φόρτωση SVG στο πρόχειρο Load Text into Clipboard Φόρτωση κειμένου στο πρόχειρο Local Libraries Τοπικές βιβλιοθήκες + Locate Layer Εντοπισμός επιπέδου Locate Object Εντοπισμός αντικειμένου Locate Selected Objects Εντοπισμός επιλεγμένων αντικειμένων Lock (⌘2) Κλείδωμα (⌘2) @@ -3255,6 +3336,7 @@ theme Appearance Εμφάνιση Art Brush Options Επιλογές πινέλου σχεδίου Pattern Brush Options Επιλογές πινέλου μοτίβου Rotation relative to: Περιστροφή ως προς: + Hue Jitter: Διακύμανση απόχρωσης: Brush Scale Options Επιλογές κλιμάκωσης πινέλου Scale Proportionately Αναλογική κλιμάκωση Stretch to Fit Stroke Length Επέκταση για προσαρμογή στο μήκος περιγράμματος @@ -3399,7 +3481,7 @@ theme Appearance Εμφάνιση One Point Perspective Preset 3 Προεπιλογή προοπτικής ενός σημείου 3 One Point Perspective Preset 4 Προεπιλογή προοπτικής ενός σημείου 4 One Point Perspective Preset 5 Προεπιλογή προοπτικής ενός σημείου 5 - Opacity & Mask Define Knockout Shape Η αδιαφάνεια και η μάσκα καθορίζουν το σχήμα αποκοπής + Opacity & Mask Define Knockout Shape Η αδιαφάνεια και η μάσκα καθορίζουν το σχήμα διάτρησης Opacity Mask Info Πληροφορίες μάσκας αδιαφάνειας Opacity Mask Options Επιλογές μάσκας αδιαφάνειας Opacity: 50% Multiply Αδιαφάνεια: 50% Πολλαπλασιασμός @@ -3463,6 +3545,9 @@ theme Appearance Εμφάνιση Overprint Υπερεκτύπωση Overprint and Transparency Flattener Υπερεκτύπωση και ισοπέδωση διαφάνειας Overprint and Transparency Flattener Options Επιλογές υπερεκτύπωσης και ισοπέδωσης διαφάνειας + Custom… Προσαρμοσμένο… + Custom Transparency Flattener Options Προσαρμοσμένες επιλογές ισοπέδωσης διαφάνειας + EPS has no alpha transparency, and Overprints sets whether overprints are kept. Το EPS δεν έχει διαφάνεια άλφα και οι Υπερεκτυπώσεις ορίζουν αν διατηρούνται οι υπερεκτυπώσεις. Overprint Black… Υπερεκτύπωση μαύρου… Overprint Fill Υπερεκτύπωση γεμίσματος Overprint Preview Προεπισκόπηση υπερεκτύπωσης @@ -3477,7 +3562,7 @@ theme Appearance Εμφάνιση Page Σελίδα Page information Πληροφορίες σελίδας Page Isolated Blending Απομονωμένη ανάμειξη σελίδας - Page Knockout Group Ομάδα αποκοπής σελίδας + Page Knockout Group Ομάδα διάτρησης σελίδας Pages Σελίδες Paintbrush Πινέλο ζωγραφικής (Paintbrush Tool) Paragraph Style Στυλ παραγράφου @@ -3543,6 +3628,7 @@ theme Appearance Εμφάνιση Play Current Selection Αναπαραγωγή τρέχουσας επιλογής Save Actions… Αποθήκευση ενεργειών… Load Actions… Φόρτωση ενεργειών… + Replace Actions… Αντικατάσταση ενεργειών… Reset Actions Επαναφορά ενεργειών Replace the current actions with the default set? Να αντικατασταθούν οι τρέχουσες ενέργειες με το προεπιλεγμένο σύνολο; Append adds the default set after the current sets instead. Η Προσάρτηση προσθέτει αντί γι’ αυτό το προεπιλεγμένο σύνολο μετά τα τρέχοντα σύνολα. @@ -3555,6 +3641,10 @@ theme Appearance Εμφάνιση Polar Grid Tool Πολικό πλέγμα (Polar Grid Tool) Polygon Πολύγωνο Polygon Properties: Ιδιότητες πολυγώνου: + Line Properties: Ιδιότητες γραμμής: + Line Length: Μήκος γραμμής: + Line Angle: Γωνία γραμμής: + Constrain Pie Angle Διατήρηση γωνίας κυκλικού τομέα Power Saving (integrated) Εξοικονόμηση ενέργειας (ενσωματωμένη GPU) Portuguese Πορτογαλικά PostScript: PostScript: @@ -3674,6 +3764,9 @@ digits Malayalam Μαλαγιάλαμ Real World: Πραγματικός κόσμος: Real-time Drawing and Editing Σχεδίαση και επεξεργασία σε πραγματικό χρόνο Use Monitor Profile for Canvas Χρήση προφίλ οθόνης για τον καμβά + Refresh Monitor Profile Ανανέωση προφίλ οθόνης +@msg turn on Use Monitor Profile for Canvas first ενεργοποιήστε πρώτα τη «Χρήση προφίλ οθόνης για τον καμβά» +@msg this build doesn't read display profiles αυτή η έκδοση δεν διαβάζει προφίλ οθονών The canvas is drawn in sRGB. Ο καμβάς σχεδιάζεται σε sRGB. Canvas display profile: Προφίλ οθόνης καμβά: The system matches the window to the display's colors. Το σύστημα προσαρμόζει το παράθυρο στα χρώματα της οθόνης. @@ -3831,6 +3924,8 @@ digits Malayalam Μαλαγιάλαμ Replaces the saved preset of that name. Αντικαθιστά την αποθηκευμένη προεπιλογή με αυτό το όνομα. Require a password to open the document Απαίτηση κωδικού για το άνοιγμα εγγράφου Reset Bounding Box Επαναφορά πλαισίου οριοθέτησης + Rotate Bounding Box Περιστροφή πλαισίου οριοθέτησης + Rotate Bounding Box… Περιστροφή πλαισίου οριοθέτησης… Reset Envelope Mesh Επαναφορά πλέγματος περιβλήματος Reset Envelope Shape Επαναφορά σχήματος περιβλήματος Reset Essentials Επαναφορά χώρου εργασίας Essentials @@ -3885,6 +3980,7 @@ digits Malayalam Μαλαγιάλαμ The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Ο τροχός του ποντικιού με πατημένο το Cmd/Ctrl κυλά τον καμβά οριζόντια. Dragging sideways on a numeric field's label changes the field's value. Η μεταφορά προς τα πλάγια πάνω στην ετικέτα ενός αριθμητικού πεδίου αλλάζει την τιμή του πεδίου. A two-finger rotate gesture on a trackpad rotates the canvas view. Μια κίνηση περιστροφής με δύο δάχτυλα σε επιφάνεια αφής περιστρέφει την προβολή του καμβά. + When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Όταν μετακινείτε σημεία αγκύρωσης, κάθε καμπύλη με ένα μετακινημένο άκρο διατηρεί το σχήμα της σε σχέση με τα άκρα της. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Όσο κρατάτε πατημένη τη συντόμευση ενός εργαλείου, το εργαλείο είναι επιλεγμένο, και μετά επιλέγεται ξανά το προηγούμενο εργαλείο. Shows the bounding box while you move the selection or draw a shape. Εμφανίζει το πλαίσιο οριοθέτησης όσο μετακινείτε την επιλογή ή σχεδιάζετε ένα σχήμα. Create Trim Marks draws Japanese-style marks instead of Roman ones. Η Δημιουργία σημαδιών ξακρίσματος σχεδιάζει σημάδια ιαπωνικού τύπου αντί για ρωμαϊκά. @@ -3915,6 +4011,29 @@ digits Malayalam Μαλαγιάλαμ The unit for East Asian type measurements, which no field uses yet. Η μονάδα για τις μετρήσεις κειμένου Ανατολικής Ασίας, την οποία δεν χρησιμοποιεί ακόμη κανένα πεδίο. When on, a number typed without a unit into a field in picas is read in points. Όταν είναι ενεργό, ένας αριθμός που πληκτρολογείται χωρίς μονάδα σε πεδίο σε πίκες διαβάζεται σε σημεία. With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options. Με το Αναγνωριστικό XML, τα ονόματα αντικειμένων εμφανίζονται ως αναγνωριστικά XML στα Επίπεδα, στις Μεταβλητές και στις Επιλογές επιπέδου. + The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl. Το βήμα για το μέγεθος κειμένου και το διάστιχο: τα Cmd/Ctrl+Shift+. και Cmd/Ctrl+Shift+, αλλάζουν το μέγεθος κατά ένα βήμα, ή κατά πέντε μαζί με Alt. Σε οριζόντιο κείμενο, το Alt με το επάνω ή κάτω βέλος αλλάζει το διάστιχο κατά ένα βήμα, ή κατά πέντε με Cmd/Ctrl. + The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl. Το βήμα για την αραίωση και το kerning, σε χιλιοστά του em: σε οριζόντιο κείμενο, το Alt με το αριστερό ή δεξί βέλος αλλάζει το kerning στον δρομέα ή την αραίωση του επιλεγμένου κειμένου κατά ένα βήμα, ή κατά πέντε με Cmd/Ctrl. + The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. Το βήμα για τη μετατόπιση γραμμής βάσης: σε οριζόντιο κείμενο, τα Alt και Shift με το επάνω ή κάτω βέλος μετακινούν τη γραμμή βάσης κατά ένα βήμα, ή κατά πέντε με Cmd/Ctrl. + Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. Εμφανίζει τις επιλογές για ιαπωνικό και άλλο ανατολικοασιατικό κείμενο στα πάνελ Χαρακτήρας, Παράγραφος, OpenType και Γλύφοι, καθώς και την εντολή Σύνθετες γραμματοσειρές. + Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. Εμφανίζει τις επιλογές για αραβικό, εβραϊκό και ινδικό κείμενο στα πάνελ Χαρακτήρας και Παράγραφος, όπως η κατεύθυνση παραγράφου, οι κασίντες και τα ψηφία. + The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. Τα εργαλεία επιλογής επιλέγουν κείμενο μόνο στη γραμμή βάσης του, στο πλαίσιο του κειμένου περιοχής ή στη διαδρομή του, όχι οπουδήποτε μέσα στο πλαίσιό του. + Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. Τα μενού γραμματοσειρών δείχνουν κάθε γραμματοσειρά με το αγγλικό της όνομα· όταν είναι ανενεργό, μια γραμματοσειρά που έχει και όνομα στη δική της γλώσσα δείχνει αυτό το όνομα. + New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. Το νέο κείμενο περιοχής ξεκινά με ενεργό το Αυτόματο μέγεθος, οπότε ένα ορθογώνιο πλαίσιο οριζόντιου κειμένου μεγαλώνει ή μικραίνει σε ύψος για να χωρά το κείμενό του. + Font lists and the Type › Font menu show a sample of each font beside its name. Οι λίστες γραμματοσειρών και το μενού Γραμματοσειρά δείχνουν ένα δείγμα κάθε γραμματοσειράς δίπλα στο όνομά της. + Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on. Τα δείγματα γραμματοσειρών σχεδιάζονται με σκούρο κείμενο σε λευκό, όποια κι αν είναι η φωτεινότητα του περιβάλλοντος· ισχύει μόνο όσο είναι ενεργές οι προεπισκοπήσεις γραμματοσειρών στα μενού. + How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is. Πόσο ψηλή είναι κάθε γραμμή στις λίστες των πεδίων γραμματοσειράς, όπως αυτό του πάνελ Χαρακτήρας, και άρα πόσο μεγάλο είναι κάθε δείγμα. + How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first. Πόσες από τις τελευταίες γραμματοσειρές που χρησιμοποιήθηκαν, από 1 έως 15, δείχνουν οι Πρόσφατες γραμματοσειρές και οι λίστες γραμματοσειρών, με την πιο πρόσφατη πρώτη. + When you change the font or font style of text, characters the new font has no glyph for keep the font they had. Όταν αλλάζετε τη γραμματοσειρά ή το στυλ γραμματοσειράς ενός κειμένου, οι χαρακτήρες για τους οποίους η νέα γραμματοσειρά δεν έχει γλύφο κρατούν την προηγούμενη γραμματοσειρά τους. + A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export. Μια ροζ επισήμανση στον καμβά σημειώνει τους γλύφους που αντικαταστάθηκαν από λειτουργίες OpenType, όπως τα συμπλέγματα· δεν τυπώνεται ούτε εξάγεται. + With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from. Με το εργαλείο Κείμενο, η επιλογή ενός χαρακτήρα δείχνει δίπλα του στον καμβά μια σειρά με τους εναλλακτικούς γλύφους του για να διαλέξετε. + A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export. Μια ροζ επισήμανση στον καμβά σημειώνει κείμενο που σχεδιάζεται με γραμματοσειρά αντικατάστασης επειδή λείπει η γραμματοσειρά του· δεν τυπώνεται ούτε εξάγεται. + New type made with a Type tool starts with placeholder text, selected, so typing replaces it. Το νέο κείμενο που δημιουργείται με εργαλείο κειμένου ξεκινά με επιλεγμένο κείμενο κράτησης θέσης, το οποίο αντικαθίσταται από ό,τι πληκτρολογείτε. + Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list. Η πληκτρολόγηση ενός δείκτη λίστας, όπως 1. ή *, και μετά ενός κενού στην αρχή μιας παραγράφου κάνει την παράγραφο λίστα. + Fonts in this folder show in the font menus and can be used without being installed. Οι γραμματοσειρές σε αυτόν τον φάκελο εμφανίζονται στα μενού γραμματοσειρών και μπορούν να χρησιμοποιηθούν χωρίς εγκατάσταση. + Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows. Η εφαρμογή στυλ γραφικών σε κείμενο αφαιρεί το δικό τους γέμισμα ή περίγραμμα από τους χαρακτήρες όπου το στυλ έχει, ώστε να φαίνεται το χρώμα του στυλ. + Align and Distribute measure point type by the ink of its glyphs instead of its em box. Η Στοίχιση και η Κατανομή μετρούν το κείμενο σημείου με βάση το μελάνι των γλύφων του αντί για το τετράγωνο em του. + Align and Distribute measure area type by the ink of its glyphs instead of its frame. Η Στοίχιση και η Κατανομή μετρούν το κείμενο περιοχής με βάση το μελάνι των γλύφων του αντί για το πλαίσιό του. + The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box. Το πλαίσιο οριοθέτησης και το πάνελ Μετασχηματισμός μετρούν το κείμενο σημείου με βάση το μελάνι των γλύφων του αντί για το τετράγωνο em του. Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply. Προσκολλά τη σχεδίαση, τη μετακίνηση και την κλιμάκωση στις υποδιαιρέσεις του πλέγματος, ακόμη και όταν το πλέγμα είναι κρυφό· όσο είναι ενεργό, η Προσκόλληση σε εικονοστοιχείο δεν ισχύει. The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead. Το χρώμα των οδηγών που δεν είναι επιλεγμένοι· ένας πίνακας σχεδίασης με Ετικέτα οδηγών σχεδιάζει τους δικούς του οδηγούς στο χρώμα της ετικέτας. Draws guides as solid lines or as dots, including the guides already in the document. Σχεδιάζει τους οδηγούς ως συνεχείς γραμμές ή ως κουκκίδες, μαζί με τους οδηγούς που υπάρχουν ήδη στο έγγραφο. @@ -4059,6 +4178,9 @@ digits Malayalam Μαλαγιάλαμ Search commands, tools, panels and effects… Αναζήτηση εντολών, εργαλείων, πλαισίων και εφέ… No commands match Καμία εντολή δεν ταιριάζει {pos} of {total}: {name} {pos} από {total}: {name} + No menu item Χωρίς στοιχείο μενού + Toolbar Γραμμή εργαλείων + {toolbar}, in the {tool} group {toolbar}, στην ομάδα {tool} @plural {n} result|{n} results {n} αποτέλεσμα|{n} αποτελέσματα @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} από {n} αποτέλεσμα. Συνεχίστε να πληκτρολογείτε για να τα περιορίσετε.|{shown} από {n} αποτελέσματα. Συνεχίστε να πληκτρολογείτε για να τα περιορίσετε. Recent Commands Πρόσφατες εντολές @@ -4127,6 +4249,7 @@ digits Malayalam Μαλαγιάλαμ Set Slice Rectangle Ορισμός ορθογωνίου τομής Set Tab Stops Ορισμός στηλοθετών Set Text Ορισμός κειμένου + Set the current fill or stroke to the selected color Ορισμός επιλεγμένου χρώματος ως τρέχοντος γεμίσματος ή περιγράμματος Set the selected color to the current color Ορισμός επιλεγμένου χρώματος ως τρέχοντος Set Zoom Ορισμός ζουμ Setup… Ρύθμιση… @@ -4229,7 +4352,7 @@ digits Malayalam Μαλαγιάλαμ Show Vivid/Muted Εμφάνιση έντονων/απαλών Show Warm/Cool Εμφάνιση θερμών/ψυχρών Show {kind} Brushes Εμφάνιση πινέλων {kind} - Show/hide plate (Alt-click: only this plate) Εμφάνιση/απόκρυψη πλάκας (Alt-κλικ: μόνο αυτή η πλάκα) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Εμφάνιση/απόκρυψη πλάκας (Alt-κλικ: μόνο αυτή η πλάκα· ξανά Alt-κλικ: όλες οι πλάκες) Shown with the optimised preview. Εμφανίζεται με τη βελτιστοποιημένη προεπισκόπηση. Side 1: Πλευρά 1: Side 2: Πλευρά 2: @@ -4331,6 +4454,11 @@ digits Malayalam Μαλαγιάλαμ Opacity Masks Μάσκες αδιαφάνειας Objects with Effects Αντικείμενα με εφέ Path Length Μήκος διαδρομής + Grid Size Μέγεθος πλέγματος + Grid Colors Χρώματα πλέγματος + Flattener Preset Προεπιλογή ισοπέδωσης + X X + Y Y Spot Colors Πλακάτα χρώματα Spot Colors… Πλακάτα χρώματα… Stacked Bar Graph Tool Στοιβαγμένο ραβδόγραμμα (Stacked Bar Graph Tool) @@ -4460,7 +4588,7 @@ digits Malayalam Μαλαγιάλαμ Composite Fonts Σύνθετες γραμματοσειρές Export Composite Fonts Εξαγωγή σύνθετων γραμματοσειρών Import Composite Fonts Εισαγωγή σύνθετων γραμματοσειρών -@msg each font must be {name, parts} κάθε γραμματοσειρά πρέπει να είναι {name, parts} +@msg each font must be {{name, parts}} κάθε γραμματοσειρά πρέπει να είναι {{name, parts}} @msg unknown key `{k}`; a font takes name and parts άγνωστο κλειδί `{k}`· μια γραμματοσειρά δέχεται name και parts @msg each font needs a name κάθε γραμματοσειρά χρειάζεται όνομα @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) το `{raw}` δεν μπορεί να είναι όνομα σύνθετης γραμματοσειράς (1 έως {COMPOSITE_NAME_MAX} χαρακτήρες, χωρίς χαρακτήρες ελέγχου) @@ -4473,7 +4601,10 @@ digits Malayalam Μαλαγιάλαμ @msg two composite fonts are named `{_1}` δύο σύνθετες γραμματοσειρές ονομάζονται `{_1}` @msg `{_1}` is the name of an installed font το `{_1}` είναι όνομα εγκατεστημένης γραμματοσειράς @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: το {_2} χρησιμοποιεί την `{font}`, που είναι σύνθετη γραμματοσειρά -@msg give fonts: [{name, parts}…] δώστε fonts: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] δώστε fonts: [{{name, parts}}…] +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} το `scope` πρέπει να είναι "document", {{artboards: [index, …]}} ή {{layers: [id, …]}} +@msg numbers out of order in {{}} quantifier αριθμοί εκτός σειράς στον ποσοδείκτη {{}} +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) το χρώμα δεν είναι ντεγκραντέ ελεύθερης μορφής (εφαρμόστε ένα με paint.editGradient {{kind: "freeform"}}) @msg path is empty το path είναι κενό @msg fonts must be a list of composite fonts το fonts πρέπει να είναι λίστα σύνθετων γραμματοσειρών @msg names must be strings τα names πρέπει να είναι συμβολοσειρές @@ -4672,6 +4803,8 @@ digits Malayalam Μαλαγιάλαμ V Spacing: Κατακόρυφη απόσταση: V: Κατακόρυφα: Variable Width Profile Προφίλ μεταβλητού πλάτους + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Το πινέλο του περιγράμματος διατηρεί το δικό του μέγεθος, οπότε ένα προφίλ πλάτους δεν το αλλάζει. Αφαιρέστε το πινέλο για να χρησιμοποιήσετε προφίλ. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Το πινέλο του περιγράμματος διατηρεί το δικό του μέγεθος, οπότε ένα προφίλ πλάτους δεν το αλλάζει. Αφαιρέστε το πινέλο για να χρησιμοποιήσετε προφίλ. New Variable Νέα μεταβλητή Delete Variable Διαγραφή μεταβλητής Lock Variables Κλείδωμα μεταβλητών @@ -4728,7 +4861,7 @@ digits Malayalam Μαλαγιάλαμ Vertical Scale % Κατακόρυφη κλίμακα % Vertical Type on a Path Tool Κατακόρυφο κείμενο σε διαδρομή (Vertical Type on a Path Tool) Very High Πολύ υψηλή - View Artboard Only Προβολή μόνο πίνακα σχεδίασης + View Artboard Contents Only Προβολή μόνο του περιεχομένου του πίνακα σχεδίασης View Opacity Mask Προβολή μάσκας αδιαφάνειας View PDF after saving Προβολή PDF μετά την αποθήκευση View {n} Προβολή {n} @@ -4811,6 +4944,7 @@ digits Malayalam Μαλαγιάλαμ {people} contributors · {commits} commits {people} συνεισφέροντες · {commits} commits Joins Συνδέσεις Axis Άξονας + Axis Angle Γωνία άξονα Drag to move Σύρετε για μετακίνηση Drag to float as a toolbar Σύρετε για αποδέσμευση ως γραμμή εργαλείων Put back in the toolbar Επαναφορά στη γραμμή εργαλείων @@ -4886,6 +5020,7 @@ digits Malayalam Μαλαγιάλαμ @msg bad trailer μη έγκυρο τελικό τμήμα @msg balance must be between 0 and 100 το balance πρέπει να είναι μεταξύ 0 και 100 @msg batch step {_1} (`{id}`) failed: {e} απέτυχε το βήμα {_1} της μαζικής επεξεργασίας (`{id}`): {e} +@msg action step {_1} (`{id}`) failed: {reason} απέτυχε το βήμα {_1} της ενέργειας (`{id}`): {reason} @msg brightness must be dark|mediumDark|mediumLight|light το brightness πρέπει να είναι dark|mediumDark|mediumLight|light @msg can't encode the document: {0} δεν είναι δυνατή η κωδικοποίηση εγγράφου: {0} @msg can't parse shortcut `{c}` δεν είναι δυνατή η ανάλυση της συντόμευσης `{c}` @@ -4905,6 +5040,7 @@ digits Malayalam Μαλαγιάλαμ @msg choose a folder to export to επιλέξτε φάκελο εξαγωγής @msg choose a location for the package επιλέξτε τοποθεσία συσκευασίας @msg clipboard is empty το πρόχειρο είναι κενό +@msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: τουλάχιστον ένα χρώμα πρέπει να παραμείνει στον πίνακα χρωμάτων @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: το `{h}` δεν είναι έγκυρο χρώμα, όπως το "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: επιτρέπονται το πολύ {MAX_TABLE} χρώματα @msg command `{0}` is not available right now: {1} η εντολή `{0}` δεν είναι διαθέσιμη αυτήν τη στιγμή: {1} @@ -4972,9 +5108,15 @@ digits Malayalam Μαλαγιάλαμ @msg no PNG encoder δεν υπάρχει κωδικοποιητής PNG @msg no active document δεν υπάρχει ενεργό έγγραφο @msg no active perspective plane δεν υπάρχει ενεργό επίπεδο προοπτικής +@msg the perspective grid is hidden το πλέγμα προοπτικής είναι κρυφό +@msg Automatic Plane Positioning is off: turn on anchorPoint or gridlineIntersection (perspective.widget.options) Η αυτόματη τοποθέτηση επιπέδου είναι απενεργοποιημένη: ενεργοποιήστε το anchorPoint ή το gridlineIntersection (perspective.widget.options) +@msg anchorPoint must be true or false το anchorPoint πρέπει να είναι true ή false +@msg gridlineIntersection must be true or false το gridlineIntersection πρέπει να είναι true ή false +@msg tolerance must be 0 or more το tolerance πρέπει να είναι 0 ή μεγαλύτερο +@msg give `at` or `clear`, not both δώστε `at` ή `clear`, όχι και τα δύο @msg no anchor points selected δεν έχουν επιλεγεί σημεία αγκύρωσης -@msg `points` must be three [x, y] pairs of numbers το `points` πρέπει να είναι τρία ζεύγη αριθμών [x, y] -@msg direct-select three anchor points, or give `points` επιλέξτε άμεσα τρία σημεία αγκύρωσης ή δώστε `points` +@msg `points` must be two or three [x, y] pairs of numbers το `points` πρέπει να είναι δύο ή τρία ζεύγη αριθμών [x, y] +@msg direct-select two or three anchor points, or give `points` επιλέξτε άμεσα δύο ή τρία σημεία αγκύρωσης ή δώστε `points` @msg no circle passes through these points: two are the same or all three lie on one line κανένας κύκλος δεν περνά από αυτά τα σημεία: δύο είναι ίδια ή και τα τρία βρίσκονται σε μία ευθεία @msg no app to open files here δεν υπάρχει εφαρμογή για άνοιγμα αρχείων εδώ @msg no artboard δεν υπάρχει πίνακας σχεδίασης @@ -5076,12 +5218,17 @@ digits Malayalam Μαλαγιάλαμ @msg no such user library δεν υπάρχει τέτοια βιβλιοθήκη χρήστη @msg no such view δεν υπάρχει τέτοια προβολή @msg no such width point δεν υπάρχει τέτοιο σημείο πλάτους +@msg `single` must be `incoming` or `outgoing` το `single` πρέπει να είναι `incoming` ή `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point τα `index` και `outIndex` πρέπει να είναι τα δύο μισά ενός ασυνεχούς σημείου πλάτους +@msg a discontinuous width point keeps its place ένα ασυνεχές σημείο πλάτους διατηρεί τη θέση του @msg no swatch `{name}` δεν υπάρχει δείγμα χρώματος `{name}` @msg no swatch library `{l}` (see swatch.library.list) δεν υπάρχει βιβλιοθήκη δειγμάτων `{l}` (δείτε swatch.library.list) @msg no symbol instances selected δεν έχουν επιλεγεί στιγμιότυπα συμβόλων @msg no target object has an opacity mask: select one or give `id` κανένα αντικείμενο-στόχος δεν έχει μάσκα αδιαφάνειας: επιλέξτε ένα ή δώστε `id` @msg no threaded text selected δεν έχει επιλεγεί συνδεδεμένο κείμενο @msg no user library folder here δεν υπάρχει φάκελος βιβλιοθήκης χρήστη εδώ +@msg `{file}` has no swatches of its own το `{file}` δεν έχει δικά του δείγματα χρωμάτων +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold το `{_1}` έχει δείγματα μοτίβου, που ένα αρχείο .vcswatches δεν μπορεί να περιέχει @msg no user workspace `{from}` δεν υπάρχει χώρος εργασίας χρήστη `{from}` @msg node {_1} is not text ο κόμβος {_1} δεν είναι κείμενο @msg node {_1} is on a locked artboard ο κόμβος {_1} βρίσκεται σε κλειδωμένο πίνακα σχεδίασης @@ -5330,6 +5477,13 @@ digits Malayalam Μαλαγιάλαμ @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} περισσότερα από {MAX_CSV_ROWS} σύνολα δεδομένων: η Εισαγωγή συνόλων δεδομένων διαβάζει έως {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} περισσότερες από {MAX_CSV_COLS} μεταβλητές: η Εισαγωγή συνόλων δεδομένων διαβάζει έως {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} οι μεταβλητές που δεν είναι κειμένου παραλείφθηκαν: {kinds} +variable-kind Visibility Ορατότητα +variable-kind Linked File Συνδεδεμένο αρχείο +variable-kind Graph Data Δεδομένα γραφήματος +variable-kind Unknown Άγνωστο +variable-list-two {0}, {1} {0} και {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} και {1} @msg a new document won't read these variables back with their kind: {names} ένα νέο έγγραφο δεν θα διαβάσει ξανά αυτές τις μεταβλητές με το είδος τους: {names} @msg a new document refuses this file because of these variables: {names} ένα νέο έγγραφο απορρίπτει αυτό το αρχείο λόγω αυτών των μεταβλητών: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them η κεφαλίδα `{header}` για το `{name}` θα διαβαζόταν ως η μεταβλητή `{other}`: μετονομάστε μία από τις δύο @@ -5355,6 +5509,8 @@ digits Malayalam Μαλαγιάλαμ @msg {label}: lost track of a shape's style {label}: χάθηκε η παρακολούθηση του στυλ σχήματος @msg {label}: select paths {label}: επιλέξτε διαδρομές @msg {label}: select paths, compound paths, groups or text {label}: επιλέξτε διαδρομές, σύνθετες διαδρομές, ομάδες ή κείμενο +@msg a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first μια γραμμή ή άλλη ανοιχτή διαδρομή που δεν περικλείει εμβαδόν δεν αλλάζει το σχήμα του αποτελέσματος· για να τη συμπεριλάβετε, εφαρμόστε της πρώτα Αντικείμενο › Διαδρομή › Μετατροπή περιγράμματος σε διαδρομή +@msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first το {label} παρήγαγε κενό αποτέλεσμα: μια γραμμή ή άλλη ανοιχτή διαδρομή δεν περικλείει εμβαδόν· για να τη συμπεριλάβετε, εφαρμόστε της πρώτα Αντικείμενο › Διαδρομή › Μετατροπή περιγράμματος σε διαδρομή @msg {label}… {label}… @msg {name}: CRC mismatch {name}: ασυμφωνία CRC @msg {name}: no local header {name}: δεν υπάρχει τοπική κεφαλίδα @@ -5381,6 +5537,9 @@ digits Malayalam Μαλαγιάλαμ @msgplural Discarded {n} recovered document|Discarded {n} recovered documents Απορρίφθηκε {n} ανακτημένο έγγραφο|Απορρίφθηκαν {n} ανακτημένα έγγραφα @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them Επαναφέρθηκε {n} ανακτημένο έγγραφο: αποθηκεύστε το για να διατηρηθεί|Επαναφέρθηκαν {n} ανακτημένα έγγραφα: αποθηκεύστε τα για να διατηρηθούν @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} Άνοιξε με {n} σημείωση: {first}|Άνοιξε με {n} σημειώσεις: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Αντιγράφηκε με {n} σημείωση: {first}|Αντιγράφηκε με {n} σημειώσεις: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Αποκόπηκε με {n} σημείωση: {first}|Αποκόπηκε με {n} σημειώσεις: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Η εικόνα ανιχνεύτηκε με {n} σημείωση: {first}|Η εικόνα ανιχνεύτηκε με {n} σημειώσεις: {first} @msgplural {notice}. Opened with {n} note: {first}|{notice}. Opened with {n} notes: {first} {notice}. Άνοιξε με {n} σημείωση: {first}|{notice}. Άνοιξε με {n} σημειώσεις: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} Αποθηκεύτηκε το {path} με {n} σημείωση: {first}|Αποθηκεύτηκε το {path} με {n} σημειώσεις: {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first Ενσωματώθηκε {n} εικόνα· λείπουν {missing}: επανασυνδέστε τις πρώτα|Ενσωματώθηκαν {n} εικόνες· λείπουν {missing}: επανασυνδέστε τις πρώτα @@ -5407,6 +5566,8 @@ digits Malayalam Μαλαγιάλαμ @msg All colors are within the CMYK gamut Όλα τα χρώματα βρίσκονται εντός της χρωματικής γκάμας CMYK @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} χρώμα βρίσκεται εκτός της χρωματικής γκάμας CMYK|{n} χρώματα βρίσκονται εκτός της χρωματικής γκάμας CMYK @msg Unembedded to {_1} Καταργήθηκε η ενσωμάτωση στο {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} Καταργήθηκε η ενσωμάτωση {n} εικόνας στο {folder}|Καταργήθηκε η ενσωμάτωση {n} εικόνων στο {folder} +@msg every numbered name for {name} is taken in that folder όλα τα αριθμημένα ονόματα για το {name} χρησιμοποιούνται ήδη σε αυτόν τον φάκελο @msg Reset {_1} Επαναφορά {_1} @msg Sent to {_1} Στάλθηκε στο {_1} @msg {_1} files {_1} αρχεία @@ -5422,6 +5583,8 @@ digits Malayalam Μαλαγιάλαμ @msg Reload the page to go on (changes not saved yet may be lost). Ανανεώστε τη σελίδα για να συνεχίσετε (οι μη αποθηκευμένες αλλαγές ενδέχεται να χαθούν). @msg tool (a tool id) is required απαιτείται tool (αναγνωριστικό εργαλείου) @msg {tool} isn't in a toolbar group of several tools το {tool} δεν ανήκει σε ομάδα πολλών εργαλείων της γραμμής εργαλείων +@msg Presentation Mode hides the toolbars: change the screen mode to show them η Λειτουργία παρουσίασης κρύβει τις γραμμές εργαλείων: αλλάξτε τη λειτουργία οθόνης για να εμφανιστούν +@msg Tab has hidden the toolbars: press Tab to show them το Tab έκρυψε τις γραμμές εργαλείων: πατήστε Tab για να εμφανιστούν @msg onto must name a panel floating in another group το onto πρέπει να ορίζει πίνακα που αιωρείται σε άλλη ομάδα @msg below and above must name a panel floating in another group τα below και above πρέπει να ορίζουν πίνακα που αιωρείται σε άλλη ομάδα @msg give only one of onto, below and above δώστε μόνο ένα από τα onto, below και above @@ -5552,6 +5715,9 @@ digits Malayalam Μαλαγιάλαμ @msg automation path rejected: outside the read root {root}: {path} απορρίφθηκε η διαδρομή αυτοματισμού: εκτός ρίζας ανάγνωσης {root}: {path} @msg automation path rejected: outside the read roots {roots}: {path} απορρίφθηκε η διαδρομή αυτοματισμού: εκτός των ριζών ανάγνωσης {roots}: {path} @msg a linked JavaScript file is outside the read roots ένα συνδεδεμένο αρχείο JavaScript είναι εκτός των ριζών ανάγνωσης +@msg a linked image file is outside the read roots ένα συνδεδεμένο αρχείο εικόνας είναι εκτός των ριζών ανάγνωσης +@msg a linked file's export folder is outside the read roots ο φάκελος εξαγωγής ενός συνδεδεμένου αρχείου είναι εκτός των ριζών ανάγνωσης +@msg a linked file's editing data can't be read to check it against the read roots τα δεδομένα επεξεργασίας ενός συνδεδεμένου αρχείου δεν μπορούν να διαβαστούν για έλεγχο με τις ρίζες ανάγνωσης @msg the library's file is outside the read roots το αρχείο της βιβλιοθήκης είναι εκτός των ριζών ανάγνωσης @msg {file} names more than one linked JavaScript file το {file} αντιστοιχεί σε περισσότερα από ένα συνδεδεμένα αρχεία JavaScript @msg automation path rejected: outside the write root {root}: {path} απορρίφθηκε η διαδρομή αυτοματισμού: εκτός ρίζας εγγραφής {root}: {path} @@ -5665,6 +5831,7 @@ digits Malayalam Μαλαγιάλαμ @msg missing panel layout λείπει η διάταξη πινάκων @msg unsupported native docking operation μη υποστηριζόμενη εγγενής λειτουργία σύνδεσης πινάκων Linux Display Server Διακομιστής οθόνης Linux + Low-Latency Drawing Σχεδίαση χαμηλής καθυστέρησης Ruler Origin Αρχή χαράκων Reset Ruler Origin Επαναφορά αρχής χαράκων @msg the compressed file unpacks to more than VectorCraft reads ({_1} MB of document, {_2} MB per image) το αποσυμπιεσμένο αρχείο υπερβαίνει τα όρια ανάγνωσης του VectorCraft ({_1} MB ανά έγγραφο, {_2} MB ανά εικόνα) @@ -5679,6 +5846,7 @@ digits Malayalam Μαλαγιάλαμ Both sides Και οι δύο πλευρές Cove Κοίλη ακμή Front Μπροστά + Side Πλάι Isometric Bottom Ισομετρική κάτω όψη Isometric Left Ισομετρική αριστερή όψη Isometric Right Ισομετρική δεξιά όψη @@ -5765,7 +5933,7 @@ digits Malayalam Μαλαγιάλαμ @msg each of `{GRAPHICS}` must be an object κάθε στοιχείο του `{GRAPHICS}` πρέπει να είναι αντικείμενο @msg `{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}` οι καταχωρίσεις του `{GRAPHICS}` δέχονται symbol, face, x, y, scale και rotation, όχι `{k}` @msg each of `{GRAPHICS}` needs `symbol`, the name of a symbol κάθε στοιχείο του `{GRAPHICS}` χρειάζεται `symbol`, το όνομα ενός συμβόλου -@msg `{GRAPHICS}` face must be front or back το face του `{GRAPHICS}` πρέπει να είναι front ή back +@msg `{GRAPHICS}` face must be front, back or side το face του `{GRAPHICS}` πρέπει να είναι front, back ή side @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} το {key} του `{GRAPHICS}` πρέπει να είναι αριθμός από {lo} έως {hi} @msg `{GRAPHICS}` must be an array το `{GRAPHICS}` πρέπει να είναι πίνακας @msg Graphics map onto the Plane, Extrude and Revolve object types Τα γραφικά αντιστοιχίζονται στους τύπους αντικειμένου Επίπεδο, Εξώθηση και Περιστροφή γύρω από άξονα @@ -6089,6 +6257,7 @@ digits Malayalam Μαλαγιάλαμ [VectorCraft Default] [Προεπιλογή VectorCraft] of από x Height Ύψος x + Em Box Height Ύψος τετραγώνου em ▾ Default Actions ▾ Προεπιλεγμένες ενέργειες ⚠ {chord} was already used by {names} — it has been removed there. Προσοχή: το {chord} χρησιμοποιούνταν ήδη από {names} — αφαιρέθηκε από εκεί. @msg give corners of the path: anchors between two straight sides ορίστε τις γωνίες της διαδρομής: σημεία αγκύρωσης μεταξύ δύο ευθύγραμμων πλευρών @@ -6458,6 +6627,8 @@ effect Points Σημεία Reset Horizontal Scale Επαναφορά οριζόντιας κλίμακας Reset Tracking and Kerning Επαναφορά απόστασης χαρακτήρων και διαγραμμάτωσης Highlight Font Name Επισήμανση ονόματος γραμματοσειράς + Highlight Font Size Επισήμανση μεγέθους γραμματοσειράς + Other… Άλλο… Highlight Kerning Επισήμανση διαγραμμάτωσης Highlight Tracking Επισήμανση απόστασης χαρακτήρων Sample Color from Screen Δειγματοληψία χρώματος από την οθόνη @@ -6499,6 +6670,8 @@ effect Points Σημεία @msg Unknown dimension option {k} Άγνωστη επιλογή διάστασης {k} @msg Unknown dimension orientation Άγνωστος προσανατολισμός διάστασης @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe το `mode` πρέπει να είναι grayscale, rgb, hsb, cmyk ή websafe +@msg `view` must be wheel or box το `view` πρέπει να είναι wheel ή box +@msg `channel` must be hue, saturation, brightness, red, green or blue το `channel` πρέπει να είναι hue, saturation, brightness, red, green ή blue @msg `{key}` must be an array of these names: {_1} το `{key}` πρέπει να είναι πίνακας με αυτά τα ονόματα: {_1} @msg choose a destination folder επιλέξτε φάκελο προορισμού @msg choose a source folder επιλέξτε φάκελο προέλευσης @@ -7362,6 +7535,12 @@ anchor Points: Σημεία: @msg `mode` must be "free", "keepAngles" or "symmetric" Το `mode` πρέπει να είναι "free", "keepAngles" ή "symmetric" @msg `{key}` must be [x, y] Το `{key}` πρέπει να είναι [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Μετατροπέας μονάδων + Unit Converter Panel Πλαίσιο Μετατροπέας μονάδων + Copy with Units Αντιγραφή με μονάδες + From Selection Από την επιλογή + # Color Effects add-on: Select by Color Kind. Select by Color Kind Επιλογή κατά είδος χρώματος Objects with Spot Colors Αντικείμενα με χρώματα spot @@ -7587,6 +7766,14 @@ breakText Glyphs Γλύφοι Remove Gaps Αφαίρεση κενών @msg that makes too many pieces (at most 100000): make the dashes longer αυτό δίνει πάρα πολλά κομμάτια (το πολύ 100000): κάντε τις παύλες μεγαλύτερες @msg select paths, or segments, to divide επιλέξτε διαδρομές ή τμήματα για διαίρεση +# Path Precision Tools add-on: Smooth Bridge. + Smooth Bridge… Ομαλή γέφυρα… + Smooth Bridge Ομαλή γέφυρα + Keep Originals Διατήρηση πρωτοτύπων +@msg select two circles to bridge επιλέξτε δύο κύκλους για γεφύρωση +@msg one circle is inside the other ο ένας κύκλος βρίσκεται μέσα στον άλλο +@msg the circles are too far apart for this radius: raise the radius οι κύκλοι απέχουν πολύ μεταξύ τους για αυτή την ακτίνα: αυξήστε την ακτίνα +@msg the circles are too far apart for this radius οι κύκλοι απέχουν πολύ μεταξύ τους για αυτή την ακτίνα # Path Precision Tools add-on: Common Tangents. Common Tangents… Κοινές εφαπτόμενες… Common Tangents Κοινές εφαπτόμενες @@ -8099,4 +8286,15 @@ breakText Glyphs Γλύφοι @msg A panel is not joined to the rest by a crease. Ένα πάνελ δεν συνδέεται με τα υπόλοιπα με καμία γραμμή πτύχωσης. @msg A fold line is on a non-printing layer. Μια γραμμή δίπλωσης βρίσκεται σε επίπεδο που δεν εκτυπώνεται. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Πάνελ: {panels}, μεντεσέδες: {hinges}, σφάλματα: {errors}, προειδοποιήσεις: {warnings} + Fold Preview Προεπισκόπηση δίπλωσης + Fold Δίπλωση + Show Fold Lines Εμφάνιση γραμμών δίπλωσης + Three-Quarter Τρία τέταρτα + Open a document to preview its folded shape. Ανοίξτε ένα έγγραφο για να δείτε σε προεπισκόπηση το διπλωμένο σχήμα του. +@msg Check the fold lines first. Ελέγξτε πρώτα τις γραμμές δίπλωσης. +@msg Panels: {panels}, hinges: {hinges} Πάνελ: {panels}, μεντεσέδες: {hinges} +@msg Other blanks not shown: {count} Άλλα αναπτύγματα δεν εμφανίζονται: {count} +@msg A joint does not close by {gap} pt. Μια ένωση δεν κλείνει κατά {gap} pt. +@msg Two panels pass through each other. Δύο πάνελ διαπερνούν το ένα το άλλο. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" το composer πρέπει να είναι "singleLine", "everyLine", "standardSingleLine" ή "standardEveryLine" +@msg text.{key} `{v}`: use "{_1}" or "{_2}" text.{key} `{v}`: χρησιμοποιήστε "{_1}" ή "{_2}" diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index a456910a16..bee8f3bfe7 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -11,7 +11,7 @@ # Coverage: the whole interface — every menu string and every `tl!` literal (`complete_menus`, # `untranslated_report` lists gaps). Left in English on purpose (`MENU_KEEP_AS_IS` in the tests): the product name, language # names, OpenType, the built-in workspace names and the bracketed perspective grid preset names. -# Photoshop-style raster effects (Effect menu, their dialogs). +# Raster effects (Effect menu, their dialogs). Glowing Edges… Bordes resplandecientes… Glowing Edges Bordes resplandecientes Edge Width Ancho del borde @@ -119,6 +119,7 @@ Add Anchor Point Agregar punto de ancla Add Anchor Point Tool Herramienta Agregar punto de ancla Add Anchor Points Agregar puntos de ancla + Add Around Agregar alrededor del objeto Add Effect Agregar efecto Add Freeform Line Agregar línea libre Add Freeform Point Agregar punto libre @@ -140,8 +141,12 @@ Add to Swatches Agregar a muestras Add Used Colors Agregar colores usados Additional Plug-ins Folder Carpeta de plugins adicionales + Plug-in Instruction Budget Presupuesto de instrucciones de plugins Additional Fonts Folder Carpeta de fuentes adicionales Adjust Adjoining Width Points Ajustar puntos de anchura contiguos + Incoming Entrante + Outgoing Saliente + Single Width Only Solo una anchura Adjust Color Balance… Ajustar equilibrio de color… Adjust Colors Ajustar colores Adjust Options: Opciones de ajuste: @@ -196,6 +201,7 @@ Angle: Ángulo: Angles Ángulos Animated Zoom Zoom animado + Anti Alias Suavizado Anti-alias Suavizado Anti-Alias Suavizado Anti-alias Rasters Suavizar imágenes ráster @@ -361,6 +367,12 @@ font-technology Variable Variables Brush Definition Definición del pincel Brush Libraries Bibliotecas de pinceles Brush Options… Opciones de pincel… + Options of Selected Object… Opciones del objeto seleccionado… + Options of Selected Object Opciones del objeto seleccionado +@msg no path painted with a brush is selected no hay ningún trazado pintado con un pincel seleccionado +@msg the selected paths are painted with brushes of different types los trazados seleccionados están pintados con pinceles de tipos distintos +@msg give `params` or `reset`, not both indique `params` o `reset`, no ambos +@msg a bristle brush has no options of its own on a path un pincel de cerdas no tiene opciones propias en un trazado Brush Strokes Trazos de pincel Brushes Pinceles Built-in Libraries Bibliotecas integradas @@ -417,6 +429,12 @@ font-technology Variable Variables Character Alignment Alineación de caracteres Character / Paragraph Carácter / Párrafo Character Rotation Rotación de caracteres + Chinese Big 5 Chino Big 5 + Cyrillic Cirílico + Greek Griego + Turkish Turco + Baltic Báltico + Central European Centroeuropeo Character Set: Juego de caracteres: Character Style Estilo de carácter Character Style Options Opciones de estilo de carácter @@ -479,6 +497,8 @@ font-technology Variable Variables Choose a folder Elige una carpeta Choose… Elegir… Circle Círculo + Circle Tool Herramienta Círculo + Circle too large Círculo demasiado grande Classic Defaults Valores predeterminados clásicos Clean Up… Limpiar… Clear Borrar @@ -554,6 +574,7 @@ font-technology Variable Variables Color Mixer (Shift-click the chip) Mezclador de colores (Shift+clic en la muestra) Color Mode Modo de color Color Mode: Modo de color: + Color Model Modelo de color Color Model: Modelo de color: Color Models Modelos de color Color Picker Selector de color @@ -574,12 +595,18 @@ font-technology Variable Variables Saturation and brightness Saturación y brillo Color field Campo de color {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Vista de rueda + Box View Vista de cuadro + Box Channel Canal del cuadro + Color box Cuadro de color + Color Wheel Options Opciones de la rueda de color Color Type: Tipo de color: Color: Color: Colorize Colorear Colors Colores Colors: Colores: Column Graph Tool Herramienta Gráfico de columnas + Columns Columnas Columns: Columnas: Column… Columna… Combine Slices Combinar sectores @@ -790,6 +817,8 @@ font-technology Variable Variables Delete Artboard Eliminar mesa de trabajo Delete Artboards Eliminar mesas de trabajo Delete Brush Eliminar pincel + Delete Color Eliminar color + Restore Generated Table Restaurar tabla generada Delete Character Style Eliminar estilo de carácter Delete Empty Artboards Eliminar mesas de trabajo vacías Delete Freeform Point Eliminar punto libre @@ -858,6 +887,7 @@ font-technology Variable Variables Direct Selection Tool Herramienta Selección directa Direction Handles Manejadores de dirección Disable Auto Add/Delete Desactivar agregar/eliminar automático + Interpolate Control Points When Moving Anchors Interpolar manejadores de dirección al mover puntos de ancla Disable Opacity Mask Desactivar máscara de opacidad Discard Descartar Discard Empty Type Descartar texto vacío @@ -1074,6 +1104,7 @@ font-technology Variable Variables Enable text access for screen readers Permitir el acceso al texto para lectores de pantalla Enable Touch Gestures Activar gestos táctiles Switch Selection and Drawing Modes Cambiar entre modos de selección y dibujo + Select Last Selection Tool Elegir la última herramienta de selección Enable Touch Workspace Activar espacio de trabajo táctil Encoding Codificación Encoding: Codificación: @@ -1256,6 +1287,8 @@ font-technology Variable Variables Files Archivos Files of a PDF standard can't be password-protected. Los archivos de un estándar PDF no se pueden proteger con contraseña. Files of this standard tag their colours with ICC profiles. Los archivos de este estándar etiquetan sus colores con perfiles ICC. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Los archivos de este estándar etiquetan sus colores con perfiles ICC, excepto los colores CMYK en el perfil de propósito de salida, que se escriben como DeviceCMYK. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. Con «No incluir perfiles» y un propósito de salida CMYK, cada color CMYK se escribe como DeviceCMYK, salvo que se convierta a un destino CMYK de otro perfil. Fill Relleno Fill & Stroke Relleno y trazo Fill (X), double-click for the Color Picker Relleno (X), doble clic para el selector de color @@ -1305,6 +1338,8 @@ font-technology Variable Variables Reset Tracking and Kerning Restablecer espaciado e interletraje Reset Horizontal Scale Restablecer escala horizontal Highlight Font Name Resaltar nombre de fuente + Highlight Font Size Resaltar tamaño de fuente + Other… Otro… Highlight Kerning Resaltar interletraje Highlight Tracking Resaltar espaciado Spacing Espaciado @@ -2030,6 +2065,7 @@ font-technology Variable Variables Load SVG into Clipboard Cargar SVG en el portapapeles Load Text into Clipboard Cargar texto en el portapapeles Local Libraries Bibliotecas locales + Locate Layer Localizar capa Locate Object Localizar objeto Locate Selected Objects Localizar objetos seleccionados Location Ubicación @@ -2226,6 +2262,7 @@ font-technology Variable Variables Scatter: Dispersión: Rotation: Rotación: Rotation relative to: Rotación relativa a: + Hue Jitter: Variación del tono: Brush Scale Options Opciones de escala del pincel Scale Proportionately Escalar proporcionalmente Stretch to Fit Stroke Length Estirar para ajustar a la longitud del trazo @@ -2262,6 +2299,7 @@ font-technology Variable Variables Black becomes the stroke color and white stays white. Other colors become tints of the stroke color by their lightness. El negro pasa a ser el color del trazo y el blanco sigue siendo blanco. Los demás colores pasan a ser matices del color del trazo, y cuanto más claro es un color, más claro es su matiz. Black and white stay as they are. Dark colors become shades of the stroke color and light colors become tints of it. El negro sigue siendo negro y el blanco sigue siendo blanco. Los demás colores pasan a ser sombras del color del trazo cuando son oscuros y matices de él cuando son claros. The key color becomes the stroke color. The other colors shift their hue by the same amount and keep their saturation and brightness. El color clave pasa a ser el color del trazo. Los demás colores giran en la rueda de colores lo mismo que el color clave y conservan su saturación y su brillo. + Roundness Redondez Roundness: Redondez: Fixed Fijo Pressure Presión @@ -2567,6 +2605,9 @@ font-technology Variable Variables Overprint Sobreimprimir Overprint and Transparency Flattener Sobreimpresión y acoplador de transparencia Overprint and Transparency Flattener Options Opciones de sobreimpresión y acoplador de transparencia + Custom… Personalizado… + Custom Transparency Flattener Options Opciones personalizadas de acoplador de transparencia + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS no tiene transparencia alfa, y Sobreimpresiones determina si se conservan las sobreimpresiones. Overprint Black… Sobreimprimir negro… Overprint Fill Sobreimprimir relleno Overprint Preview Vista previa de sobreimpresión @@ -2616,6 +2657,11 @@ font-technology Variable Variables Pathfinders: Buscatrazos: Paths Trazados Path Length Longitud de los trazados + Grid Size Tamaño de cuadrícula + Grid Colors Colores de cuadrícula + Flattener Preset Preajuste del acoplador + X X + Y Y Paths: {paths} Anchors: {anchors} Colors: {colors} Trazados: {paths} Anclas: {anchors} Colores: {colors} Pattern Motivo Pattern Editing Edición de motivo @@ -2673,6 +2719,7 @@ font-technology Variable Variables Play Current Selection Reproducir la selección actual Save Actions… Guardar acciones… Load Actions… Cargar acciones… + Replace Actions… Reemplazar acciones… Reset Actions Restablecer acciones Replace the current actions with the default set? ¿Reemplazar las acciones actuales por el conjunto predeterminado? Append adds the default set after the current sets instead. Añadir agrega en su lugar el conjunto predeterminado después de los conjuntos actuales. @@ -2688,6 +2735,10 @@ font-technology Variable Variables Polar Grid Tool Herramienta Cuadrícula polar Polygon Polígono Polygon Properties: Propiedades del polígono: + Line Properties: Propiedades de la línea: + Line Length: Longitud de la línea: + Line Angle: Ángulo de la línea: + Constrain Pie Angle Restringir ángulo del sector Polygon Tool Herramienta Polígono Portrait Vertical Power Saving (integrated) Ahorro de energía (integrada) @@ -2847,6 +2898,9 @@ digits Malayalam Malayálam Real World: Mundo real: Real-time Drawing and Editing Dibujo y edición en tiempo real Use Monitor Profile for Canvas Usar perfil del monitor para el lienzo + Refresh Monitor Profile Actualizar perfil del monitor +@msg turn on Use Monitor Profile for Canvas first activa primero «Usar perfil del monitor para el lienzo» +@msg this build doesn't read display profiles esta versión no lee perfiles de pantalla The canvas is drawn in sRGB. El lienzo se dibuja en sRGB. Canvas display profile: Perfil de pantalla del lienzo: The system matches the window to the display's colors. El sistema ajusta la ventana a los colores de la pantalla. @@ -3039,6 +3093,8 @@ digits Malayalam Malayálam Reselect Volver a seleccionar Reset Restablecer Reset Bounding Box Restablecer cuadro delimitador + Rotate Bounding Box Rotar cuadro delimitador + Rotate Bounding Box… Rotar cuadro delimitador… Reset Envelope Mesh Restablecer malla de envolvente Reset Envelope Shape Restablecer forma de envolvente Reset Essentials Restablecer Essentials @@ -3079,6 +3135,7 @@ digits Malayalam Malayálam Reshape Segment Remodelar segmento Reshape Tool Herramienta Remodelar Reshape Type Area Remodelar área de texto + Resolution Resolución Resolution: Resolución: Responsive Adaptable Restore Restaurar @@ -3105,6 +3162,7 @@ digits Malayalam Malayálam The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. La rueda del mouse con Cmd/Ctrl pulsado desplaza el lienzo en horizontal. Dragging sideways on a numeric field's label changes the field's value. Arrastrar en horizontal sobre la etiqueta de un campo numérico cambia el valor del campo. A two-finger rotate gesture on a trackpad rotates the canvas view. Un gesto de giro con dos dedos en un trackpad gira la vista del lienzo. + When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Al mover puntos de ancla, cada curva con un extremo movido conserva su forma respecto a sus extremos. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Mantener pulsado el atajo de una herramienta la elige hasta que lo suelta, y después vuelve a elegirse la herramienta anterior. Shows the bounding box while you move the selection or draw a shape. Muestra el cuadro delimitador mientras mueve la selección o dibuja una forma. Create Trim Marks draws Japanese-style marks instead of Roman ones. Crear marcas de recorte dibuja marcas de estilo japonés en lugar de romanas. @@ -3135,6 +3193,29 @@ digits Malayalam Malayálam The unit for East Asian type measurements, which no field uses yet. La unidad para las medidas del texto de Asia oriental, que todavía no usa ningún campo. When on, a number typed without a unit into a field in picas is read in points. Si está activado, un número escrito sin unidad en un campo en picas se lee en puntos. With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options. Con ID XML, los nombres de los objetos se muestran como ID XML en Capas, Variables y Opciones de capa. + The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl. El paso del tamaño del texto y del interlineado: Cmd/Ctrl+Mayús+. y Cmd/Ctrl+Mayús+, cambian el tamaño un paso, o cinco con Alt también; en texto horizontal, Alt con la flecha arriba o abajo cambia el interlineado un paso, o cinco con Cmd/Ctrl. + The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl. El paso del tracking y del kerning, en milésimas de em: en texto horizontal, Alt con la flecha izquierda o derecha cambia el kerning en el cursor o el tracking del texto seleccionado un paso, o cinco con Cmd/Ctrl. + The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. El paso del desplazamiento vertical: en texto horizontal, Alt y Mayús con la flecha arriba o abajo mueven la línea de base un paso, o cinco con Cmd/Ctrl. + Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. Muestra las opciones del texto japonés y de otros idiomas de Asia oriental en los paneles Carácter, Párrafo, OpenType y Glifos, y el comando Fuentes compuestas. + Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. Muestra las opciones del texto árabe, hebreo e índico en los paneles Carácter y Párrafo, como la dirección del párrafo, las kashidas y los dígitos. + The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. Las herramientas de selección seleccionan el texto solo en su línea de base, el marco del texto de área o su trazado, no en cualquier punto dentro de su caja. + Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. Los menús de fuentes muestran cada fuente con su nombre en inglés; desactivado, una fuente que también tiene un nombre en su propio idioma muestra ese nombre. + New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. El texto de área nuevo empieza con Tamaño automático activado, así que un marco rectangular de texto horizontal crece o se reduce en altura para ajustarse a su texto. + Font lists and the Type › Font menu show a sample of each font beside its name. Las listas de fuentes y el menú Fuente muestran una muestra de cada fuente junto a su nombre. + Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on. Las muestras de fuentes se dibujan en texto oscuro sobre blanco, sea cual sea el brillo de la interfaz; solo se aplica mientras las previsualizaciones de fuentes en los menús están activadas. + How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is. La altura de cada fila en las listas de los campos de fuente, como el del panel Carácter, y por tanto el tamaño de cada muestra. + How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first. Cuántas de las últimas fuentes usadas, de 1 a 15, muestran Fuentes recientes y las listas de fuentes, la más reciente primero. + When you change the font or font style of text, characters the new font has no glyph for keep the font they had. Al cambiar la fuente o el estilo de fuente de un texto, los caracteres para los que la nueva fuente no tiene glifo conservan la fuente que tenían. + A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export. Un resaltado rosa en el lienzo marca los glifos que las funciones OpenType han sustituido, como las ligaduras; no se imprime ni se exporta. + With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from. Con la herramienta Texto, al seleccionar un solo carácter aparece junto a él en el lienzo una fila de sus glifos alternativos para elegir. + A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export. Un resaltado rosa en el lienzo marca el texto dibujado con una fuente sustituta porque falta su fuente; no se imprime ni se exporta. + New type made with a Type tool starts with placeholder text, selected, so typing replaces it. El texto nuevo creado con una herramienta de texto empieza con texto de relleno seleccionado, que lo que escriba sustituye. + Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list. Escribir un marcador de lista como 1. o * y luego un espacio al principio de un párrafo convierte el párrafo en una lista. + Fonts in this folder show in the font menus and can be used without being installed. Las fuentes de esta carpeta aparecen en los menús de fuentes y se pueden usar sin instalarlas. + Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows. Aplicar un estilo gráfico a un texto quita a los caracteres su propio relleno o trazo donde el estilo tiene uno, para que se vea la pintura del estilo. + Align and Distribute measure point type by the ink of its glyphs instead of its em box. Alinear y Distribuir miden el texto de punto por la tinta de sus glifos en lugar de por su caja em. + Align and Distribute measure area type by the ink of its glyphs instead of its frame. Alinear y Distribuir miden el texto de área por la tinta de sus glifos en lugar de por su marco. + The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box. El cuadro delimitador y el panel Transformar miden el texto de punto por la tinta de sus glifos en lugar de por su caja em. Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply. Ajusta el dibujo, el desplazamiento y el escalado a las subdivisiones de la cuadrícula, aunque la cuadrícula esté oculta; mientras está activado, Ajustar a píxel no se aplica. The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead. El color de las guías no seleccionadas; una mesa de trabajo con una Etiqueta de las guías dibuja sus propias guías en el color de la etiqueta. Draws guides as solid lines or as dots, including the guides already in the document. Dibuja las guías como líneas continuas o como puntos, incluidas las guías que ya están en el documento. @@ -3216,6 +3297,7 @@ digits Malayalam Malayálam Rounded Rectangle Tool Herramienta Rectángulo redondeado Rounded Rectangle… Rectángulo redondeado… Row Size: Tamaño de fila: + Rows Filas Rows: Filas: Rule: Filete: Rulers Reglas @@ -3390,6 +3472,9 @@ digits Malayalam Malayálam Search commands, tools, panels and effects… Buscar comandos, herramientas, paneles y efectos… No commands match Ningún comando coincide {pos} of {total}: {name} {pos} de {total}: {name} + No menu item Sin elemento de menú + Toolbar Barra de herramientas + {toolbar}, in the {tool} group {toolbar}, en el grupo {tool} @plural {n} result|{n} results {n} resultado|{n} resultados @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} de {n} resultado. Sigue escribiendo para acotarlos.|{shown} de {n} resultados. Sigue escribiendo para acotarlos. Recent Commands Comandos recientes @@ -3470,6 +3555,7 @@ digits Malayalam Malayálam Set Slice Rectangle Definir rectángulo de sector Set Tab Stops Definir tabulaciones Set Text Definir texto + Set the current fill or stroke to the selected color Asignar el color seleccionado al relleno o trazo actual Set the selected color to the current color Asignar el color actual al color seleccionado Set Zoom Definir zoom Settings… Ajustes… @@ -3593,7 +3679,7 @@ digits Malayalam Malayálam Show Vivid/Muted Mostrar vivos/apagados Show Warm/Cool Mostrar cálidos/fríos Show {kind} Brushes Mostrar pinceles de {kind} - Show/hide plate (Alt-click: only this plate) Mostrar/ocultar plancha (Alt+clic: solo esta plancha) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Mostrar/ocultar plancha (Alt+clic: solo esta plancha; Alt+clic otra vez: todas las planchas) Show: Mostrar: Shown with the optimised preview. Se muestra con la vista previa optimizada. Side 1: Lado 1: @@ -3900,7 +3986,7 @@ digits Malayalam Malayálam Composite Fonts Fuentes compuestas Export Composite Fonts Exportar fuentes compuestas Import Composite Fonts Importar fuentes compuestas -@msg each font must be {name, parts} cada fuente debe ser {name, parts} +@msg each font must be {{name, parts}} cada fuente debe ser {{name, parts}} @msg unknown key `{k}`; a font takes name and parts clave desconocida `{k}`; una fuente admite name y parts @msg each font needs a name cada fuente necesita un nombre @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` no puede nombrar una fuente compuesta (de 1 a {COMPOSITE_NAME_MAX} caracteres, sin caracteres de control) @@ -3913,7 +3999,10 @@ digits Malayalam Malayálam @msg two composite fonts are named `{_1}` dos fuentes compuestas se llaman `{_1}` @msg `{_1}` is the name of an installed font `{_1}` es el nombre de una fuente instalada @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2} usa `{font}`, una fuente compuesta -@msg give fonts: [{name, parts}…] indique fonts: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] indique fonts: [{{name, parts}}…] +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` debe ser "document", {{artboards: [index, …]}} o {{layers: [id, …]}} +@msg numbers out of order in {{}} quantifier números desordenados en el cuantificador {{}} +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) la pintura no es un degradado de forma libre (aplique uno con paint.editGradient {{kind: "freeform"}}) @msg path is empty path está vacío @msg fonts must be a list of composite fonts fonts debe ser una lista de fuentes compuestas @msg names must be strings names debe contener cadenas @@ -3996,6 +4085,13 @@ digits Malayalam Malayálam Thumbnail View Vista de miniaturas Thumbnails: Miniaturas: Tile Mosaico + Tile All Vertically Mosaico vertical de todo + Tile All Horizontally Mosaico horizontal de todo + 2-Up Layout Disposición de 2 + 3-Up Layout Disposición de 3 + 4-Up Layout Disposición de 4 + 6-Up Layout Disposición de 6 + Arrange Documents Organizar documentos Tile Edge Color Color del borde del mosaico Tile Edge Color… Color del borde del mosaico… Tile Full Pages Mosaico de páginas completas @@ -4190,6 +4286,8 @@ digits Malayalam Malayálam V Spacing: Espaciado V: V: V: Variable Width Profile Perfil de anchura variable + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. El pincel del trazo mantiene su propio tamaño, así que un perfil de anchura no lo cambia. Quite el pincel para usar un perfil. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. El pincel del trazo mantiene su propio tamaño, así que un perfil de anchura no lo cambia. Quite el pincel para usar un perfil. Variables Variables New Variable Nueva variable Delete Variable Eliminar variable @@ -4254,7 +4352,7 @@ digits Malayalam Malayálam Vertical: Vertical: Very High Muy alta View Ver - View Artboard Only Ver solo la mesa de trabajo + View Artboard Contents Only Ver solo el contenido de la mesa de trabajo View Opacity Mask Ver máscara de opacidad View PDF after saving Ver PDF después de guardar View {n} Vista {n} @@ -4468,6 +4566,7 @@ imageTrace Outline Contorno Bevel Bisel Offset Desplazamiento Axis Eje + Axis Angle Ángulo del eje axis Horizontal Horizontal axis Vertical Vertical axis Both Ambos @@ -4544,6 +4643,13 @@ axis Both Ambos Show External Script Warning Mostrar advertencia de scripts externos A Script Is Running Se está ejecutando un script Script Alert Aviso del script + Script File Access Acceso del script a archivos + The script asks to read a file you choose. El script pide leer un archivo que usted elija. + The script asks to read and write a file you choose. El script pide leer y escribir un archivo que usted elija. + The script asks to read and write a folder you choose, with everything in it. El script pide leer y escribir una carpeta que usted elija, con todo su contenido. + Allow Once Permitir una vez + Always Allow This Script Permitir siempre este script + Deny Denegar A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Un script puede cambiar los documentos abiertos y escribir archivos mediante los comandos que ejecuta. Ejecute solo scripts de confianza. Do not show this warning again No volver a mostrar esta advertencia Stop the script and undo what it did? Then quit again. ¿Detener el script y deshacer lo que hizo? Después, vuelva a salir. @@ -4560,6 +4666,8 @@ axis Both Ambos @msg the script is no longer in the Scripts folder el script ya no está en la carpeta Scripts Some scripts were not listed Algunos scripts no se han incluido en la lista The Scripts folder cannot be read No se puede leer la carpeta Scripts + Loading scripts… Cargando scripts… + The Scripts folder is still being read Aún se está leyendo la carpeta Scripts @msg the script's run is no longer available la ejecución del script ya no está disponible @msg a failed command changed undo steps that could not be put back, so the script was stopped un comando fallido cambió pasos de deshacer que no se pudieron restaurar, así que el script se detuvo @msg a recovery copy could not be written, so the script was not run no se pudo escribir una copia de recuperación, así que el script no se ejecutó @@ -4572,8 +4680,6 @@ axis Both Ambos @msg Script file could not be read No se pudo leer el archivo de script @msg Script folder has more than 2,048 entries La carpeta de script tiene más de 2048 entradas @msg Script file open mode must be r, w, e or a El modo de apertura del archivo de script debe ser r, w, e o a -@msg Script file writing is not available La escritura de archivos de script no está disponible -@msg Script file dialogs are not available Los cuadros de diálogo de archivos de script no están disponibles @msg Script files cannot be opened in another application Los archivos de script no se pueden abrir en otra aplicación @msg Script file access is unavailable on the web El acceso a archivos de script no está disponible en la web @msg Script has 256 files open El script tiene 256 archivos abiertos @@ -4712,8 +4818,37 @@ liquify-list-end {0}, {1} {0}, {1} @msg is a prompt's answer, whose `value` must be a string or null es la respuesta de un prompt, cuyo `value` debe ser una cadena o null @msg must have `kind` alert, confirm or prompt debe tener `kind` alert, confirm o prompt @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` solo es para una ejecución sin nadie a quien preguntar: en la aplicación, la persona responde cada cuadro de diálogo +@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` debe ser un número entero de 1 a {_1} +@msg `args{place}` is nested more than 64 levels deep `args{place}` está anidado a más de 64 niveles +@msg `args` must be an object `args` debe ser un objeto +@msg `args` is larger than 1 MiB `args` ocupa más de 1 MiB +@msg `path` is empty `path` está vacío +@msg `installed` takes a `path`, not a `source` `installed` admite un `path`, no un `source` +@msg `path` must name a .js or .jsx file `path` debe indicar un archivo .js o .jsx +@msg give exactly one of `path` and `source` indique exactamente uno de `path` y `source` @msg Running a script Ejecutando un script @msg Copied the script report Se copió el informe del script +@msg Script file access denied: {path} Acceso del script a archivos denegado: {path} +@msg Script file access to the app's own folders is not allowed El script no puede acceder a las carpetas propias de la aplicación +@msg Script file cannot encode the text El archivo del script no puede codificar el texto +@msg Script file could not be written No se pudo escribir el archivo del script +@msg Script file dialogs need a person to answer them Los cuadros de diálogo de archivo del script necesitan que una persona los responda +@msg Script file is not open for writing El archivo del script no está abierto para escritura +@msg Script file name is already in use El nombre del archivo del script ya está en uso +@msg Script file name must be a name without a folder El nombre del archivo del script debe ser un nombre sin carpeta +@msg Script file permission can be kept only for a script run from a file El permiso de archivos solo se puede conservar para un script ejecutado desde un archivo +@msg Script file permission could not be saved No se pudo guardar el permiso de archivos del script +@msg Script folder is not empty La carpeta del script no está vacía +@msg Script files cannot make aliases Los archivos del script no pueden crear alias +@msg Script file hidden setting cannot be changed No se puede cambiar el ajuste de oculto del archivo del script +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: un cuadro de diálogo de archivo no se puede abrir dentro de una devolución de llamada de una función integrada, un getter, una conversión o un archivo que ejecuta $.evalFile; llámelo desde el propio código del script +@msg the script wrote more file data than one run may write (32 MiB) el script escribió más datos de archivo de los que puede escribir una ejecución (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` para el cuadro de diálogo de archivo de un script debe ser uno de: once, always, deny, stop +@msg choose a file or folder first, or deny elija primero un archivo o una carpeta, o deniegue +@msg the script file permissions could not be saved: {e} no se pudieron guardar los permisos de archivos de los scripts: {e} +@msg this script's file access can be allowed only once el acceso a archivos de este script solo se puede permitir una vez +@msg Only the person at the keyboard can allow a script's file access Solo la persona que está en el teclado puede permitir el acceso a archivos de un script +@msg A script is given at most 2,048 files: the files picked after them were left out Un script recibe como máximo 2.048 archivos: los archivos elegidos después de ellos se omitieron @msg Copied the link info Se copió la información del vínculo @msg Corners edits the corners of a path Esquinas edita las esquinas de un trazado @msg Couldn't copy to the system clipboard: {e} No se pudo copiar al portapapeles del sistema: {e} @@ -4789,6 +4924,7 @@ liquify-list-end {0}, {1} {0}, {1} @msg Saved {path} Se guardó {path} @msg Select text or click into text with the Type tool to insert glyphs Selecciona texto o haz clic dentro del texto con la herramienta Texto para insertar glifos @msg Shape Builder: no region under the pointer Generador de formas: no hay ninguna región bajo el puntero +@msg Shape Builder: select all paths you want to merge Generador de formas: selecciona todos los trazados que quieras combinar @msg Shape Builder: select paths or compound paths Generador de formas: selecciona trazados o trazados compuestos @msg Show All Hidden Attributes: nothing is hidden Mostrar todos los atributos ocultos: no hay nada oculto @msg Split Into Grid: select paths large enough for the grid Dividir en cuadrícula: selecciona trazados lo bastante grandes para la cuadrícula @@ -4844,6 +4980,8 @@ liquify-list-end {0}, {1} {0}, {1} @msg `{min_key}` is greater than `{max_key}` `{min_key}` es mayor que `{max_key}` @msg give at least one of `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` indica al menos uno de `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` debe ser grayscale, rgb, hsb, cmyk o websafe +@msg `view` must be wheel or box `view` debe ser wheel o box +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` debe ser hue, saturation, brightness, red, green o blue @msg `{k}` must be [x, y] `{k}` debe ser [x, y] @msg `{name}` has no options `{name}` no tiene opciones @msg `{name}` is a built-in workspace; choose another name `{name}` es un espacio de trabajo integrado; elige otro nombre @@ -4932,6 +5070,7 @@ liquify-list-end {0}, {1} {0}, {1} @msg bad trailer trailer no válido @msg balance must be between 0 and 100 balance debe estar entre 0 y 100 @msg batch step {_1} (`{id}`) failed: {e} falló el paso {_1} del lote (`{id}`): {e} +@msg action step {_1} (`{id}`) failed: {reason} falló el paso {_1} de la acción (`{id}`): {reason} @msg brightness must be dark|mediumDark|mediumLight|light brightness debe ser dark|mediumDark|mediumLight|light @msg can't encode the document: {0} no se puede codificar el documento: {0} @msg can't parse shortcut `{c}` no se puede interpretar el atajo `{c}` @@ -4951,6 +5090,7 @@ liquify-list-end {0}, {1} {0}, {1} @msg choose a folder to export to elige una carpeta a la que exportar @msg choose a location for the package elige una ubicación para el paquete @msg clipboard is empty el portapapeles está vacío +@msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: al menos un color debe quedar en la tabla de colores @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` no es un color como "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: como máximo {MAX_TABLE} colores @msg command `{0}` is not available right now: {1} el comando `{0}` no está disponible ahora: {1} @@ -5018,9 +5158,15 @@ liquify-list-end {0}, {1} {0}, {1} @msg no PNG encoder no hay codificador PNG @msg no active document no hay ningún documento activo @msg no active perspective plane no hay ningún plano de perspectiva activo +@msg the perspective grid is hidden la cuadrícula de perspectiva está oculta +@msg Automatic Plane Positioning is off: turn on anchorPoint or gridlineIntersection (perspective.widget.options) El posicionamiento automático del plano está desactivado: activa anchorPoint o gridlineIntersection (perspective.widget.options) +@msg anchorPoint must be true or false anchorPoint debe ser true o false +@msg gridlineIntersection must be true or false gridlineIntersection debe ser true o false +@msg tolerance must be 0 or more tolerance debe ser 0 o más +@msg give `at` or `clear`, not both indica `at` o `clear`, no ambos @msg no anchor points selected no hay puntos de ancla seleccionados -@msg `points` must be three [x, y] pairs of numbers `points` debe ser tres pares de números [x, y] -@msg direct-select three anchor points, or give `points` seleccione directamente tres puntos de ancla o indique `points` +@msg `points` must be two or three [x, y] pairs of numbers `points` debe ser dos o tres pares de números [x, y] +@msg direct-select two or three anchor points, or give `points` seleccione directamente dos o tres puntos de ancla o indique `points` @msg no circle passes through these points: two are the same or all three lie on one line ningún círculo pasa por estos puntos: dos son iguales o los tres están en una misma línea @msg no app to open files here aquí no hay ninguna aplicación para abrir archivos @msg no artboard no hay mesa de trabajo @@ -5122,12 +5268,17 @@ liquify-list-end {0}, {1} {0}, {1} @msg no such user library no existe esa biblioteca de usuario @msg no such view no existe esa vista @msg no such width point no existe ese punto de anchura +@msg `single` must be `incoming` or `outgoing` `single` debe ser `incoming` u `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` y `outIndex` deben ser las dos mitades de un mismo punto de anchura discontinuo +@msg a discontinuous width point keeps its place un punto de anchura discontinuo conserva su posición @msg no swatch `{name}` no existe la muestra `{name}` @msg no swatch library `{l}` (see swatch.library.list) no existe la biblioteca de muestras `{l}` (consulta swatch.library.list) @msg no symbol instances selected no hay instancias de símbolo seleccionadas @msg no target object has an opacity mask: select one or give `id` ningún objeto de destino tiene máscara de opacidad: selecciona uno o indica `id` @msg no threaded text selected no hay texto enlazado seleccionado @msg no user library folder here aquí no hay ninguna carpeta de bibliotecas de usuario +@msg `{file}` has no swatches of its own `{file}` no tiene muestras propias +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` tiene muestras de motivo, que un archivo .vcswatches no puede contener @msg no user workspace `{from}` no existe el espacio de trabajo de usuario `{from}` @msg node {_1} is not text el nodo {_1} no es texto @msg node {_1} is on a locked artboard el nodo {_1} está en una mesa de trabajo bloqueada @@ -5383,6 +5534,13 @@ liquify-list-end {0}, {1} {0}, {1} @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} más de {MAX_CSV_ROWS} conjuntos de datos: Importar conjuntos de datos lee como máximo {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} más de {MAX_CSV_COLS} variables: Importar conjuntos de datos lee como máximo {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} se omitieron las variables que no son de texto: {kinds} +variable-kind Visibility Visibilidad +variable-kind Linked File Archivo vinculado +variable-kind Graph Data Datos del gráfico +variable-kind Unknown Desconocido +variable-list-two {0}, {1} {0} y {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} y {1} @msg a new document won't read these variables back with their kind: {names} un documento nuevo no volverá a leer estas variables con su tipo: {names} @msg a new document refuses this file because of these variables: {names} un documento nuevo rechaza este archivo por estas variables: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them el encabezado `{header}` de `{name}` se leería como la variable `{other}`: cambie el nombre de una de las dos @@ -5408,6 +5566,8 @@ liquify-list-end {0}, {1} {0}, {1} @msg {label}: lost track of a shape's style {label}: se perdió el estilo de una forma @msg {label}: select paths {label}: selecciona trazados @msg {label}: select paths, compound paths, groups or text {label}: selecciona trazados, trazados compuestos, grupos o texto +@msg a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first una línea u otro trazado abierto que no encierra ningún área no cambia la forma del resultado; para incluirlo, aplícale primero Objeto › Trazado › Contornear trazo +@msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first {label} produjo un resultado vacío: una línea u otro trazado abierto no encierra ningún área; para incluirlo, aplícale primero Objeto › Trazado › Contornear trazo @msg {label}… {label}… @msg {name}: CRC mismatch {name}: el CRC no coincide @msg {name}: no local header {name}: no hay encabezado local @@ -5434,6 +5594,9 @@ liquify-list-end {0}, {1} {0}, {1} @msgplural Discarded {n} recovered document|Discarded {n} recovered documents Se descartó {n} documento recuperado|Se descartaron {n} documentos recuperados @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them Se restauró {n} documento recuperado: guárdalo para conservarlo|Se restauraron {n} documentos recuperados: guárdalos para conservarlos @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} Se abrió con {n} nota: {first}|Se abrió con {n} notas: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Se copió con {n} nota: {first}|Se copió con {n} notas: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Se cortó con {n} nota: {first}|Se cortó con {n} notas: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Se calcó la imagen con {n} nota: {first}|Se calcó la imagen con {n} notas: {first} @msgplural {notice}. Opened with {n} note: {first}|{notice}. Opened with {n} notes: {first} {notice}. Se abrió con {n} nota: {first}|{notice}. Se abrió con {n} notas: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} Se guardó {path} con {n} nota: {first}|Se guardó {path} con {n} notas: {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first Se incrustó {n} imagen; faltan {missing}: vuelve a vincularlas primero|Se incrustaron {n} imágenes; faltan {missing}: vuelve a vincularlas primero @@ -5460,6 +5623,8 @@ liquify-list-end {0}, {1} {0}, {1} @msg All colors are within the CMYK gamut Todos los colores están dentro de la gama CMYK @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} color está fuera de la gama CMYK|{n} colores están fuera de la gama CMYK @msg Unembedded to {_1} Se desincrustó en {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} Se desincrustó {n} imagen en {folder}|Se desincrustaron {n} imágenes en {folder} +@msg every numbered name for {name} is taken in that folder todos los nombres numerados para {name} ya existen en esa carpeta @msg Reset {_1} Se restableció {_1} @msg Sent to {_1} Se envió a {_1} @msg {_1} files {_1} archivos @@ -5475,6 +5640,8 @@ liquify-list-end {0}, {1} {0}, {1} @msg Reload the page to go on (changes not saved yet may be lost). Vuelve a cargar la página para continuar (los cambios que aún no se guardaron podrían perderse). @msg tool (a tool id) is required se requiere tool (un id de herramienta) @msg {tool} isn't in a toolbar group of several tools {tool} no está en un grupo de la barra de herramientas con varias herramientas +@msg Presentation Mode hides the toolbars: change the screen mode to show them el Modo de presentación oculta las barras de herramientas: cambie el modo de pantalla para mostrarlas +@msg Tab has hidden the toolbars: press Tab to show them Tab ha ocultado las barras de herramientas: pulse Tab para mostrarlas @msg onto must name a panel floating in another group onto debe nombrar un panel que flote en otro grupo @msg below and above must name a panel floating in another group below y above deben nombrar un panel que flote en otro grupo @msg give only one of onto, below and above indica solo uno de onto, below y above @@ -5589,6 +5756,9 @@ liquify-list-end {0}, {1} {0}, {1} @msg automation path rejected: outside the read root {root}: {path} ruta de automatización rechazada: fuera de la carpeta raíz de lectura {root}: {path} @msg automation path rejected: outside the read roots {roots}: {path} ruta de automatización rechazada: fuera de las carpetas raíz de lectura {roots}: {path} @msg a linked JavaScript file is outside the read roots un archivo JavaScript vinculado está fuera de las carpetas raíz de lectura +@msg a linked image file is outside the read roots un archivo de imagen vinculado está fuera de las carpetas raíz de lectura +@msg a linked file's export folder is outside the read roots la carpeta de exportación de un archivo vinculado está fuera de las carpetas raíz de lectura +@msg a linked file's editing data can't be read to check it against the read roots no se pueden leer los datos de edición de un archivo vinculado para comprobarlos con las carpetas raíz de lectura @msg automation path rejected: outside the write root {root}: {path} ruta de automatización rechazada: fuera de la carpeta raíz de escritura {root}: {path} @msg automation path rejected: outside the write roots {roots}: {path} ruta de automatización rechazada: fuera de las carpetas raíz de escritura {roots}: {path} @msg automation path rejected: path is empty ruta de automatización rechazada: la ruta está vacía @@ -5816,6 +5986,7 @@ lighting Light Luz @msg missing panel layout Falta la distribución de paneles @msg unsupported native docking operation Operación nativa de anclaje no admitida Linux Display Server Servidor de pantalla de Linux + Low-Latency Drawing Dibujo de baja latencia X11 (XWayland) When a Pen Is Attached X11 (XWayland) cuando hay un lápiz conectado If a drawing tablet's pen doesn't draw, choose an X11 (XWayland) option. Si el lápiz de una tableta digitalizadora no dibuja, elige una opción X11 (XWayland). X11 (XWayland) X11 (XWayland) @@ -6080,6 +6251,7 @@ effect Regular Regular Ascent Ascendente Cap Height Altura de mayúsculas x Height Altura de la x + Em Box Height Altura del cuadro eme Justify Justificar First Baseline Primera línea de base Vertical Align Alineación vertical @@ -6249,6 +6421,7 @@ mark-style Japanese Japonesas Cove Cóncavo Depth Profundidad Front Frontal + Side Lateral Isometric Bottom Isométrica inferior Isometric Left Isométrica izquierda Isometric Right Isométrica derecha @@ -6344,7 +6517,7 @@ mark-style Japanese Japonesas @msg each of `{GRAPHICS}` must be an object cada elemento de `{GRAPHICS}` debe ser un objeto @msg `{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}` los elementos de `{GRAPHICS}` admiten symbol, face, x, y, scale y rotation, no `{k}` @msg each of `{GRAPHICS}` needs `symbol`, the name of a symbol cada elemento de `{GRAPHICS}` necesita `symbol`, el nombre de un símbolo -@msg `{GRAPHICS}` face must be front or back face de `{GRAPHICS}` debe ser front o back +@msg `{GRAPHICS}` face must be front, back or side face de `{GRAPHICS}` debe ser front, back o side @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} de `{GRAPHICS}` debe ser un número de {lo} a {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` debe ser una matriz @msg Graphics map onto the Plane, Extrude and Revolve object types Los gráficos se asignan a los tipos de objeto Plano, Extrusión y Revolución @@ -7351,6 +7524,12 @@ anchor Points: Puntos: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` debe ser "free", "keepAngles" o "symmetric" @msg `{key}` must be [x, y] `{key}` debe ser [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Conversor de unidades + Unit Converter Panel Panel Conversor de unidades + Copy with Units Copiar con unidades + From Selection Desde la selección + # Color Effects add-on: Select by Color Kind. Select by Color Kind Seleccionar por tipo de color Objects with Spot Colors Objetos con tintas planas @@ -7575,6 +7754,14 @@ breakText Glyphs Glifos Remove Gaps Quitar separaciones @msg that makes too many pieces (at most 100000): make the dashes longer eso da demasiados trozos (como máximo 100000): alargue los guiones @msg select paths, or segments, to divide seleccione trazados o segmentos para dividir +# Path Precision Tools add-on: Smooth Bridge. + Smooth Bridge… Puente suave… + Smooth Bridge Puente suave + Keep Originals Conservar originales +@msg select two circles to bridge seleccione dos círculos para unir +@msg one circle is inside the other un círculo está dentro del otro +@msg the circles are too far apart for this radius: raise the radius los círculos están demasiado separados para este radio: aumente el radio +@msg the circles are too far apart for this radius los círculos están demasiado separados para este radio # Path Precision Tools add-on: Common Tangents. Common Tangents… Tangentes comunes… Common Tangents Tangentes comunes @@ -8086,4 +8273,15 @@ breakText Glyphs Glifos @msg A panel is not joined to the rest by a crease. Un panel no está unido al resto por ninguna línea de hendido. @msg A fold line is on a non-printing layer. Una línea de plegado está en una capa que no se imprime. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneles: {panels}, bisagras: {hinges}, errores: {errors}, advertencias: {warnings} + Fold Preview Vista previa del plegado + Fold Plegado + Show Fold Lines Mostrar líneas de plegado + Three-Quarter Tres cuartos + Open a document to preview its folded shape. Abre un documento para previsualizar su forma plegada. +@msg Check the fold lines first. Comprueba primero las líneas de plegado. +@msg Panels: {panels}, hinges: {hinges} Paneles: {panels}, bisagras: {hinges} +@msg Other blanks not shown: {count} Otros troquelados no mostrados: {count} +@msg A joint does not close by {gap} pt. Una unión no cierra por {gap} pt. +@msg Two panels pass through each other. Dos paneles se atraviesan entre sí. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer debe ser "singleLine", "everyLine", "standardSingleLine" o "standardEveryLine" +@msg text.{key} `{v}`: use "{_1}" or "{_2}" text.{key} `{v}`: use "{_1}" o "{_2}" diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index bff46fc0d7..ec15ca6a99 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -180,6 +180,8 @@ Shear… Vinouta… Transform Each… Muunna kutakin… Reset Bounding Box Palauta rajausruutu + Rotate Bounding Box Kierrä rajausruutua + Rotate Bounding Box… Kierrä rajausruutua… Arrange Järjestä Bring to Front Tuo eteen Bring Forward Tuo eteenpäin @@ -301,7 +303,7 @@ Move Plane to Match Object Siirrä taso objektin mukaan Edit Text Muokkaa tekstiä Live Paint Elävä maalaus - Merge Yhdistä + Merge Sulauta Gap Options… Aukkojen asetukset… Gap Options Aukkojen asetukset Gap Detection Aukkojen tunnistus @@ -710,6 +712,13 @@ Previous Document Edellinen asiakirja Cascade Porrasta Tile Vierekkäin + Tile All Vertically Kaikki vierekkäin pystysuunnassa + Tile All Horizontally Kaikki vierekkäin vaakasuunnassa + 2-Up Layout 2 ikkunan asettelu + 3-Up Layout 3 ikkunan asettelu + 4-Up Layout 4 ikkunan asettelu + 6-Up Layout 6 ikkunan asettelu + Arrange Documents Järjestä asiakirjat Float in Window Kelluta ikkunassa Float All in Windows Kelluta kaikki ikkunoissa Consolidate All Windows Yhdistä kaikki ikkunat @@ -756,6 +765,11 @@ Saturation and brightness Kylläisyys ja kirkkaus Color field Värikenttä {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Ympyränäkymä + Box View Ruutunäkymä + Box Channel Ruudun kanava + Color box Väriruutu + Color Wheel Options Väriympyrän asetukset CSS Properties CSS-ominaisuudet Document Info Asiakirjan tiedot Flattener Preview Litistyksen esikatselu @@ -1521,6 +1535,7 @@ lighting Light Valo Play Current Selection Toista nykyinen valinta Save Actions… Tallenna toiminnot… Load Actions… Lataa toiminnot… + Replace Actions… Korvaa toiminnot… Reset Actions Palauta toiminnot Replace the current actions with the default set? Korvataanko nykyiset toiminnot oletussarjalla? Append adds the default set after the current sets instead. Lisää-painike lisää sen sijaan oletussarjan nykyisten sarjojen perään. @@ -1681,7 +1696,7 @@ digits Malayalam Malajalam Composite Fonts Yhdistelmäfontit Export Composite Fonts Vie yhdistelmäfontit Import Composite Fonts Tuo yhdistelmäfontit -@msg each font must be {name, parts} jokaisen fontin on oltava {name, parts} +@msg each font must be {{name, parts}} jokaisen fontin on oltava {{name, parts}} @msg unknown key `{k}`; a font takes name and parts tuntematon avain `{k}`; fontti ottaa name ja parts @msg each font needs a name jokainen fontti tarvitsee nimen @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` ei kelpaa yhdistelmäfontin nimeksi (1–{COMPOSITE_NAME_MAX} merkkiä, ei ohjausmerkkejä) @@ -1694,7 +1709,10 @@ digits Malayalam Malajalam @msg two composite fonts are named `{_1}` kahden yhdistelmäfontin nimi on `{_1}` @msg `{_1}` is the name of an installed font `{_1}` on asennetun fontin nimi @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2} käyttää fonttia `{font}`, joka on yhdistelmäfontti -@msg give fonts: [{name, parts}…] anna fonts: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] anna fonts: [{{name, parts}}…] +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope`-arvon on oltava "document", {{artboards: [index, …]}} tai {{layers: [id, …]}} +@msg numbers out of order in {{}} quantifier luvut väärässä järjestyksessä kvanttorissa {{}} +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) maali ei ole vapaamuotoinen liukuväri (käytä sellaista komennolla paint.editGradient {{kind: "freeform"}}) @msg path is empty path on tyhjä @msg fonts must be a list of composite fonts fonts on oltava luettelo yhdistelmäfonteista @msg names must be strings names on oltava merkkijonoja @@ -1737,6 +1755,7 @@ digits Malayalam Malajalam Underline Alleviivaus Vertical Scale % Pystyskaalaus % Axis Akseli + Axis Angle Akselin kulma ICF Top/Right ICF ylä/oikea ICF Bottom/Left ICF ala/vasen Show Font Height Options Näytä fontin korkeuden asetukset @@ -1779,6 +1798,7 @@ digits Malayalam Malajalam Rule: Sääntö: Save changes to {name} Tallenna muutokset kohteeseen {name} Save theme to My Themes Tallenna teema Omiin teemoihin + Set the current fill or stroke to the selected color Aseta nykyiseksi täytöksi tai viivaksi valittu väri Set the selected color to the current color Aseta valituksi väriksi nykyinen väri Copy All Styles Kopioi kaikki tyylit Exported {path} Viety: {path} @@ -2081,7 +2101,7 @@ digits Malayalam Malajalam Stroke: click for swatches, Shift-click for the color mixer Viiva: napsauta avataksesi värimallit, Vaihto-napsauta avataksesi värisekoittimen This panel is on the roadmap (see the parity plan). Tämä paneeli on suunnitteilla (katso yhdenmukaisuussuunnitelma). Open a document to navigate it. Avaa asiakirja, niin voit liikkua siinä. - View Artboard Only Näytä vain piirtoalusta + View Artboard Contents Only Näytä vain piirtoalustan sisältö Contextual Alternates Kontekstuaaliset vaihtoehdot Default Figure Oletusnumerot Discretionary Ligatures Valinnaiset ligatuurit @@ -2231,7 +2251,7 @@ digits Malayalam Malajalam Overprint Preview (separations) Päällepainatuksen esikatselu (erottelut) Show All Plates Näytä kaikki painolevyt Show all plates Näytä kaikki painolevyt - Show/hide plate (Alt-click: only this plate) Näytä/piilota painolevy (Alt-napsautus: vain tämä painolevy) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Näytä/piilota painolevy (Alt-napsautus: vain tämä painolevy; uusi Alt-napsautus: kaikki painolevyt) Simulate Paper Simuloi paperia Use Black Point Compensation Käytä mustan pisteen kompensointia Working CMYK (don't tag) Työ-CMYK (ei tunnistetta) @@ -2271,6 +2291,8 @@ digits Malayalam Malajalam Tip extends past the end point Kärki ulottuu päätepisteen yli Tip on the end point Kärki päätepisteessä Variable Width Profile Muuttuvan leveyden profiili + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Viivan sivellin säilyttää oman kokonsa, joten leveysprofiili ei muuta sitä. Poista sivellin, jos haluat käyttää profiilia. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Viivan sivellin säilyttää oman kokonsa, joten leveysprofiili ei muuta sitä. Poista sivellin, jos haluat käyttää profiilia. Weight: Paksuus: Art using a deleted global swatch keeps its colour. Poistettua globaalia värimallia käyttävä kuvitus säilyttää värinsä. Color Group: {name} Väriryhmä: {name} @@ -2380,6 +2402,10 @@ digits Malayalam Malajalam Flip Horizontal Käännä vaakasuunnassa Flip Vertical Käännä pystysuunnassa Polygon Properties: Monikulmion ominaisuudet: + Line Properties: Viivan ominaisuudet: + Line Length: Viivan pituus: + Line Angle: Viivan kulma: + Constrain Pie Angle Säilytä sektorin kulma Rectangle Properties: Suorakulmion ominaisuudet: Shape Properties: Muodon ominaisuudet: Shape Properties Muodon ominaisuudet @@ -2421,6 +2447,7 @@ digits Malayalam Malajalam Scatter: Sirottelu: Rotation: Kierto: Rotation relative to: Kierto suhteessa: + Hue Jitter: Sävyn vaihtelu: Brush Scale Options Siveltimen skaalausasetukset Scale Proportionately Skaalaa suhteellisesti Stretch to Fit Stroke Length Venytä viivan pituuteen @@ -2459,6 +2486,7 @@ digits Malayalam Malajalam Size: Koko: Calligraphic Brush Options Kalligrafisen siveltimen asetukset Bristle Brush Options Harjassiveltimen asetukset + Roundness Pyöreys Roundness: Pyöreys: Shape: Muoto: Bristle Length: Harjasten pituus: @@ -2777,6 +2805,7 @@ digits Malayalam Malajalam BLANK DOCUMENT PRESETS TYHJÄN ASIAKIRJAN ESIASETUKSET Bleed Leikkuuvara Change to Right-to-Left Layout Vaihda oikealta vasemmalle -asetteluun + Columns Sarakkeet Columns: Sarakkeet: Documents you create appear here. Luomasi asiakirjat näkyvät tässä. More Settings Lisää asetuksia @@ -2910,6 +2939,9 @@ digits Malayalam Malajalam Open a document to preview its pages Avaa asiakirja, niin voit esikatsella sen sivuja Output › Mode Tuloste › Tila Overprint and Transparency Flattener Options Päällepainatuksen ja läpinäkyvyyden litistyksen asetukset + Custom… Mukautettu… + Custom Transparency Flattener Options Läpinäkyvyyden litistyksen mukautetut asetukset + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS:ssä ei ole alfa-läpinäkyvyyttä, ja Päällepainatukset määrää, säilytetäänkö päällepainatukset. Place the pages with the placement again Sijoita sivut uudelleen sijoittelun mukaan Placement: Sijoittelu: Preserve CMYK Numbers Säilytä CMYK-arvot @@ -2959,14 +2991,19 @@ digits Malayalam Malajalam Around Object Objektin ympärillä Background: Tausta: Changing these settings changes how raster effects look when exported, flattened or expanded. Näiden asetusten muuttaminen vaikuttaa rasteritehosteiden ulkoasuun vietäessä, litistettäessä tai laajennettaessa. + Add Around Lisää objektin ympärille + Anti Alias Reunanpehmennys + Color Model Värijärjestelmä Color Model: Värijärjestelmä: Create Clipping Mask Luo leikkausmaski Preserve Spot Colors Säilytä spottivärit + Resolution Tarkkuus Resolution: Tarkkuus: Transparent Läpinäkyvä Layout Order: Asettelujärjestys: Change to Left-to-Right Layout Vaihda vasemmalta oikealle -asetteluun Artboards: {n} Piirtoalustat: {n} + Rows Rivit Rows: Rivit: Assign Määritä Color Group: Väriryhmä: @@ -3115,6 +3152,8 @@ antiAlias Sharp Terävä Every option matches {base}. Kaikki asetukset vastaavat kohdetta {base}. Files of a PDF standard can't be password-protected. PDF-standardin mukaisia tiedostoja ei voi suojata salasanalla. Files of this standard tag their colours with ICC profiles. Tämän standardin tiedostot merkitsevät värinsä ICC-profiileilla. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Tämän standardin tiedostot merkitsevät värinsä ICC-profiileilla, paitsi tulostustavoitteen profiilin CMYK-värit, jotka kirjoitetaan DeviceCMYK-muodossa. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. Kun valintana on ”Älä sisällytä profiileja” ja tulostustavoite on CMYK, jokainen CMYK-väri kirjoitetaan DeviceCMYK-muodossa, ellei sitä muunneta toisen profiilin CMYK-kohteeseen. Flattener preset: Litistyksen esiasetus: General › Thumbnails Yleiset › Pikkukuvat Grayscale images Harmaasävykuvat @@ -3334,6 +3373,12 @@ antiAlias Sharp Terävä LF (macOS, Linux) LF (macOS, Linux) CRLF (Windows) CRLF (Windows) Text Export Options Tekstin vientiasetukset + Chinese Big 5 Kiina Big 5 + Cyrillic Kyrillinen + Greek Kreikka + Turkish Turkki + Baltic Balttilainen + Central European Keskieurooppalainen Character Set: Merkistö: Join the lines of each paragraph Yhdistä kunkin kappaleen rivit Line Breaks Rivinvaihdot @@ -3363,6 +3408,9 @@ antiAlias Sharp Terävä Variable Options Muuttujan asetukset Define a variable first Määritä ensin muuttuja Adjust Adjoining Width Points Säädä viereisiä leveyspisteitä + Incoming Saapuva + Outgoing Lähtevä + Single Width Only Vain yksi leveys Keep both sides the same width Pidä molemmat puolet samanlevyisinä Side 1: Puoli 1: Side 2: Puoli 2: @@ -3471,9 +3519,17 @@ theme Appearance Ulkoasu Break Link to Symbol Katkaise linkki symboliin Brush Definition Siveltimen määritys Brush Options… Siveltimen asetukset… + Options of Selected Object… Valitun objektin asetukset… + Options of Selected Object Valitun objektin asetukset +@msg no path painted with a brush is selected siveltimellä maalattua polkua ei ole valittu +@msg the selected paths are painted with brushes of different types valitut polut on maalattu eri tyyppisillä siveltimillä +@msg give `params` or `reset`, not both anna `params` tai `reset`, ei molempia +@msg a bristle brush has no options of its own on a path harjassiveltimellä ei ole polulla omia asetuksia Current Brush Nykyinen sivellin Current Symbol Nykyinen symboli Delete Brush Poista sivellin + Delete Color Poista väri + Restore Generated Table Palauta luotu taulukko Delete Symbol Poista symboli Delete the selected symbol? Poistetaanko valittu symboli? Delete the selected symbols? Poistetaanko valitut symbolit? @@ -3751,6 +3807,7 @@ theme Appearance Ulkoasu Select Art Valitse kuvitus Set Current Layer Aseta nykyinen taso Flatten Artwork Litistä kuvitus + Locate Layer Paikanna taso Locate Object Paikanna objekti Lock Others Lukitse muut Merge Selected Yhdistä valitut @@ -3927,6 +3984,7 @@ theme Appearance Ulkoasu 90° & 45° Angles 90° ja 45° kulmat 90° Angles 90° kulmat Additional Plug-ins Folder Lisälaajennusten kansio + Plug-in Instruction Budget Laajennusten käskybudjetti Additional Fonts Folder Lisäfonttien kansio Alignment Guides Tasausapuviivat Anchor Points, Handle, and Bounding Box Display Ankkuripisteiden, kahvojen ja rajausruudun näyttö @@ -3953,6 +4011,7 @@ theme Appearance Ulkoasu Data Recovery Tietojen palautus Default Language Oletuskieli Disable Auto Add/Delete Poista automaattinen lisäys/poisto käytöstä + Interpolate Control Points When Moving Anchors Interpoloi suuntakahvat siirrettäessä ankkuripisteitä Display All Blacks Accurately Näytä kaikki mustat tarkasti Display All Blacks as Rich Black Näytä kaikki mustat syvämustina Display Bitmaps as Anti-aliased Images in Pixel Preview Näytä bittikartat reunanpehmennettyinä kuvina pikseliesikatselussa @@ -3969,6 +4028,7 @@ theme Appearance Ulkoasu Enable Rubber Band for Ota kumilankavalinta käyttöön kohteelle Enable Touch Gestures Ota kosketuseleet käyttöön Switch Selection and Drawing Modes Vaihda valinta- ja piirtotilan välillä + Select Last Selection Tool Valitse viimeksi käytetty valintatyökalu Enable Touch Workspace Ota kosketustyötila käyttöön English: UK Englanti: UK Every (minutes) Välein (minuuttia) @@ -4040,6 +4100,9 @@ theme Appearance Ulkoasu Printing / Exporting Tulostus / vienti Real-time Drawing and Editing Reaaliaikainen piirto ja muokkaus Use Monitor Profile for Canvas Käytä näytön profiilia kankaalle + Refresh Monitor Profile Päivitä näytön profiili +@msg turn on Use Monitor Profile for Canvas first ota ensin käyttöön ”Käytä näytön profiilia kankaalle” +@msg this build doesn't read display profiles tämä versio ei lue näyttöjen profiileja The canvas is drawn in sRGB. Kangas piirretään sRGB-tilassa. Canvas display profile: Kankaan näyttöprofiili: The system matches the window to the display's colors. Järjestelmä sovittaa ikkunan näytön väreihin. @@ -4101,6 +4164,7 @@ theme Appearance Ulkoasu Scroll Sideways with Cmd/Ctrl + Wheel Vieritä vaakasuunnassa Cmd/Ctrl + hiiren rullalla Scrub Numeric Fields by Dragging Muuta numerokenttiä vetämällä Linux Display Server Linuxin näyttöpalvelin + Low-Latency Drawing Pienen viiveen piirto Print Preview Tulostuksen esikatselu Print Setup Tulostusasetukset Bitmap Bittikartta @@ -4439,6 +4503,9 @@ font-technology Variable Muuttuvat Search commands, tools, panels and effects… Hae komentoja, työkaluja, paneeleita ja tehosteita… No commands match Mikään komento ei vastaa hakua {pos} of {total}: {name} {pos}/{total}: {name} + No menu item Ei valikkokohdetta + Toolbar Työkalurivi + {toolbar}, in the {tool} group {toolbar}, ryhmässä {tool} @plural {n} result|{n} results {n} tulos|{n} tulosta @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown}/{n} tulosta. Kirjoita lisää rajataksesi tuloksia.|{shown}/{n} tulosta. Kirjoita lisää rajataksesi tuloksia. Recent Commands Viimeisimmät komennot @@ -4475,6 +4542,7 @@ font-technology Variable Muuttuvat The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Hiiren rulla vierittää piirtopintaa sivuttain, kun Cmd/Ctrl on painettuna. Dragging sideways on a numeric field's label changes the field's value. Numerokentän nimiön vetäminen sivuttain muuttaa kentän arvoa. A two-finger rotate gesture on a trackpad rotates the canvas view. Kahden sormen kiertoele kosketuslevyllä kiertää piirtopinnan näkymää. + When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Kun siirrät ankkuripisteitä, jokainen käyrä, jonka toinen pää siirtyy, säilyttää muotonsa suhteessa päihinsä. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Työkalun pikanäppäimen pitäminen painettuna valitsee työkalun, kunnes päästät irti, ja sitten edellinen työkalu valitaan uudelleen. Shows the bounding box while you move the selection or draw a shape. Näyttää rajausruudun, kun siirrät valintaa tai piirrät muotoa. Create Trim Marks draws Japanese-style marks instead of Roman ones. Luo leikkuumerkit piirtää japanilaistyyliset merkit roomalaisten sijaan. @@ -4505,6 +4573,29 @@ font-technology Variable Muuttuvat The unit for East Asian type measurements, which no field uses yet. Itä-Aasian tekstin mittojen yksikkö, jota mikään kenttä ei vielä käytä. When on, a number typed without a unit into a field in picas is read in points. Kun asetus on käytössä, picoina näytettävään kenttään ilman yksikköä kirjoitettu luku luetaan pisteinä. With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options. XML-tunnus-asetuksella objektien nimet näytetään XML-tunnuksina kohteissa Tasot, Muuttujat ja Tason asetukset. + The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl. Tekstin koon ja rivivälin askel: Cmd/Ctrl+Vaihto+. ja Cmd/Ctrl+Vaihto+, muuttavat kokoa yhden askeleen, Alt-näppäimen kanssa viisi; vaakasuuntaisessa tekstissä Alt ja ylä- tai alanuoli muuttavat riviväliä yhden askeleen, Cmd/Ctrl-näppäimen kanssa viisi. + The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl. Merkkivälin ja parivälistyksen askel em-yksikön tuhannesosina: vaakasuuntaisessa tekstissä Alt ja vasen tai oikea nuoli muuttavat kohdistimen kohdan parivälistystä tai valitun tekstin merkkiväliä yhden askeleen, Cmd/Ctrl-näppäimen kanssa viisi. + The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. Perusviivan siirron askel: vaakasuuntaisessa tekstissä Alt, vaihtonäppäin ja ylä- tai alanuoli siirtävät perusviivaa yhden askeleen, Cmd/Ctrl-näppäimen kanssa viisi. + Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. Näyttää japanin ja muiden Itä-Aasian kielten tekstin asetukset paneeleissa Merkki, Kappale, OpenType ja Merkit sekä komennon Yhdistelmäfontit. + Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. Näyttää arabian, heprean ja intialaisten kielten tekstin asetukset paneeleissa Merkki ja Kappale, kuten kappaleen suunnan, kashidat ja numerot. + The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. Valintatyökalut valitsevat tekstin vain sen perusviivalta, aluetekstin kehyksestä tai sen polulta, eivät mistä tahansa sen laatikon sisältä. + Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. Fonttivalikot näyttävät jokaisen fontin englanninkielisellä nimellä; pois päältä fontti, jolla on nimi myös omalla kielellään, näyttää sen nimen. + New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. Uusi aluetekstin kehys alkaa automaattinen koko päällä, joten vaakasuuntaisen tekstin suorakulmainen kehys kasvaa tai pienenee korkeudeltaan tekstinsä mukaan. + Font lists and the Type › Font menu show a sample of each font beside its name. Fonttiluettelot ja Fontti-valikko näyttävät jokaisen fontin näytteen sen nimen vieressä. + Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on. Fonttinäytteet piirretään tummalla tekstillä valkoiselle käyttöliittymän kirkkaudesta riippumatta; tämä koskee vain aikaa, jolloin valikkojen fonttiesikatselut ovat päällä. + How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is. Kuinka korkea kukin rivi on fonttikenttien luetteloissa, kuten Merkki-paneelin kentässä, ja siten kuinka suuri kukin näyte on. + How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first. Kuinka monta viimeksi käytettyä fonttia, 1–15, Viimeisimmät fontit ja fonttiluettelot näyttävät, uusin ensin. + When you change the font or font style of text, characters the new font has no glyph for keep the font they had. Kun vaihdat tekstin fontin tai fonttityylin, merkit, joille uudessa fontissa ei ole glyfiä, säilyttävät aiemman fonttinsa. + A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export. Vaaleanpunainen korostus piirtoalueella merkitsee glyfit, jotka OpenType-ominaisuudet ovat korvanneet, kuten ligatuurit; sitä ei tulosteta eikä viedä. + With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from. Tekstityökalulla yhden merkin valitseminen näyttää sen vieressä piirtoalueella rivin sen vaihtoehtoisia glyfejä valittavaksi. + A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export. Vaaleanpunainen korostus piirtoalueella merkitsee tekstin, joka piirretään korvaavalla fontilla, koska sen oma fontti puuttuu; sitä ei tulosteta eikä viedä. + New type made with a Type tool starts with placeholder text, selected, so typing replaces it. Tekstityökalulla luotu uusi teksti alkaa valitulla paikkamerkkitekstillä, jonka kirjoittaminen korvaa. + Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list. Luettelomerkin, kuten 1. tai *, ja sen jälkeen välilyönnin kirjoittaminen kappaleen alkuun tekee kappaleesta luettelon. + Fonts in this folder show in the font menus and can be used without being installed. Tämän kansion fontit näkyvät fonttivalikoissa, ja niitä voi käyttää asentamatta. + Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows. Grafiikkatyylin käyttäminen tekstiin poistaa merkkien oman täytön tai viivan, kun tyylissä on sellainen, joten tyylin väri näkyy. + Align and Distribute measure point type by the ink of its glyphs instead of its em box. Tasaa ja Jaa mittaavat pistetekstin sen glyfien musteen mukaan eivätkä sen em-laatikon mukaan. + Align and Distribute measure area type by the ink of its glyphs instead of its frame. Tasaa ja Jaa mittaavat aluetekstin sen glyfien musteen mukaan eivätkä sen kehyksen mukaan. + The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box. Rajausruutu ja Muunna-paneeli mittaavat pistetekstin sen glyfien musteen mukaan eivätkä sen em-laatikon mukaan. Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply. Kohdistaa piirtämisen, siirtämisen ja skaalaamisen ruudukon jakoihin myös silloin, kun ruudukko on piilossa; kun asetus on päällä, Kohdista pikseliin ei ole käytössä. The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead. Valitsemattomien apuviivojen väri; piirtoalusta, jolla on apuviivojen tunniste, piirtää omat apuviivansa tunnisteen värillä. Draws guides as solid lines or as dots, including the guides already in the document. Piirtää apuviivat yhtenäisinä viivoina tai pisteinä, myös asiakirjassa jo olevat apuviivat. @@ -4548,6 +4639,8 @@ font-technology Variable Muuttuvat Couldn't paste from the clipboard: {e} Leikepöydältä ei voitu liittää: {e} Channel Kanava Circle Ympyrä + Circle Tool Ympyrätyökalu + Circle too large Ympyrä on liian suuri Clip to Art Rajaa kuvitukseen Colorize Väritä Gamma Gamma @@ -4777,6 +4870,13 @@ imageTrace Outline Ääriviiva Show External Script Warning Näytä ulkoisten komentosarjojen varoitus A Script Is Running Komentosarja on käynnissä Script Alert Komentosarjan ilmoitus + Script File Access Komentosarjan tiedostojen käyttö + The script asks to read a file you choose. Komentosarja pyytää lupaa lukea valitsemasi tiedoston. + The script asks to read and write a file you choose. Komentosarja pyytää lupaa lukea ja kirjoittaa valitsemasi tiedoston. + The script asks to read and write a folder you choose, with everything in it. Komentosarja pyytää lupaa lukea ja kirjoittaa valitsemasi kansion ja kaiken sen sisällön. + Allow Once Salli kerran + Always Allow This Script Salli tämä komentosarja aina + Deny Estä A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Komentosarja voi muuttaa avoimia asiakirjoja ja kirjoittaa tiedostoja suorittamillaan komennoilla. Suorita vain komentosarjoja, joihin luotat. Do not show this warning again Älä näytä tätä varoitusta uudelleen Stop the script and undo what it did? Then quit again. Pysäytetäänkö komentosarja ja kumotaan sen muutokset? Lopeta sitten uudelleen. @@ -4793,6 +4893,8 @@ imageTrace Outline Ääriviiva @msg the script is no longer in the Scripts folder komentosarja ei ole enää Scripts-kansiossa Some scripts were not listed Kaikkia komentosarjoja ei ole lueteltu The Scripts folder cannot be read Scripts-kansiota ei voi lukea + Loading scripts… Ladataan komentosarjoja… + The Scripts folder is still being read Scripts-kansiota luetaan vielä @msg the script's run is no longer available komentosarjan suoritus ei ole enää käytettävissä @msg a failed command changed undo steps that could not be put back, so the script was stopped epäonnistunut komento muutti kumoamisvaiheita, joita ei voitu palauttaa, joten komentosarja pysäytettiin @msg a recovery copy could not be written, so the script was not run palautuskopiota ei voitu kirjoittaa, joten komentosarjaa ei suoritettu @@ -4805,8 +4907,6 @@ imageTrace Outline Ääriviiva @msg Script file could not be read Komentosarjatiedostoa ei voitu lukea @msg Script folder has more than 2,048 entries Komentosarjakansiossa on yli 2 048 kohdetta @msg Script file open mode must be r, w, e or a Komentosarjatiedoston avaustilan on oltava r, w, e tai a -@msg Script file writing is not available Komentosarjatiedostojen kirjoittaminen ei ole käytettävissä -@msg Script file dialogs are not available Komentosarjojen tiedostovalintaikkunat eivät ole käytettävissä @msg Script files cannot be opened in another application Komentosarjatiedostoja ei voi avata toisessa sovelluksessa @msg Script file access is unavailable on the web Komentosarjatiedostojen käyttö ei ole mahdollista verkossa @msg Script has 256 files open Komentosarjalla on 256 tiedostoa auki @@ -4945,8 +5045,37 @@ liquify-list-end {0}, {1} {0} ja {1} @msg is a prompt's answer, whose `value` must be a string or null on prompt-vastaus, joten sen `value`-arvon on oltava merkkijono tai null @msg must have `kind` alert, confirm or prompt `kind`-arvon on oltava alert, confirm tai prompt @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` on vain ajolle, jossa ei ole ketään kysyttävää: sovelluksessa henkilö vastaa jokaiseen valintaikkunaan +@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` on oltava kokonaisluku väliltä 1–{_1} +@msg `args{place}` is nested more than 64 levels deep `args{place}` on sisäkkäin yli 64 tason syvyydellä +@msg `args` must be an object `args` on oltava objekti +@msg `args` is larger than 1 MiB `args` on suurempi kuin 1 MiB +@msg `path` is empty `path` on tyhjä +@msg `installed` takes a `path`, not a `source` `installed` ottaa `path`-arvon, ei `source`-arvoa +@msg `path` must name a .js or .jsx file `path` on oltava .js- tai .jsx-tiedosto +@msg give exactly one of `path` and `source` anna tasan yksi arvoista `path` ja `source` @msg Running a script Suoritetaan komentosarjaa @msg Copied the script report Komentosarjan raportti kopioitiin +@msg Script file access denied: {path} Komentosarjan tiedostojen käyttö estettiin: {path} +@msg Script file access to the app's own folders is not allowed Komentosarjat eivät saa käyttää sovelluksen omia kansioita +@msg Script file cannot encode the text Komentosarjan tiedosto ei voi koodata tekstiä +@msg Script file could not be written Komentosarjan tiedostoa ei voitu kirjoittaa +@msg Script file dialogs need a person to answer them Komentosarjan tiedostovalintaikkunoihin tarvitaan vastaava henkilö +@msg Script file is not open for writing Komentosarjan tiedosto ei ole auki kirjoittamista varten +@msg Script file name is already in use Komentosarjan tiedoston nimi on jo käytössä +@msg Script file name must be a name without a folder Komentosarjan tiedoston nimen on oltava nimi ilman kansiota +@msg Script file permission can be kept only for a script run from a file Tiedostolupa voidaan säilyttää vain tiedostosta suoritetulle komentosarjalle +@msg Script file permission could not be saved Komentosarjan tiedostolupaa ei voitu tallentaa +@msg Script folder is not empty Komentosarjan kansio ei ole tyhjä +@msg Script files cannot make aliases Komentosarjan tiedostot eivät voi luoda aliaksia +@msg Script file hidden setting cannot be changed Komentosarjan tiedoston piilotusasetusta ei voi muuttaa +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: tiedostovalintaikkunaa ei voi avata sisäänrakennetun funktion, getterin, muunnoksen tai $.evalFile-funktion suorittaman tiedoston takaisinkutsussa; kutsu sitä komentosarjan omasta koodista +@msg the script wrote more file data than one run may write (32 MiB) komentosarja kirjoitti enemmän tiedostodataa kuin yksi suoritus saa kirjoittaa (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop komentosarjan tiedostovalintaikkunan `answer`-arvon on oltava jokin seuraavista: once, always, deny, stop +@msg choose a file or folder first, or deny valitse ensin tiedosto tai kansio tai estä +@msg the script file permissions could not be saved: {e} komentosarjojen tiedostolupia ei voitu tallentaa: {e} +@msg this script's file access can be allowed only once tämän komentosarjan tiedostojen käytön voi sallia vain kerran +@msg Only the person at the keyboard can allow a script's file access Vain näppäimistön ääressä oleva ihminen voi sallia komentosarjan tiedostojen käytön +@msg A script is given at most 2,048 files: the files picked after them were left out Komentosarja saa enintään 2 048 tiedostoa: niiden jälkeen valitut tiedostot jätettiin pois @msg Copied the link info Linkin tiedot kopioitiin @msg Corners edits the corners of a path Kulmat-toiminto muokkaa polun kulmia @msg Couldn't copy to the system clipboard: {e} Järjestelmän leikepöydälle ei voitu kopioida: {e} @@ -5022,6 +5151,7 @@ liquify-list-end {0}, {1} {0} ja {1} @msg Saved {path} Tallennettiin {path} @msg Select text or click into text with the Type tool to insert glyphs Valitse tekstiä tai napsauta tekstiin tekstityökalulla, niin voit lisätä merkkejä @msg Shape Builder: no region under the pointer Muodonmuodostin: osoittimen alla ei ole aluetta +@msg Shape Builder: select all paths you want to merge Muodonmuodostin: valitse kaikki polut, jotka haluat yhdistää @msg Shape Builder: select paths or compound paths Muodonmuodostin: valitse polkuja tai yhdistelmäpolkuja @msg Show All Hidden Attributes: nothing is hidden Näytä kaikki piilotetut attribuutit: mitään ei ole piilotettu @msg Split Into Grid: select paths large enough for the grid Jaa ruudukoksi: valitse ruudukolle riittävän suuret polut @@ -5156,6 +5286,7 @@ liquify-list-end {0}, {1} {0} ja {1} @msg bad trailer virheellinen trailer @msg balance must be between 0 and 100 balance-arvon on oltava väliltä 0–100 @msg batch step {_1} (`{id}`) failed: {e} erävaihe {_1} (`{id}`) epäonnistui: {e} +@msg action step {_1} (`{id}`) failed: {reason} toiminnon vaihe {_1} (`{id}`) epäonnistui: {reason} @msg brightness must be dark|mediumDark|mediumLight|light brightness-arvon on oltava dark|mediumDark|mediumLight|light @msg can't encode the document: {0} asiakirjaa ei voi koodata: {0} @msg can't parse shortcut `{c}` pikanäppäintä `{c}` ei voi jäsentää @@ -5175,6 +5306,7 @@ liquify-list-end {0}, {1} {0} ja {1} @msg choose a folder to export to valitse kansio, johon viedään @msg choose a location for the package valitse paketin sijainti @msg clipboard is empty leikepöytä on tyhjä +@msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: väritaulukkoon on jäätävä vähintään yksi väri @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` ei ole väri, kuten "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: enintään {MAX_TABLE} väriä @msg command `{0}` is not available right now: {1} komento `{0}` ei ole nyt käytettävissä: {1} @@ -5242,9 +5374,15 @@ liquify-list-end {0}, {1} {0} ja {1} @msg no PNG encoder ei PNG-kooderia @msg no active document ei aktiivista asiakirjaa @msg no active perspective plane ei aktiivista perspektiivitasoa +@msg the perspective grid is hidden perspektiiviruudukko on piilotettu +@msg Automatic Plane Positioning is off: turn on anchorPoint or gridlineIntersection (perspective.widget.options) Tason automaattinen sijoittaminen on pois päältä: ota käyttöön anchorPoint tai gridlineIntersection (perspective.widget.options) +@msg anchorPoint must be true or false anchorPoint-arvon on oltava true tai false +@msg gridlineIntersection must be true or false gridlineIntersection-arvon on oltava true tai false +@msg tolerance must be 0 or more tolerance-arvon on oltava 0 tai enemmän +@msg give `at` or `clear`, not both anna `at` tai `clear`, ei molempia @msg no anchor points selected ankkuripisteitä ei ole valittu -@msg `points` must be three [x, y] pairs of numbers `points` on annettava kolmena lukuparina [x, y] -@msg direct-select three anchor points, or give `points` valitse suoraan kolme ankkuripistettä tai anna `points` +@msg `points` must be two or three [x, y] pairs of numbers `points` on annettava kahtena tai kolmena lukuparina [x, y] +@msg direct-select two or three anchor points, or give `points` valitse suoraan kaksi tai kolme ankkuripistettä tai anna `points` @msg no circle passes through these points: two are the same or all three lie on one line näiden pisteiden kautta ei kulje ympyrää: kaksi pisteistä on samoja tai kaikki kolme ovat samalla suoralla @msg no app to open files here täällä ei ole sovellusta tiedostojen avaamiseen @msg no artboard ei piirtoalustaa @@ -5346,12 +5484,17 @@ liquify-list-end {0}, {1} {0} ja {1} @msg no such user library käyttäjäkirjastoa ei ole @msg no such view näkymää ei ole @msg no such width point leveyspistettä ei ole +@msg `single` must be `incoming` or `outgoing` `single` on oltava `incoming` tai `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` ja `outIndex` on oltava saman epäjatkuvan leveyspisteen kaksi puolikasta +@msg a discontinuous width point keeps its place epäjatkuva leveyspiste pysyy paikallaan @msg no swatch `{name}` ei värimallia `{name}` @msg no swatch library `{l}` (see swatch.library.list) ei värimallikirjastoa `{l}` (ks. swatch.library.list) @msg no symbol instances selected symboli-ilmentymiä ei ole valittu @msg no target object has an opacity mask: select one or give `id` millään kohdeobjektilla ei ole peittävyysmaskia: valitse sellainen tai anna `id` @msg no threaded text selected ketjutettua tekstiä ei ole valittu @msg no user library folder here täällä ei ole käyttäjäkirjastokansiota +@msg `{file}` has no swatches of its own tiedostossa `{file}` ei ole omia värimalleja +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold kirjastossa `{_1}` on kuviomalleja, joita .vcswatches-tiedosto ei voi sisältää @msg no user workspace `{from}` ei käyttäjän työtilaa `{from}` @msg node {_1} is not text solmu {_1} ei ole tekstiä @msg node {_1} is on a locked artboard solmu {_1} on lukitulla piirtoalustalla @@ -5599,6 +5742,13 @@ liquify-list-end {0}, {1} {0} ja {1} @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} yli {MAX_CSV_ROWS} tietojoukkoa: Tuo tietojoukot lukee enintään {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} yli {MAX_CSV_COLS} muuttujaa: Tuo tietojoukot lukee enintään {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} muut kuin tekstimuuttujat jätettiin pois: {kinds} +variable-kind Visibility Näkyvyys +variable-kind Linked File Linkitetty tiedosto +variable-kind Graph Data Kaavion tiedot +variable-kind Unknown Tuntematon +variable-list-two {0}, {1} {0} ja {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} ja {1} @msg a new document won't read these variables back with their kind: {names} uusi asiakirja ei lue näitä muuttujia takaisin niiden lajin mukaisina: {names} @msg a new document refuses this file because of these variables: {names} uusi asiakirja hylkää tämän tiedoston näiden muuttujien vuoksi: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them muuttujan `{name}` otsikko `{header}` luettaisiin muuttujaksi `{other}`: nimeä toinen niistä uudelleen @@ -5624,6 +5774,8 @@ liquify-list-end {0}, {1} {0} ja {1} @msg {label}: lost track of a shape's style {label}: muodon tyyli kadotettiin @msg {label}: select paths {label}: valitse polkuja @msg {label}: select paths, compound paths, groups or text {label}: valitse polkuja, yhdistelmäpolkuja, ryhmiä tai tekstiä +@msg a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first viiva tai muu avoin polku, joka ei rajaa aluetta, ei muuta tuloksen muotoa; jos haluat sisällyttää sen, käytä siihen ensin komentoa Objekti › Polku › Ääriviivaa viiva +@msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first {label} tuotti tyhjän tuloksen: viiva tai muu avoin polku ei rajaa aluetta; jos haluat sisällyttää sen, käytä siihen ensin komentoa Objekti › Polku › Ääriviivaa viiva @msg {label}… {label}… @msg {name}: CRC mismatch {name}: CRC ei täsmää @msg {name}: no local header {name}: ei paikallista otsaketta @@ -5650,6 +5802,9 @@ liquify-list-end {0}, {1} {0} ja {1} @msgplural Discarded {n} recovered document|Discarded {n} recovered documents Hylättiin {n} palautettu asiakirja|Hylättiin {n} palautettua asiakirjaa @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them Palautettiin {n} asiakirja: tallenna se säilyttääksesi sen|Palautettiin {n} asiakirjaa: tallenna ne säilyttääksesi ne @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} Avattiin, {n} huomautus: {first}|Avattiin, {n} huomautusta: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Kopioitiin, {n} huomautus: {first}|Kopioitiin, {n} huomautusta: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Leikattiin, {n} huomautus: {first}|Leikattiin, {n} huomautusta: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Kuva jäljitettiin, {n} huomautus: {first}|Kuva jäljitettiin, {n} huomautusta: {first} @msgplural {notice}. Opened with {n} note: {first}|{notice}. Opened with {n} notes: {first} {notice}. Avattiin, {n} huomautus: {first}|{notice}. Avattiin, {n} huomautusta: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} Tallennettiin {path}, {n} huomautus: {first}|Tallennettiin {path}, {n} huomautusta: {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first Upotettiin {n} kuva; {missing} puuttuu: linkitä ne ensin uudelleen|Upotettiin {n} kuvaa; {missing} puuttuu: linkitä ne ensin uudelleen @@ -5676,6 +5831,8 @@ liquify-list-end {0}, {1} {0} ja {1} @msg All colors are within the CMYK gamut Kaikki värit ovat CMYK-väriavaruuden sisällä @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} väri on CMYK-väriavaruuden ulkopuolella|{n} väriä on CMYK-väriavaruuden ulkopuolella @msg Unembedded to {_1} Upotus purettiin kohteeseen {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} Upotus purettiin {n} kuvalta kohteeseen {folder}|Upotus purettiin {n} kuvalta kohteeseen {folder} +@msg every numbered name for {name} is taken in that folder kaikki kohteen {name} numeroidut nimet ovat jo käytössä siinä kansiossa @msg Reset {_1} Palautettiin oletukseksi {_1} @msg Sent to {_1} Lähetettiin kohteeseen {_1} @msg {_1} files {_1}-tiedostot @@ -5691,6 +5848,8 @@ liquify-list-end {0}, {1} {0} ja {1} @msg Reload the page to go on (changes not saved yet may be lost). Lataa sivu uudelleen jatkaaksesi (tallentamattomat muutokset voivat kadota). @msg tool (a tool id) is required tool (työkalun tunnus) vaaditaan @msg {tool} isn't in a toolbar group of several tools {tool} ei ole usean työkalun työkaluriviryhmässä +@msg Presentation Mode hides the toolbars: change the screen mode to show them Esitystila piilottaa työkalurivit: tuo ne näkyviin vaihtamalla näyttötilaa +@msg Tab has hidden the toolbars: press Tab to show them Tab on piilottanut työkalurivit: tuo ne näkyviin painamalla Tab-näppäintä @msg onto must name a panel floating in another group onto-arvon on nimettävä toisessa ryhmässä kelluva paneeli @msg below and above must name a panel floating in another group below- ja above-arvojen on nimettävä toisessa ryhmässä kelluva paneeli @msg give only one of onto, below and above anna vain yksi arvoista onto, below ja above @@ -5779,6 +5938,9 @@ liquify-list-end {0}, {1} {0} ja {1} @msg automation path rejected: outside the read root {root}: {path} automaation polku hylättiin: lukujuuren {root} ulkopuolella: {path} @msg automation path rejected: outside the read roots {roots}: {path} automaation polku hylättiin: lukujuurten {roots} ulkopuolella: {path} @msg a linked JavaScript file is outside the read roots linkitetty JavaScript-tiedosto on lukujuurten ulkopuolella +@msg a linked image file is outside the read roots linkitetty kuvatiedosto on lukujuurten ulkopuolella +@msg a linked file's export folder is outside the read roots linkitetyn tiedoston vientikansio on lukujuurten ulkopuolella +@msg a linked file's editing data can't be read to check it against the read roots linkitetyn tiedoston muokkaustietoja ei voi lukea niiden tarkistamiseksi lukujuuria vasten @msg the library's file is outside the read roots kirjaston tiedosto on lukujuurten ulkopuolella @msg {file} names more than one linked JavaScript file {file} vastaa useampaa kuin yhtä linkitettyä JavaScript-tiedostoa @msg automation path rejected: outside the write root {root}: {path} automaation polku hylättiin: kirjoitusjuuren {root} ulkopuolella: {path} @@ -6058,6 +6220,7 @@ liquify-list-end {0}, {1} {0} ja {1} Ascent Nousu Cap Height Versaalikorkeus x Height x-korkeus + Em Box Height Em-laatikon korkeus Justify Tasaa molemmat reunat First Baseline Ensimmäinen perusviiva Vertical Align Pystytasaus @@ -6191,6 +6354,7 @@ mark-style Japanese Japanilainen Cove Kouru Depth Syvyys Front Edestä + Side Sivulta Isometric Bottom Isometrinen ala Isometric Left Isometrinen vasen Isometric Right Isometrinen oikea @@ -6286,7 +6450,7 @@ mark-style Japanese Japanilainen @msg each of `{GRAPHICS}` must be an object jokaisen `{GRAPHICS}`-kohteen on oltava objekti @msg `{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}` `{GRAPHICS}`-kohteet hyväksyvät arvot symbol, face, x, y, scale ja rotation, eivät arvoa `{k}` @msg each of `{GRAPHICS}` needs `symbol`, the name of a symbol jokainen `{GRAPHICS}`-kohde tarvitsee arvon `symbol`, symbolin nimen -@msg `{GRAPHICS}` face must be front or back `{GRAPHICS}`-kohteen face-arvon on oltava front tai back +@msg `{GRAPHICS}` face must be front, back or side `{GRAPHICS}`-kohteen face-arvon on oltava front, back tai side @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} `{GRAPHICS}`-kohteen {key}-arvon on oltava luku, joka on vähintään {lo} ja enintään {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` on oltava taulukko @msg Graphics map onto the Plane, Extrude and Revolve object types Grafiikat sijoitetaan objektityypeille Taso, Pursota ja Pyöräytä @@ -6468,6 +6632,8 @@ mark-style Japanese Japanilainen Reset Horizontal Scale Palauta vaakaskaalaus Reset Tracking and Kerning Palauta merkkiväli ja parivälistys Highlight Font Name Korosta fontin nimi + Highlight Font Size Korosta fonttikoko + Other… Muu… Highlight Kerning Korosta parivälistys Highlight Tracking Korosta merkkiväli Sample Color from Screen Poimi väri näytöltä @@ -6509,6 +6675,8 @@ mark-style Japanese Japanilainen @msg Unknown dimension option {k} Tuntematon mitoitusasetus {k} @msg Unknown dimension orientation Tuntematon mitan suunta @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode`-arvon on oltava grayscale, rgb, hsb, cmyk tai websafe +@msg `view` must be wheel or box `view`-arvon on oltava wheel tai box +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel`-arvon on oltava hue, saturation, brightness, red, green tai blue @msg `{key}` must be an array of these names: {_1} `{key}`-arvon on oltava taulukko, jossa on näitä nimiä: {_1} @msg choose a destination folder valitse kohdekansio @msg choose a source folder valitse lähdekansio @@ -6689,6 +6857,11 @@ mark-style Japanese Japanilainen Edge Only Vain reunat Overlay Edge Reunat päällä Path Length Polun pituus + Grid Size Ruudukon koko + Grid Colors Ruudukon värit + Flattener Preset Litistyksen esiasetus + X X + Y Y swatch [None] [Ei mitään] swatch [Registration] [Kohdistus] swatch White Valkoinen @@ -7439,6 +7612,12 @@ anchor Points: Pisteet: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` on oltava "free", "keepAngles" tai "symmetric" @msg `{key}` must be [x, y] `{key}` on oltava [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Yksikkömuunnin + Unit Converter Panel Yksikkömuunnin-paneeli + Copy with Units Kopioi yksiköineen + From Selection Valinnasta + # Color Effects add-on: Select by Color Kind. Select by Color Kind Valitse värityypin mukaan Objects with Spot Colors Objektit, joissa on spottivärejä @@ -7663,6 +7842,14 @@ breakText Glyphs Merkit Remove Gaps Poista välit @msg that makes too many pieces (at most 100000): make the dashes longer siitä tulee liian monta osaa (enintään 100000): pidennä viivoja @msg select paths, or segments, to divide valitse jaettavat polut tai segmentit +# Path Precision Tools add-on: Smooth Bridge. + Smooth Bridge… Pehmeä silta… + Smooth Bridge Pehmeä silta + Keep Originals Säilytä alkuperäiset +@msg select two circles to bridge valitse kaksi yhdistettävää ympyrää +@msg one circle is inside the other toinen ympyrä on toisen sisällä +@msg the circles are too far apart for this radius: raise the radius ympyrät ovat liian kaukana toisistaan tälle säteelle: suurenna sädettä +@msg the circles are too far apart for this radius ympyrät ovat liian kaukana toisistaan tälle säteelle # Path Precision Tools add-on: Common Tangents. Common Tangents… Yhteiset tangentit… Common Tangents Yhteiset tangentit @@ -8182,4 +8369,15 @@ breakText Glyphs Merkit @msg A panel is not joined to the rest by a crease. Paneelia ei ole liitetty muihin millään nuuttausviivalla. @msg A fold line is on a non-printing layer. Taittoviiva on tasolla, jota ei tulosteta. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneelit: {panels}, saranat: {hinges}, virheet: {errors}, varoitukset: {warnings} + Fold Preview Taiton esikatselu + Fold Taitto + Show Fold Lines Näytä taittoviivat + Three-Quarter Kolme neljäsosaa + Open a document to preview its folded shape. Avaa asiakirja, niin voit esikatsella sen taitettua muotoa. +@msg Check the fold lines first. Tarkista ensin taittoviivat. +@msg Panels: {panels}, hinges: {hinges} Paneelit: {panels}, saranat: {hinges} +@msg Other blanks not shown: {count} Muita aihioita ei näytetä: {count} +@msg A joint does not close by {gap} pt. Liitos ei sulkeudu, rako {gap} pt. +@msg Two panels pass through each other. Kaksi paneelia kulkee toistensa läpi. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer on oltava "singleLine", "everyLine", "standardSingleLine" tai "standardEveryLine" +@msg text.{key} `{v}`: use "{_1}" or "{_2}" text.{key} `{v}`: käytä arvoa "{_1}" tai "{_2}" diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 3be3497f97..c8b973b692 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -12,7 +12,7 @@ # Coverage: the whole interface — every menu string and every `tl!` literal (`complete_menus`, # `untranslated_report` lists gaps). Left in English on purpose (`MENU_KEEP_AS_IS` in the tests): the product name, language # names, OpenType, the built-in workspace names and the bracketed perspective grid preset names. -# Photoshop-style raster effects (Effect menu, their dialogs). +# Raster effects (Effect menu, their dialogs). Glowing Edges… Contour lumineux… Glowing Edges Contour lumineux Edge Width Largeur du bord @@ -120,6 +120,7 @@ Add Anchor Point Ajouter un point d’ancrage Add Anchor Point Tool Outil Ajout de point d’ancrage Add Anchor Points Ajouter des points d’ancrage + Add Around Ajouter autour de l’objet Add Effect Ajouter un effet Add Freeform Line Ajouter une ligne libre Add Freeform Point Ajouter un point libre @@ -141,8 +142,12 @@ Add to Swatches Ajouter au nuancier Add Used Colors Ajouter les couleurs utilisées Additional Plug-ins Folder Dossier de modules externes supplémentaires + Plug-in Instruction Budget Budget d’instructions des modules externes Additional Fonts Folder Dossier de polices supplémentaires Adjust Adjoining Width Points Ajuster les points de largeur adjacents + Incoming Entrant + Outgoing Sortant + Single Width Only Une seule largeur Adjust Color Balance… Régler la balance des couleurs… Adjust Colors Régler les couleurs Adjust Options: Options de réglage : @@ -197,6 +202,7 @@ Angle: Angle : Angles Angles Animated Zoom Zoom animé + Anti Alias Lissage Anti-alias Lissage Anti-Alias Lissage Anti-alias Rasters Lisser les images pixellisées @@ -362,6 +368,12 @@ font-technology Variable Variables Brush Definition Définition de la forme Brush Libraries Bibliothèques de formes Brush Options… Options de forme… + Options of Selected Object… Options de l’objet sélectionné… + Options of Selected Object Options de l’objet sélectionné +@msg no path painted with a brush is selected aucun tracé peint avec une forme n’est sélectionné +@msg the selected paths are painted with brushes of different types les tracés sélectionnés sont peints avec des formes de types différents +@msg give `params` or `reset`, not both indiquez `params` ou `reset`, pas les deux +@msg a bristle brush has no options of its own on a path une forme Soies n’a pas d’options propres sur un tracé Brush Strokes Contours de forme Brushes Formes Built-in Libraries Bibliothèques intégrées @@ -418,6 +430,12 @@ font-technology Variable Variables Character Alignment Alignement des caractères Character / Paragraph Caractère / Paragraphe Character Rotation Rotation des caractères + Chinese Big 5 Chinois Big 5 + Cyrillic Cyrillique + Greek Grec + Turkish Turc + Baltic Balte + Central European Europe centrale Character Set: Jeu de caractères : Character Style Style de caractère Character Style Options Options de style de caractère @@ -480,6 +498,8 @@ font-technology Variable Variables Choose a folder Choisissez un dossier Choose… Choisir… Circle Cercle + Circle Tool Outil Cercle + Circle too large Cercle trop grand Classic Defaults Valeurs par défaut classiques Clean Up… Nettoyer… Clear Effacer @@ -555,6 +575,7 @@ font-technology Variable Variables Color Mixer (Shift-click the chip) Mélangeur de couleurs (Maj+clic sur la vignette) Color Mode Mode colorimétrique Color Mode: Mode colorimétrique : + Color Model Modèle colorimétrique Color Model: Modèle colorimétrique : Color Models Modèles colorimétriques Color Picker Sélecteur de couleurs @@ -575,12 +596,18 @@ font-technology Variable Variables Saturation and brightness Saturation et luminosité Color field Champ de couleur {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Affichage roue + Box View Affichage carré + Box Channel Couche du carré + Color box Carré de couleur + Color Wheel Options Options de la roue chromatique Color Type: Type de couleur : Color: Couleur : Colorize Coloriser Colors Couleurs Colors: Couleurs : Column Graph Tool Outil Graphe à barres verticales + Columns Colonnes Columns: Colonnes : Column… Colonne… Combine Slices Combiner les tranches @@ -792,6 +819,8 @@ font-technology Variable Variables Delete Artboard Supprimer le plan de travail Delete Artboards Supprimer les plans de travail Delete Brush Supprimer la forme + Delete Color Supprimer la couleur + Restore Generated Table Restaurer la table générée Delete Character Style Supprimer le style de caractère Delete Empty Artboards Supprimer les plans de travail vides Delete Freeform Point Supprimer le point libre @@ -861,6 +890,7 @@ font-technology Variable Variables Direct Selection Tool Outil Sélection directe Direction Handles Poignées de direction Disable Auto Add/Delete Désactiver l’ajout/suppression automatique + Interpolate Control Points When Moving Anchors Interpoler les poignées de direction lors du déplacement des points d’ancrage Disable Opacity Mask Désactiver le masque d’opacité Discard Ignorer Discard Empty Type Supprimer le texte vide @@ -1065,6 +1095,7 @@ font-technology Variable Variables Enable text access for screen readers Autoriser l’accès au texte pour les lecteurs d’écran Enable Touch Gestures Activer les gestes tactiles Switch Selection and Drawing Modes Basculer entre les modes sélection et dessin + Select Last Selection Tool Choisir le dernier outil de sélection Enable Touch Workspace Activer l’espace de travail tactile Encoding Codage Encoding: Codage : @@ -1247,6 +1278,8 @@ font-technology Variable Variables Files Fichiers Files of a PDF standard can't be password-protected. Les fichiers conformes à une norme PDF ne peuvent pas être protégés par mot de passe. Files of this standard tag their colours with ICC profiles. Les fichiers conformes à cette norme balisent leurs couleurs avec des profils ICC. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Les fichiers conformes à cette norme balisent leurs couleurs avec des profils ICC, sauf les couleurs CMJN du profil du mode de sortie, qui sont écrites en DeviceCMYK. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. Avec l’option Ne pas inclure les profils et un mode de sortie CMJN, chaque couleur CMJN est écrite en DeviceCMYK, sauf si elle est convertie vers une destination CMJN d’un autre profil. Fill Fond Fill & Stroke Fond et contour Fill (X), double-click for the Color Picker Fond (X), double-cliquez pour ouvrir le Sélecteur de couleurs @@ -1295,6 +1328,8 @@ font-technology Variable Variables Reset Tracking and Kerning Réinitialiser l’approche et le crénage Reset Horizontal Scale Réinitialiser la mise à l’échelle horizontale Highlight Font Name Surligner le nom de la police + Highlight Font Size Surligner la taille de police + Other… Autre… Highlight Kerning Surligner le crénage Highlight Tracking Surligner l’approche Spacing Espacement @@ -2020,6 +2055,7 @@ font-technology Variable Variables Load SVG into Clipboard Charger un SVG dans le presse-papiers Load Text into Clipboard Charger du texte dans le presse-papiers Local Libraries Bibliothèques locales + Locate Layer Localiser le calque Locate Object Localiser l’objet Locate Selected Objects Localiser les objets sélectionnés Location Emplacement @@ -2214,6 +2250,7 @@ font-technology Variable Variables Scatter: Dispersion : Rotation: Rotation : Rotation relative to: Rotation par rapport à : + Hue Jitter: Variation de teinte : Brush Scale Options Options de mise à l’échelle de la forme Scale Proportionately Mettre à l’échelle proportionnellement Stretch to Fit Stroke Length Étirer selon la longueur du contour @@ -2250,6 +2287,7 @@ font-technology Variable Variables Black and white stay as they are. Dark colors become shades of the stroke color and light colors become tints of it. Le noir reste noir et le blanc reste blanc. Les autres couleurs deviennent des ombres de la couleur du contour quand elles sont foncées et des teintes de celle-ci quand elles sont claires. The key color becomes the stroke color. The other colors shift their hue by the same amount and keep their saturation and brightness. La couleur clé devient la couleur du contour. Les autres couleurs tournent sur le cercle chromatique autant que la couleur clé et gardent leur saturation et leur luminosité. Key Color: Couleur clé : + Roundness Arrondi Roundness: Arrondi : Fixed Fixe Pressure Pression @@ -2555,6 +2593,9 @@ font-technology Variable Variables Overprint Surimpression Overprint and Transparency Flattener Surimpression et aplatissement des transparences Overprint and Transparency Flattener Options Options de surimpression et d’aplatissement des transparences + Custom… Personnalisé… + Custom Transparency Flattener Options Options personnalisées d’aplatissement des transparences + EPS has no alpha transparency, and Overprints sets whether overprints are kept. Le format EPS n’a pas de transparence alpha, et Surimpressions détermine si les surimpressions sont conservées. Overprint Black… Surimpression du noir… Overprint Fill Surimpression du fond Overprint Preview Aperçu de la surimpression @@ -2604,6 +2645,11 @@ font-technology Variable Variables Pathfinders: Pathfinders : Paths Tracés Path Length Longueur des tracés + Grid Size Taille de la grille + Grid Colors Couleurs de la grille + Flattener Preset Paramètre prédéfini d’aplatissement + X X + Y Y Paths: {paths} Anchors: {anchors} Colors: {colors} Tracés : {paths} Points d’ancrage : {anchors} Couleurs : {colors} Pattern Motif Pattern Editing Modification du motif @@ -2661,6 +2707,7 @@ font-technology Variable Variables Play Current Selection Exécuter la sélection actuelle Save Actions… Enregistrer les scripts… Load Actions… Charger des scripts… + Replace Actions… Remplacer les scripts… Reset Actions Réinitialiser les scripts Replace the current actions with the default set? Remplacer les scripts actuels par le jeu par défaut ? Append adds the default set after the current sets instead. Le bouton Ajouter ajoute plutôt le jeu par défaut après les jeux actuels. @@ -2676,6 +2723,10 @@ font-technology Variable Variables Polar Grid Tool Outil Grille à coordonnées polaires Polygon Polygone Polygon Properties: Propriétés du polygone : + Line Properties: Propriétés de la ligne : + Line Length: Longueur de la ligne : + Line Angle: Angle de la ligne : + Constrain Pie Angle Conserver l’angle du secteur Polygon Tool Outil Polygone Portrait Portrait Power Saving (integrated) Économie d’énergie (intégrée) @@ -2835,6 +2886,9 @@ digits Malayalam Malayalam Real World: Monde réel : Real-time Drawing and Editing Dessin et édition en temps réel Use Monitor Profile for Canvas Utiliser le profil du moniteur pour la zone de travail + Refresh Monitor Profile Actualiser le profil du moniteur +@msg turn on Use Monitor Profile for Canvas first activez d’abord « Utiliser le profil du moniteur pour la zone de travail » +@msg this build doesn't read display profiles cette version ne lit pas les profils d’affichage The canvas is drawn in sRGB. La zone de travail est affichée en sRGB. Canvas display profile: Profil d’affichage de la zone de travail : The system matches the window to the display's colors. Le système adapte la fenêtre aux couleurs de l’écran. @@ -3027,6 +3081,8 @@ digits Malayalam Malayalam Reselect Resélectionner Reset Réinitialiser Reset Bounding Box Réinitialiser le cadre de sélection + Rotate Bounding Box Faire pivoter le cadre de sélection + Rotate Bounding Box… Faire pivoter le cadre de sélection… Reset Envelope Mesh Réinitialiser le filet de l’enveloppe Reset Envelope Shape Réinitialiser la forme de l’enveloppe Reset Essentials Réinitialiser Essentials @@ -3067,6 +3123,7 @@ digits Malayalam Malayalam Reshape Segment Modeler le segment Reshape Tool Outil Modelage Reshape Type Area Modeler la zone de texte + Resolution Résolution Resolution: Résolution : Responsive Adaptatif Restore Restaurer @@ -3093,6 +3150,7 @@ digits Malayalam Malayalam The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. La molette de la souris avec Cmd/Ctrl enfoncée fait défiler la zone de travail latéralement. Dragging sideways on a numeric field's label changes the field's value. Faire glisser latéralement le libellé d’un champ numérique modifie la valeur du champ. A two-finger rotate gesture on a trackpad rotates the canvas view. Un geste de rotation à deux doigts sur un pavé tactile fait pivoter la vue de la zone de travail. + When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Quand vous déplacez des points d’ancrage, chaque courbe dont une extrémité bouge garde sa forme par rapport à ses extrémités. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Maintenir le raccourci d’un outil choisit cet outil jusqu’à ce que vous le relâchiez, puis l’outil précédent est de nouveau choisi. Shows the bounding box while you move the selection or draw a shape. Affiche le cadre de sélection pendant que vous déplacez la sélection ou dessinez une forme. Create Trim Marks draws Japanese-style marks instead of Roman ones. Créer des traits de coupe dessine des traits de style japonais au lieu de traits romains. @@ -3123,6 +3181,29 @@ digits Malayalam Malayalam The unit for East Asian type measurements, which no field uses yet. L’unité des mesures du texte d’Asie orientale, qu’aucun champ n’utilise encore. When on, a number typed without a unit into a field in picas is read in points. Si cette option est activée, un nombre saisi sans unité dans un champ en picas est lu en points. With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options. Avec ID XML, les noms des objets s’affichent sous forme d’ID XML dans Calques, Variables et Options de calque. + The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl. Le pas de la taille du texte et de l’interlignage. Cmd/Ctrl+Maj+. et Cmd/Ctrl+Maj+, modifient la taille d’un pas, ou de cinq avec Alt en plus. Dans le texte horizontal, Alt avec la flèche haut ou bas modifie l’interlignage d’un pas, ou de cinq avec Cmd/Ctrl. + The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl. Le pas de l’approche et du crénage, en millièmes de cadratin. Dans le texte horizontal, Alt avec la flèche gauche ou droite modifie le crénage au point d’insertion ou l’approche du texte sélectionné d’un pas, ou de cinq avec Cmd/Ctrl. + The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. Le pas du décalage de la ligne de base. Dans le texte horizontal, Alt et Maj avec la flèche haut ou bas déplacent la ligne de base d’un pas, ou de cinq avec Cmd/Ctrl. + Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. Affiche les options du texte japonais et des autres textes d’Asie orientale dans les panneaux Caractère, Paragraphe, OpenType et Glyphes, et la commande Polices composites. + Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. Affiche les options du texte arabe, hébreu et indien dans les panneaux Caractère et Paragraphe, comme le sens du paragraphe, les kashidas et les chiffres. + The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. Les outils de sélection ne sélectionnent le texte que sur sa ligne de base, le cadre du texte captif ou son tracé, et non n’importe où dans son cadre. + Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. Les menus de polices affichent chaque police sous son nom anglais. Désactivé, une police qui a aussi un nom dans sa propre langue affiche ce nom. + New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. Le nouveau texte captif démarre avec Taille automatique activée, si bien qu’un cadre rectangulaire de texte horizontal s’agrandit ou se réduit en hauteur selon son texte. + Font lists and the Type › Font menu show a sample of each font beside its name. Les listes de polices et le menu Police affichent un échantillon de chaque police à côté de son nom. + Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on. Les échantillons de polices sont dessinés en texte foncé sur blanc, quelle que soit la luminosité de l’interface. Cela ne s’applique que si les aperçus de polices dans les menus sont activés. + How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is. La hauteur de chaque ligne dans les listes des champs de police, comme celui du panneau Caractère, et donc la taille de chaque échantillon. + How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first. Le nombre de polices utilisées en dernier, de 1 à 15, que Polices récentes et les listes de polices affichent, de la plus récente à la plus ancienne. + When you change the font or font style of text, characters the new font has no glyph for keep the font they had. Quand vous changez la police ou le style de police d’un texte, les caractères pour lesquels la nouvelle police n’a pas de glyphe gardent leur ancienne police. + A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export. Une surbrillance rose sur la zone de travail marque les glyphes remplacés par des fonctions OpenType, comme les ligatures. Elle n’est ni imprimée ni exportée. + With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from. Avec l’outil Texte, la sélection d’un seul caractère affiche à côté de lui, sur la zone de travail, une rangée de ses glyphes de substitution à choisir. + A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export. Une surbrillance rose sur la zone de travail marque le texte dessiné dans une police de substitution parce que sa police manque. Elle n’est ni imprimée ni exportée. + New type made with a Type tool starts with placeholder text, selected, so typing replaces it. Le nouveau texte créé avec un outil Texte commence par un texte de remplissage sélectionné, que la saisie remplace. + Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list. Taper un marqueur de liste comme 1. ou * puis une espace au début d’un paragraphe transforme ce paragraphe en liste. + Fonts in this folder show in the font menus and can be used without being installed. Les polices de ce dossier apparaissent dans les menus de polices et peuvent être utilisées sans être installées. + Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows. Appliquer un style graphique à du texte retire aux caractères leur propre fond ou contour là où le style en a un, pour que la peinture du style soit visible. + Align and Distribute measure point type by the ink of its glyphs instead of its em box. Aligner et Répartir mesurent le texte de point d’après l’encre de ses glyphes plutôt que d’après son cadratin. + Align and Distribute measure area type by the ink of its glyphs instead of its frame. Aligner et Répartir mesurent le texte captif d’après l’encre de ses glyphes plutôt que d’après son cadre. + The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box. Le cadre de sélection et le panneau Transformation mesurent le texte de point d’après l’encre de ses glyphes plutôt que d’après son cadratin. Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply. Aligne le dessin, le déplacement et la mise à l’échelle sur les subdivisions de la grille, même quand la grille est masquée. Tant que l’option est activée, Magnétisme du pixel ne s’applique pas. The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead. La couleur des repères non sélectionnés. Un plan de travail doté d’une Étiquette des repères trace ses propres repères dans la couleur de l’étiquette. Draws guides as solid lines or as dots, including the guides already in the document. Trace les repères en lignes continues ou en points, y compris les repères déjà présents dans le document. @@ -3204,6 +3285,7 @@ digits Malayalam Malayalam Rounded Rectangle Tool Outil Rectangle arrondi Rounded Rectangle… Rectangle arrondi… Row Size: Taille des lignes : + Rows Lignes Rows: Lignes : Rule: Règle : Rulers Règles @@ -3378,6 +3460,9 @@ digits Malayalam Malayalam Search commands, tools, panels and effects… Chercher commandes, outils, panneaux et effets… No commands match Aucune commande ne correspond {pos} of {total}: {name} {pos} sur {total} : {name} + No menu item Aucun élément de menu + Toolbar Barre d’outils + {toolbar}, in the {tool} group {toolbar}, dans le groupe {tool} @plural {n} result|{n} results {n} résultat|{n} résultats @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} sur {n} résultat. Continuez à taper pour les affiner.|{shown} sur {n} résultats. Continuez à taper pour les affiner. Recent Commands Commandes récentes @@ -3458,6 +3543,7 @@ digits Malayalam Malayalam Set Slice Rectangle Définir le rectangle de tranche Set Tab Stops Définir les taquets de tabulation Set Text Définir le texte + Set the current fill or stroke to the selected color Appliquer la couleur sélectionnée au fond ou au contour actuel Set the selected color to the current color Remplacer la couleur sélectionnée par la couleur actuelle Set Zoom Définir le zoom Settings… Réglages… @@ -3497,9 +3583,9 @@ digits Malayalam Malayalam Shape Properties: Propriétés de la forme : Shaper Tool Outil Shaper Shapes Formes - Shear Déformation - Shear Tool Outil Déformation - Shear… Déformation… + Shear Cisaillement + Shear Tool Outil Cisaillement + Shear… Cisaillement… Shell Lower… Coquillage inférieur… Shell Upper… Coquillage supérieur… Shift Maj @@ -3581,7 +3667,7 @@ digits Malayalam Malayalam Show Vivid/Muted Afficher vives/atténuées Show Warm/Cool Afficher chaudes/froides Show {kind} Brushes Afficher les formes de type {kind} - Show/hide plate (Alt-click: only this plate) Afficher/masquer la plaque (Alt+clic : cette plaque uniquement) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Afficher/masquer la plaque (Alt+clic : cette plaque uniquement, puis à nouveau toutes les plaques) Show: Afficher : Shown with the optimised preview. Affiché avec l’aperçu optimisé. Side 1: Côté 1 : @@ -3888,7 +3974,7 @@ digits Malayalam Malayalam Composite Fonts Polices composites Export Composite Fonts Exporter des polices composites Import Composite Fonts Importer des polices composites -@msg each font must be {name, parts} chaque police doit être {name, parts} +@msg each font must be {{name, parts}} chaque police doit être {{name, parts}} @msg unknown key `{k}`; a font takes name and parts clé inconnue `{k}` ; une police prend name et parts @msg each font needs a name chaque police doit avoir un nom @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` ne peut pas nommer une police composite (1 à {COMPOSITE_NAME_MAX} caractères, sans caractères de contrôle) @@ -3901,7 +3987,7 @@ digits Malayalam Malayalam @msg two composite fonts are named `{_1}` deux polices composites s’appellent `{_1}` @msg `{_1}` is the name of an installed font `{_1}` est le nom d’une police installée @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}` : {_2} utilise `{font}`, une police composite -@msg give fonts: [{name, parts}…] indiquez fonts : [{name, parts}…] +@msg give fonts: [{{name, parts}}…] indiquez fonts : [{{name, parts}}…] @msg path is empty path est vide @msg fonts must be a list of composite fonts fonts doit être une liste de polices composites @msg names must be strings names doit contenir des chaînes @@ -3984,6 +4070,13 @@ digits Malayalam Malayalam Thumbnail View Vignettes Thumbnails: Vignettes : Tile Mosaïque + Tile All Vertically Tout en mosaïque verticale + Tile All Horizontally Tout en mosaïque horizontale + 2-Up Layout Disposition par 2 + 3-Up Layout Disposition par 3 + 4-Up Layout Disposition par 4 + 6-Up Layout Disposition par 6 + Arrange Documents Disposer les documents Tile Edge Color Couleur du bord du carreau Tile Edge Color… Couleur du bord du carreau… Tile Full Pages Mosaïque de pages entières @@ -4177,6 +4270,8 @@ digits Malayalam Malayalam V Spacing: Espacement V : V: V : Variable Width Profile Profil de largeur variable + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. La forme du contour garde sa propre taille, donc un profil de largeur ne la modifie pas. Supprimez la forme pour utiliser un profil. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. La forme du contour garde sa propre taille, donc un profil de largeur ne la modifie pas. Supprimez la forme pour utiliser un profil. Variables Variables New Variable Nouvelle variable Delete Variable Supprimer la variable @@ -4241,7 +4336,7 @@ digits Malayalam Malayalam Vertical: Vertical : Very High Très élevée View Affichage - View Artboard Only Afficher le plan de travail uniquement + View Artboard Contents Only Afficher uniquement le contenu du plan de travail View Opacity Mask Afficher le masque d’opacité View PDF after saving Afficher le PDF après l’enregistrement View {n} Vue {n} @@ -4453,6 +4548,7 @@ imageTrace Outline Contour Bevel Biseauté Offset Décalage Axis Axe + Axis Angle Angle de l’axe axis Horizontal Horizontal axis Vertical Vertical axis Both Les deux @@ -4529,6 +4625,13 @@ axis Both Les deux Show External Script Warning Afficher l’avertissement des scripts externes A Script Is Running Un script est en cours d’exécution Script Alert Alerte de script + Script File Access Accès du script aux fichiers + The script asks to read a file you choose. Le script demande à lire un fichier que vous choisissez. + The script asks to read and write a file you choose. Le script demande à lire et écrire un fichier que vous choisissez. + The script asks to read and write a folder you choose, with everything in it. Le script demande à lire et écrire un dossier que vous choisissez, avec tout son contenu. + Allow Once Autoriser une fois + Always Allow This Script Toujours autoriser ce script + Deny Refuser A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Un script peut modifier les documents ouverts et écrire des fichiers au moyen des commandes qu’il exécute. N’exécutez que des scripts de confiance. Do not show this warning again Ne plus afficher cet avertissement Stop the script and undo what it did? Then quit again. Arrêter le script et annuler ce qu’il a fait ? Quittez ensuite à nouveau. @@ -4545,6 +4648,8 @@ axis Both Les deux @msg the script is no longer in the Scripts folder le script ne se trouve plus dans le dossier Scripts Some scripts were not listed Certains scripts ne sont pas répertoriés The Scripts folder cannot be read Impossible de lire le dossier Scripts + Loading scripts… Chargement des scripts… + The Scripts folder is still being read Le dossier Scripts est encore en cours de lecture @msg the script's run is no longer available l’exécution du script n’est plus disponible @msg a failed command changed undo steps that could not be put back, so the script was stopped une commande en échec a modifié des étapes d’annulation qui n’ont pas pu être rétablies, le script a donc été arrêté @msg a recovery copy could not be written, so the script was not run une copie de récupération n’a pas pu être écrite, le script n’a donc pas été exécuté @@ -4557,8 +4662,6 @@ axis Both Les deux @msg Script file could not be read Le fichier de script n’a pas pu être lu @msg Script folder has more than 2,048 entries Le dossier de script contient plus de 2 048 entrées @msg Script file open mode must be r, w, e or a Le mode d’ouverture du fichier de script doit être r, w, e ou a -@msg Script file writing is not available L’écriture de fichiers de script n’est pas disponible -@msg Script file dialogs are not available Les boîtes de dialogue de fichiers de script ne sont pas disponibles @msg Script files cannot be opened in another application Les fichiers de script ne peuvent pas être ouverts dans une autre application @msg Script file access is unavailable on the web L’accès aux fichiers de script n’est pas disponible sur le web @msg Script has 256 files open Le script a 256 fichiers ouverts @@ -4673,9 +4776,38 @@ liquify-list-end {0}, {1} {0} et {1} @msg `name` must be the name of a script engine `name` doit être le nom d’un moteur de script @msg the main script engine is new for each run and is never kept, so it cannot be dropped le moteur de script principal est nouveau à chaque exécution et n’est jamais conservé, il ne peut donc pas être supprimé @msg there is no script engine named {name} il n’y a aucun moteur de script nommé {name} +@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` doit être un nombre entier de 1 à {_1} +@msg `args{place}` is nested more than 64 levels deep `args{place}` est imbriqué sur plus de 64 niveaux +@msg `args` must be an object `args` doit être un objet +@msg `args` is larger than 1 MiB `args` dépasse 1 Mio +@msg `path` is empty `path` est vide +@msg `installed` takes a `path`, not a `source` `installed` prend un `path`, pas un `source` +@msg `path` must name a .js or .jsx file `path` doit désigner un fichier .js ou .jsx +@msg give exactly one of `path` and `source` indiquez exactement un paramètre parmi `path` et `source` @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` est réservé à une exécution sans personne à qui demander : dans l’application, la personne répond à chaque boîte de dialogue @msg Running a script Exécution d’un script @msg Copied the script report Rapport du script copié +@msg Script file access denied: {path} Accès du script aux fichiers refusé : {path} +@msg Script file access to the app's own folders is not allowed L’accès du script aux dossiers propres à l’application n’est pas autorisé +@msg Script file cannot encode the text Le fichier du script ne peut pas encoder le texte +@msg Script file could not be written Le fichier du script n’a pas pu être écrit +@msg Script file dialogs need a person to answer them Les boîtes de dialogue de fichiers du script ont besoin d’une personne pour y répondre +@msg Script file is not open for writing Le fichier du script n’est pas ouvert en écriture +@msg Script file name is already in use Le nom du fichier du script est déjà utilisé +@msg Script file name must be a name without a folder Le nom du fichier du script doit être un nom sans dossier +@msg Script file permission can be kept only for a script run from a file L’autorisation d’accès aux fichiers ne peut être conservée que pour un script exécuté depuis un fichier +@msg Script file permission could not be saved L’autorisation d’accès aux fichiers du script n’a pas pu être enregistrée +@msg Script folder is not empty Le dossier du script n’est pas vide +@msg Script files cannot make aliases Les fichiers du script ne peuvent pas créer d’alias +@msg Script file hidden setting cannot be changed Le réglage masqué du fichier du script ne peut pas être modifié +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name} : une boîte de dialogue de fichiers ne peut pas s’ouvrir dans un rappel d’une fonction intégrée, d’un accesseur, d’une conversion ou d’un fichier exécuté par $.evalFile ; appelez-la depuis le propre code du script +@msg the script wrote more file data than one run may write (32 MiB) le script a écrit plus de données de fichiers qu’une exécution ne peut en écrire (32 Mio) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` pour la boîte de dialogue de fichiers d’un script doit être l’une des valeurs : once, always, deny, stop +@msg choose a file or folder first, or deny choisissez d’abord un fichier ou un dossier, ou refusez +@msg the script file permissions could not be saved: {e} les autorisations d’accès aux fichiers des scripts n’ont pas pu être enregistrées : {e} +@msg this script's file access can be allowed only once l’accès aux fichiers de ce script ne peut être autorisé qu’une fois +@msg Only the person at the keyboard can allow a script's file access Seule la personne au clavier peut autoriser l’accès aux fichiers d’un script +@msg A script is given at most 2,048 files: the files picked after them were left out Un script reçoit au plus 2 048 fichiers : les fichiers choisis après eux ont été laissés de côté @msg Copied the link info Informations sur le lien copiées @msg Corners edits the corners of a path Angles modifie les angles d’un tracé @msg Couldn't copy to the system clipboard: {e} Impossible de copier dans le presse-papiers du système : {e} @@ -4751,6 +4883,7 @@ liquify-list-end {0}, {1} {0} et {1} @msg Saved {path} {path} enregistré @msg Select text or click into text with the Type tool to insert glyphs Sélectionnez du texte ou cliquez dans un texte avec l’outil Texte pour insérer des glyphes @msg Shape Builder: no region under the pointer Concepteur de forme : aucune zone sous le pointeur +@msg Shape Builder: select all paths you want to merge Concepteur de forme : sélectionnez tous les tracés à fusionner @msg Shape Builder: select paths or compound paths Concepteur de forme : sélectionnez des tracés ou des tracés transparents @msg Show All Hidden Attributes: nothing is hidden Afficher tous les attributs masqués : rien n’est masqué @msg Split Into Grid: select paths large enough for the grid Découper en grille : sélectionnez des tracés assez grands pour la grille @@ -4806,6 +4939,8 @@ liquify-list-end {0}, {1} {0} et {1} @msg `{min_key}` is greater than `{max_key}` `{min_key}` est supérieur à `{max_key}` @msg give at least one of `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` indiquez au moins l’un des paramètres `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` doit valoir grayscale, rgb, hsb, cmyk ou websafe +@msg `view` must be wheel or box `view` doit valoir wheel ou box +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` doit valoir hue, saturation, brightness, red, green ou blue @msg `{k}` must be [x, y] `{k}` doit être [x, y] @msg `{name}` has no options `{name}` n’a pas d’options @msg `{name}` is a built-in workspace; choose another name `{name}` est un espace de travail intégré ; choisissez un autre nom @@ -4894,6 +5029,7 @@ liquify-list-end {0}, {1} {0} et {1} @msg bad trailer trailer non valide @msg balance must be between 0 and 100 balance doit être compris entre 0 et 100 @msg batch step {_1} (`{id}`) failed: {e} l’étape {_1} du lot (`{id}`) a échoué : {e} +@msg action step {_1} (`{id}`) failed: {reason} l’étape {_1} du script (`{id}`) a échoué : {reason} @msg brightness must be dark|mediumDark|mediumLight|light brightness doit valoir dark|mediumDark|mediumLight|light @msg can't encode the document: {0} impossible d’encoder le document : {0} @msg can't parse shortcut `{c}` impossible d’interpréter le raccourci `{c}` @@ -4913,6 +5049,7 @@ liquify-list-end {0}, {1} {0} et {1} @msg choose a folder to export to choisissez un dossier d’exportation @msg choose a location for the package choisissez un emplacement pour l’assemblage @msg clipboard is empty le presse-papiers est vide +@msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: au moins une couleur doit rester dans la table des couleurs @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what} : `{h}` n’est pas une couleur comme "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what} : {MAX_TABLE} couleurs au maximum @msg command `{0}` is not available right now: {1} la commande `{0}` n’est pas disponible pour le moment : {1} @@ -4980,9 +5117,15 @@ liquify-list-end {0}, {1} {0} et {1} @msg no PNG encoder aucun encodeur PNG @msg no active document aucun document actif @msg no active perspective plane aucun plan de perspective actif +@msg the perspective grid is hidden la grille de perspective est masquée +@msg Automatic Plane Positioning is off: turn on anchorPoint or gridlineIntersection (perspective.widget.options) Le positionnement automatique du plan est désactivé : activez anchorPoint ou gridlineIntersection (perspective.widget.options) +@msg anchorPoint must be true or false anchorPoint doit valoir true ou false +@msg gridlineIntersection must be true or false gridlineIntersection doit valoir true ou false +@msg tolerance must be 0 or more tolerance doit être supérieur ou égal à 0 +@msg give `at` or `clear`, not both indiquez `at` ou `clear`, pas les deux @msg no anchor points selected aucun point d’ancrage sélectionné -@msg `points` must be three [x, y] pairs of numbers `points` doit contenir trois paires de nombres [x, y] -@msg direct-select three anchor points, or give `points` sélectionnez trois points d’ancrage avec l’outil Sélection directe, ou indiquez `points` +@msg `points` must be two or three [x, y] pairs of numbers `points` doit contenir deux ou trois paires de nombres [x, y] +@msg direct-select two or three anchor points, or give `points` sélectionnez deux ou trois points d’ancrage avec l’outil Sélection directe, ou indiquez `points` @msg no circle passes through these points: two are the same or all three lie on one line aucun cercle ne passe par ces points : deux sont identiques ou les trois sont alignés @msg no app to open files here aucune application pour ouvrir des fichiers ici @msg no artboard aucun plan de travail @@ -5084,6 +5227,9 @@ liquify-list-end {0}, {1} {0} et {1} @msg no such user library bibliothèque utilisateur inexistante @msg no such view vue inexistante @msg no such width point point de largeur inexistant +@msg `single` must be `incoming` or `outgoing` `single` doit valoir `incoming` ou `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` et `outIndex` doivent être les deux moitiés d’un même point de largeur discontinu +@msg a discontinuous width point keeps its place un point de largeur discontinu garde sa position @msg no swatch `{name}` aucune nuance `{name}` @msg no swatch library `{l}` (see swatch.library.list) aucune bibliothèque de nuances `{l}` (voir swatch.library.list) @msg no symbol instances selected aucune instance de symbole sélectionnée @@ -5340,9 +5486,16 @@ liquify-list-end {0}, {1} {0} et {1} @msg unknown workspace (one of {_1}) espace de travail inconnu (valeurs possibles : {_1}) @msg unsupported: {0} non pris en charge : {0} @msg variables are locked les variables sont verrouillées +@msg variables that aren't text were left out: {kinds} les variables qui ne sont pas du texte ont été ignorées : {kinds} +variable-kind Visibility Visibilité +variable-kind Linked File Fichier lié +variable-kind Graph Data Données du graphe +variable-kind Unknown Inconnu +variable-list-two {0}, {1} {0} et {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} et {1} @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} plus de {MAX_CSV_ROWS} jeux de données : Importer des jeux de données en lit au plus {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} plus de {MAX_CSV_COLS} variables : Importer des jeux de données en lit au plus {MAX_CSV_COLS} -@msg variables that aren't text were left out: {kinds} les variables qui ne sont pas du texte ({kinds}) ont été ignorées @msg a new document won't read these variables back with their kind: {names} un nouveau document ne relira pas ces variables avec leur type : {names} @msg a new document refuses this file because of these variables: {names} un nouveau document refuse ce fichier à cause de ces variables : {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them l’en-tête `{header}` de `{name}` serait relu comme la variable `{other}` : renommez l’une des deux @@ -5368,6 +5521,8 @@ liquify-list-end {0}, {1} {0} et {1} @msg {label}: lost track of a shape's style {label} : le style d’une forme a été perdu @msg {label}: select paths {label} : sélectionnez des tracés @msg {label}: select paths, compound paths, groups or text {label} : sélectionnez des tracés, des tracés transparents, des groupes ou du texte +@msg a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first une ligne ou un autre tracé ouvert qui n’entoure aucune surface ne modifie pas la forme du résultat ; pour l’inclure, appliquez-lui d’abord Objet › Tracé › Vectoriser le contour +@msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first {label} a produit un résultat vide : une ligne ou un autre tracé ouvert n’entoure aucune surface ; pour l’inclure, appliquez-lui d’abord Objet › Tracé › Vectoriser le contour @msg {label}… {label}… @msg {name}: CRC mismatch {name} : CRC non concordant @msg {name}: no local header {name} : aucun en-tête local @@ -5392,6 +5547,9 @@ liquify-list-end {0}, {1} {0} et {1} @msgplural Discarded {n} recovered document|Discarded {n} recovered documents {n} document récupéré supprimé|{n} documents récupérés supprimés @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them {n} document récupéré restauré : enregistrez-le pour le conserver|{n} documents récupérés restaurés : enregistrez-les pour les conserver @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} Ouvert avec {n} remarque : {first}|Ouvert avec {n} remarques : {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Copié avec {n} remarque : {first}|Copié avec {n} remarques : {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Coupé avec {n} remarque : {first}|Coupé avec {n} remarques : {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Image vectorisée avec {n} remarque : {first}|Image vectorisée avec {n} remarques : {first} @msgplural {notice}. Opened with {n} note: {first}|{notice}. Opened with {n} notes: {first} {notice}. Ouvert avec {n} remarque : {first}|{notice}. Ouvert avec {n} remarques : {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} {path} enregistré avec {n} remarque : {first}|{path} enregistré avec {n} remarques : {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first {n} image incorporée ; il en manque {missing} : rétablissez d’abord leurs liens|{n} images incorporées ; il en manque {missing} : rétablissez d’abord leurs liens @@ -5418,6 +5576,8 @@ liquify-list-end {0}, {1} {0} et {1} @msg All colors are within the CMYK gamut Toutes les couleurs sont dans la gamme CMJN @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} couleur est hors de la gamme CMJN|{n} couleurs sont hors de la gamme CMJN @msg Unembedded to {_1} Incorporation annulée vers {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} Incorporation annulée pour {n} image vers {folder}|Incorporation annulée pour {n} images vers {folder} +@msg every numbered name for {name} is taken in that folder tous les noms numérotés pour {name} sont déjà pris dans ce dossier @msg Reset {_1} {_1} réinitialisé @msg Sent to {_1} Envoyé à {_1} @msg {_1} files Fichiers {_1} @@ -5433,6 +5593,8 @@ liquify-list-end {0}, {1} {0} et {1} @msg Reload the page to go on (changes not saved yet may be lost). Rechargez la page pour continuer (les modifications non encore enregistrées risquent d’être perdues). @msg tool (a tool id) is required tool (un identifiant d’outil) est obligatoire @msg {tool} isn't in a toolbar group of several tools {tool} ne fait pas partie d’un groupe de plusieurs outils dans la barre d’outils +@msg Presentation Mode hides the toolbars: change the screen mode to show them pour afficher les barres d’outils masquées par le Mode Présentation, changez de mode d’affichage +@msg Tab has hidden the toolbars: press Tab to show them pour afficher les barres d’outils masquées par Tab, appuyez sur Tab @msg onto must name a panel floating in another group onto doit désigner un panneau flottant dans un autre groupe @msg below and above must name a panel floating in another group below et above doivent désigner un panneau flottant dans un autre groupe @msg give only one of onto, below and above indiquez un seul de onto, below et above @@ -5571,6 +5733,9 @@ liquify-list-end {0}, {1} {0} et {1} @msg automation path rejected: outside the read root {root}: {path} chemin d’automatisation refusé : hors du dossier racine de lecture {root} : {path} @msg automation path rejected: outside the read roots {roots}: {path} chemin d’automatisation refusé : hors des dossiers racines de lecture {roots} : {path} @msg a linked JavaScript file is outside the read roots un fichier JavaScript lié est hors des dossiers racines de lecture +@msg a linked image file is outside the read roots un fichier image lié est hors des dossiers racines de lecture +@msg a linked file's export folder is outside the read roots le dossier d’exportation d’un fichier lié est hors des dossiers racines de lecture +@msg a linked file's editing data can't be read to check it against the read roots impossible de lire les données d’édition d’un fichier lié pour les vérifier par rapport aux dossiers racines de lecture @msg automation path rejected: outside the write root {root}: {path} chemin d’automatisation refusé : hors du dossier racine d’écriture {root} : {path} @msg automation path rejected: outside the write roots {roots}: {path} chemin d’automatisation refusé : hors des dossiers racines d’écriture {roots} : {path} @msg automation path rejected: path is empty chemin d’automatisation refusé : le chemin est vide @@ -5797,6 +5962,7 @@ lighting Light Lumière @msg missing panel layout Disposition des panneaux manquante @msg unsupported native docking operation Opération native d’ancrage non prise en charge Linux Display Server Serveur d’affichage Linux + Low-Latency Drawing Dessin à faible latence X11 (XWayland) When a Pen Is Attached X11 (XWayland) quand un stylet est branché If a drawing tablet's pen doesn't draw, choose an X11 (XWayland) option. Si le stylet d’une tablette graphique ne dessine pas, choisissez une option X11 (XWayland). X11 (XWayland) X11 (XWayland) @@ -5851,6 +6017,7 @@ lighting Light Lumière Cove Cavet Depth Profondeur Front Avant + Side Côté Isometric Bottom Isométrique dessous Isometric Left Isométrique gauche Isometric Right Isométrique droite @@ -5945,6 +6112,7 @@ lighting Light Lumière @msg each of `{GRAPHICS}` must be an object chaque élément de `{GRAPHICS}` doit être un objet @msg `{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}` les éléments de `{GRAPHICS}` acceptent symbol, face, x, y, scale et rotation, pas `{k}` @msg each of `{GRAPHICS}` needs `symbol`, the name of a symbol chaque élément de `{GRAPHICS}` nécessite `symbol`, le nom d’un symbole +@msg `{GRAPHICS}` face must be front, back or side face de `{GRAPHICS}` doit valoir front, back ou side @msg `{GRAPHICS}` face must be front or back face de `{GRAPHICS}` doit valoir front ou back @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} de `{GRAPHICS}` doit être un nombre de {lo} à {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` doit être un tableau @@ -6275,7 +6443,7 @@ lighting Light Lumière Set: Jeu : Shades Tons foncés Shades of Gray Nuances de gris - Shear: Déformation : + Shear: Cisaillement : Shift+Click Maj+clic Shift+Drag Maj+glisser Shortcut Raccourci @@ -6384,6 +6552,7 @@ lighting Light Lumière of sur sRGB IEC61966-2.1 sRGB IEC61966-2.1 x Height Hauteur d’x + Em Box Height Hauteur du cadratin ▾ Default Actions ▾ Scripts par défaut ⚠ {chord} was already used by {names} — it has been removed there. Attention : {chord} était déjà utilisé par {names} ; il en a été retiré. @id file.close Fermer @@ -7375,6 +7544,12 @@ anchor Points: Points : @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` doit être "free", "keepAngles" ou "symmetric" @msg `{key}` must be [x, y] `{key}` doit être [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Convertisseur d’unités + Unit Converter Panel Panneau Convertisseur d’unités + Copy with Units Copier avec les unités + From Selection Depuis la sélection + # Color Effects add-on: Select by Color Kind. Select by Color Kind Sélectionner par type de couleur Objects with Spot Colors Objets avec tons directs @@ -7599,6 +7774,14 @@ breakText Glyphs Glyphes Remove Gaps Supprimer les écarts @msg that makes too many pieces (at most 100000): make the dashes longer cela donne trop de morceaux (100000 au plus) : allongez les tirets @msg select paths, or segments, to divide sélectionnez des tracés ou des segments à diviser +# Path Precision Tools add-on: Smooth Bridge. + Smooth Bridge… Pont lissé… + Smooth Bridge Pont lissé + Keep Originals Conserver les originaux +@msg select two circles to bridge sélectionnez deux cercles à relier +@msg one circle is inside the other un cercle est à l’intérieur de l’autre +@msg the circles are too far apart for this radius: raise the radius les cercles sont trop éloignés pour ce rayon : augmentez le rayon +@msg the circles are too far apart for this radius les cercles sont trop éloignés pour ce rayon # Path Precision Tools add-on: Common Tangents. Common Tangents… Tangentes communes… Common Tangents Tangentes communes @@ -8171,7 +8354,7 @@ breakText Glyphs Glyphes @msg `scale` must be a number from 0.001 to 1000 `scale` doit être un nombre compris entre 0.001 et 1000 @msg `scale` must be a number in (0, 100] `scale` doit être un nombre dans (0, 100] @msg `scope.{key}` must be a non-empty array `scope.{key}` doit être une liste non vide -@msg `scope` must be "document", {artboards} or {layers} `scope` doit valoir "document", {artboards} ou {layers} +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` doit valoir "document", {{artboards: [index, …]}} ou {{layers: [id, …]}} @msg `scope` must be "selection" or "document", not {other} `scope` doit valoir "selection" ou "document", pas {other} @msg `script` must be a string `script` doit être une chaîne @msg `seriesIndexes` is a non-empty list of series indexes `seriesIndexes` est une liste non vide d’indices de séries @@ -8247,6 +8430,8 @@ breakText Glyphs Glyphes @msg `{f}` is the copy of a document open now `{f}` est la copie d’un document actuellement ouvert @msg `{id}` is no writable format (see document.formats) `{id}` n’est pas un format inscriptible (voir document.formats) @msg `{id}` isn't a loaded library `{id}` n’est pas une bibliothèque chargée +@msg `{file}` has no swatches of its own `{file}` n’a pas de nuances propres +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` contient des nuances de motif, qu’un fichier .vcswatches ne peut pas contenir @msg `{key}` has no colours `{key}` ne contient aucune couleur @msg `{key}` holds more than {MAX_EDIT_WORDS} words `{key}` contient plus de {MAX_EDIT_WORDS} mots @msg `{key}` is a design name `{key}` est un nom de motif @@ -8537,7 +8722,13 @@ breakText Glyphs Glyphes @msg colorModel must be {own} (the document's mode), grayscale or bitmap colorModel doit valoir {own} (le mode du document), grayscale ou bitmap @msg colour groups can't go into colour groups un groupe de couleurs ne peut pas aller dans un groupe de couleurs @msg colour, mode and spot apply to solid-colour swatches only couleur, mode et ton direct s’appliquent uniquement aux nuances de couleur unie -@msg column {column}: `{cell}` is a `%` column of graph data files, which are not read colonne {column} : `{cell}` est une colonne `%` des fichiers de données de graphe, qui ne sont pas lus +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path ligne {line}, colonne {column} : le fichier de données de graphe `{path}` pour `{var}` est un chemin relatif : indiquez `base` ou un chemin absolu +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` isn't followed: {r} ligne {line}, colonne {column} : le fichier de données de graphe `{path}` pour `{var}` n’est pas suivi : {r} +@msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} ligne {line}, colonne {column} : impossible de lire le fichier de données de graphe pour `{var}` : {e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes ligne {line}, colonne {column} : le fichier de données de graphe `{path}` pour `{var}` dépasse {MAX_GRAPH_DATA_FILE} octets +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes ligne {line}, colonne {column} : le fichier de données de graphe `{path}` pour `{var}` donne une valeur de graphe de plus de {MAX_GRAPH_CSV} octets +@msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all ligne {line}, colonne {column} : les fichiers de données de graphe contiennent plus de {MAX_GRAPH_FILES_TOTAL} octets au total +@msg `base` is empty `base` est vide @msg column {column}: `{cell}` names `{name}`, which is a {_1} variable colonne {column} : `{cell}` désigne `{name}`, qui est une variable {_1} @msg column {column}: `{cell}` names no variable colonne {column} : `{cell}` ne désigne aucune variable @msg column {column}: the variable name is longer than {MAX_NAME} characters colonne {column} : le nom de variable dépasse {MAX_NAME} caractères @@ -8549,6 +8740,7 @@ breakText Glyphs Glyphes @msg compound {_1} must contain exactly one open path to join le tracé transparent {_1} doit contenir exactement un tracé ouvert à joindre @msg connect end must be "start" or "end" l’extrémité de connect doit valoir "start" ou "end" @msg connect needs a path other than the one extended connect nécessite un tracé autre que celui qui est prolongé +@msg connect needs extend connect nécessite extend @msg connect needs id connect nécessite id @msg connect path has no open end le tracé de connect n’a pas d’extrémité ouverte @msg continuation must be an array of path chunks continuation doit être une liste de fragments de tracé @@ -9060,7 +9252,7 @@ breakText Glyphs Glyphes @msg nothing to print: every artboard picked is blank rien à imprimer : chaque plan de travail choisi est vide @msg nothing to print: the document has no art that prints rien à imprimer : le document n’a aucune illustration imprimable @msg nothing to repeat rien à répéter -@msg numbers out of order in {_1} quantifier nombres dans le désordre dans le quantificateur {_1} +@msg numbers out of order in {{}} quantifier nombres dans le désordre dans le quantificateur {{}} @msg object is not a path l’objet n’est pas un tracé @msg object transparency cannot be sampled onto highlighted characters; disable Transparency in Eyedropper Options or select the whole object la transparence d’un objet ne peut pas être prélevée sur des caractères en surbrillance ; désactivez Transparence dans les options de la pipette ou sélectionnez l’objet entier @msg object {_1} can't be set as point type l’objet {_1} ne peut pas être converti en texte de point @@ -9419,7 +9611,7 @@ breakText Glyphs Glyphes @msg the page has no area la page n’a pas de surface @msg the page's type in an unread object's box isn't in its page art le texte de la page dans le cadre d’un objet non lu n’est pas dans l’illustration de sa page @msg the paint behind the proxy is not a gradient la peinture derrière l’échantillon n’est pas un dégradé -@msg the paint is not a freeform gradient (apply one with paint.editGradient {kind}) la peinture n’est pas un dégradé de forme libre (appliquez-en un avec paint.editGradient {kind}) +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) la peinture n’est pas un dégradé de forme libre (appliquez-en un avec paint.editGradient {{kind: "freeform"}}) @msg the parameters or body do not form one function les paramètres ou le corps ne forment pas une seule fonction @msg the parent must be a layer or sublayer le parent doit être un calque ou un sous-calque @msg the pasted SVG filter {name} draws differently from the document's filter of that name, and no free name fits it le filtre SVG collé {name} dessine autrement que le filtre du document qui porte ce nom, et aucun nom libre ne lui convient @@ -9901,4 +10093,14 @@ breakText Glyphs Glyphes @msg A panel is not joined to the rest by a crease. Un panneau n’est relié au reste par aucune ligne de rainage. @msg A fold line is on a non-printing layer. Une ligne de pliage se trouve sur un calque non imprimable. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} {panels} panneau(x), {hinges} charnière(s), {errors} erreur(s), {warnings} avertissement(s) + Fold Preview Aperçu du pliage + Fold Pliage + Show Fold Lines Afficher les lignes de pliage + Three-Quarter Trois-quarts + Open a document to preview its folded shape. Ouvrez un document pour prévisualiser sa forme pliée. +@msg Check the fold lines first. Vérifiez d’abord les lignes de pliage. +@msg Panels: {panels}, hinges: {hinges} {panels} panneau(x), {hinges} charnière(s) +@msg Other blanks not shown: {count} {count} autre(s) flan(s) non affiché(s) +@msg A joint does not close by {gap} pt. Un joint ne se ferme pas, avec un écart de {gap} pt. +@msg Two panels pass through each other. Deux panneaux se traversent. @msg {_1} × {_2} pixels is too large for GIF (at most 65535 pixels a side): lower the resolution {_1} × {_2} pixels, c’est trop grand pour le GIF (65535 pixels par côté au plus) : réduisez la résolution diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index c427fc527c..614baf3b2a 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -123,6 +123,7 @@ Add Anchor Point Tool એન્કર બિંદુ ઉમેરો ટૂલ Add Anchor Points એન્કર બિંદુઓ ઉમેરો Add Anchors… એન્કર ઉમેરો… + Add Around ઑબ્જેક્ટની આસપાસ ઉમેરો Add Content કન્ટેન્ટ ઉમેરો Add Effect ઇફેક્ટ ઉમેરો Add Event ઇવેન્ટ ઉમેરો @@ -163,7 +164,11 @@ Add to the Current Shortcuts વર્તમાન શૉર્ટકટમાં ઉમેરો Additional Fonts Folder વધારાનું ફોન્ટ ફોલ્ડર Additional Plug-ins Folder વધારાનું પ્લગ-ઇન ફોલ્ડર + Plug-in Instruction Budget પ્લગ-ઇન સૂચના બજેટ Adjust Adjoining Width Points અડીને આવેલા પહોળાઈ બિંદુઓ ગોઠવો + Incoming આવતી બાજુ + Outgoing જતી બાજુ + Single Width Only ફક્ત એક પહોળાઈ Adjust Color Balance… રંગ બૅલેન્સ ગોઠવો… Adjust Colors રંગ ગોઠવો Adjust Options: ગોઠવણ વિકલ્પો: @@ -226,10 +231,12 @@ Anchors selected: {count} પસંદ કરેલા એન્કર: {count} Anchors: એન્કર: Angle ખૂણો + Axis Angle અક્ષનો ખૂણો Angle: ખૂણો: Angled Strokes… ત્રાંસા સ્ટ્રોક… Angles ખૂણા Animated Zoom ઍનિમેટેડ ઝૂમ + Anti Alias એન્ટિ-એલિયાસિંગ Anti-Alias એન્ટિ-એલિયાસ Anti-alias એન્ટિ-એલિયાસ Anti-alias Rasters રાસ્ટર એન્ટિ-એલિયાસ @@ -453,6 +460,8 @@ Brush Library બ્રશ લાઇબ્રેરી Brush Options બ્રશ વિકલ્પો Brush Options… બ્રશ વિકલ્પો… + Options of Selected Object… પસંદ કરેલા ઑબ્જેક્ટના વિકલ્પો… + Options of Selected Object પસંદ કરેલા ઑબ્જેક્ટના વિકલ્પો Brush Scale Options બ્રશ સ્કેલ વિકલ્પો Brush Strokes બ્રશ સ્ટ્રોક Brushes બ્રશ @@ -538,6 +547,11 @@ Character Color અક્ષર રંગ Character Direction અક્ષર દિશા Character Rotation અક્ષર પરિભ્રમણ + Chinese Big 5 ચાઇનીઝ Big 5 + Cyrillic સિરિલિક + Greek ગ્રીક + Baltic બાલ્ટિક + Central European મધ્ય યુરોપિયન Character Set: અક્ષર સેટ: Character Style Options અક્ષર સ્ટાઇલ વિકલ્પો Character Styles અક્ષર સ્ટાઇલ @@ -562,6 +576,8 @@ Chosen: {n} of {total} પસંદ કરેલ: {total} માંથી {n} Chrome… ક્રોમ… Circle વર્તુળ + Circle Tool વર્તુળ ટૂલ + Circle too large વર્તુળ ખૂબ મોટું છે Circle: વર્તુળ: Classic ક્લાસિક Clean Up સાફ કરો @@ -639,6 +655,7 @@ Color Library… રંગ લાઇબ્રેરી… Color Mode રંગ મોડ Color Mode: રંગ મોડ: + Color Model રંગ મોડેલ Color Model: રંગ મોડેલ: Color Models રંગ મોડેલ Color Panel Options રંગ પેનલ વિકલ્પો @@ -671,6 +688,7 @@ Column Graph Tool કૉલમ ગ્રાફ ટૂલ Column Type: કૉલમ પ્રકાર: Column Width: કૉલમ પહોળાઈ: + Columns કૉલમ Columns: કૉલમ: Column… કૉલમ… Combine Point Text પોઇન્ટ ટેક્સ્ટ જોડો @@ -770,6 +788,7 @@ Copy into the document's folder દસ્તાવેજના ફોલ્ડરમાં નકલ કરો Copy only fonts you own or are licensed to install. ફક્ત તમારી માલિકીના અથવા ઇન્સ્ટોલ કરવાના લાઇસન્સવાળા ફોન્ટ્સની નકલ કરો. Copy to User Defined વપરાશકર્તા-વ્યાખ્યાયિતમાં નકલ કરો + Copy with Units એકમો સાથે નકલ કરો Copyright કૉપીરાઇટ Copyright Info URL: કૉપીરાઇટ માહિતી URL: Templates ટેમ્પલેટ @@ -903,6 +922,8 @@ Delete Artboard આર્ટબોર્ડ કાઢી નાખો Delete Artboards આર્ટબોર્ડ્સ કાઢી નાખો Delete Brush બ્રશ કાઢી નાખો + Delete Color રંગ કાઢી નાખો + Restore Generated Table જનરેટ થયેલું ટેબલ પુનઃસ્થાપિત કરો Delete Character Style અક્ષર સ્ટાઇલ કાઢી નાખો Delete Data Set ડેટા સેટ કાઢી નાખો Delete Data Sets ડેટા સેટ્સ કાઢી નાખો @@ -994,6 +1015,7 @@ Direction: દિશા: Directives નિર્દેશો Disable Auto Add/Delete ઑટો ઍડ/ડિલીટ બંધ કરો + Interpolate Control Points When Moving Anchors એન્કર બિંદુઓ ખસેડતી વખતે દિશા હેન્ડલ્સ ઇન્ટરપોલેટ કરો Disable Opacity Mask ઓપેસિટી માસ્ક બંધ કરો Disable and Continue બંધ કરો અને ચાલુ રાખો Disabled plug-ins બંધ કરેલા પ્લગ-ઇન્સ @@ -1378,6 +1400,8 @@ Files ફાઇલો Files of a PDF standard can't be password-protected. PDF સ્ટાન્ડર્ડની ફાઇલો પાસવર્ડ-સુરક્ષિત કરી શકાતી નથી. Files of this standard tag their colours with ICC profiles. આ સ્ટાન્ડર્ડની ફાઇલો તેમના રંગોને ICC પ્રોફાઇલ્સ સાથે ટૅગ કરે છે. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. આ સ્ટાન્ડર્ડની ફાઇલો તેમના રંગોને ICC પ્રોફાઇલ્સ સાથે ટૅગ કરે છે, આઉટપુટ ઇન્ટેન્ટ પ્રોફાઇલમાંના CMYK રંગો સિવાય, જે DeviceCMYK તરીકે લખાય છે. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. “પ્રોફાઇલ્સ શામેલ કરશો નહીં” અને CMYK આઉટપુટ ઇન્ટેન્ટ સાથે, દરેક CMYK રંગ DeviceCMYK તરીકે લખાય છે, સિવાય કે તેને બીજી પ્રોફાઇલના CMYK ગંતવ્યમાં રૂપાંતરિત કરવામાં આવે. Fill ભરો Fill & Stroke ભરો અને સ્ટ્રોક Fill (X), double-click for the Color Picker ભરો (X), કલર પીકર માટે ડબલ-ક્લિક કરો @@ -1508,8 +1532,10 @@ Frequencies and angles are the output device's to apply. ફ્રિક્વન્સી અને એંગલ આઉટપુટ ડિવાઇસ લાગુ કરશે. Frequency ફ્રિક્વન્સી Fresco… ફ્રેસ્કો… + From Selection પસંદગીમાંથી From: થી: Front આગળ + Side બાજુ Full Document સંપૂર્ણ દસ્તાવેજ Full Justify સંપૂર્ણ જસ્ટિફાય Full Screen Mode ફુલ સ્ક્રીન મોડ @@ -1708,6 +1734,8 @@ Highlight Alternate Glyphs વૈકલ્પિક ગ્લિફ હાઇલાઇટ કરો Highlight Area વિસ્તાર હાઇલાઇટ કરો Highlight Font Name ફોન્ટનું નામ હાઇલાઇટ કરો + Highlight Font Size ફોન્ટ સાઇઝ હાઇલાઇટ કરો + Other… અન્ય… Highlight Intensity હાઇલાઇટ તીવ્રતા Highlight Kerning કર્નિંગ હાઇલાઇટ કરો Highlight Rows પંક્તિઓ હાઇલાઇટ કરો @@ -1907,6 +1935,7 @@ Kashidas કાશીદા Keep Formatting ફોર્મેટિંગ રાખો Keep Original મૂળ રાખો + Keep Originals મૂળ રાખો Keep Plain Text સાદો ટેક્સ્ટ રાખો Keep Shared Points Together વહેંચાયેલા પોઇન્ટ સાથે રાખો Keep Tools Beside the Canvas ટૂલ્સ કેનવાસની બાજુમાં રાખો @@ -2045,6 +2074,7 @@ Linked Files લિંક કરેલી ફાઇલો Links લિંક્સ Linux Display Server Linux ડિસ્પ્લે સર્વર + Low-Latency Drawing ઓછા વિલંબવાળું ડ્રોઇંગ Liquify લિક્વિફાઇ List Data Sets ડેટા સેટની યાદી List Folder ફોલ્ડરની યાદી @@ -2069,6 +2099,7 @@ Live curve fitting લાઇવ કર્વ ફિટિંગ Live preview લાઇવ પૂર્વાવલોકન Load Actions… ઍક્શન લોડ કરો… + Replace Actions… ઍક્શન બદલો… Reset Actions ઍક્શન રીસેટ કરો Replace the current actions with the default set? વર્તમાન ઍક્શનને ડિફૉલ્ટ સેટથી બદલવા છે? Append adds the default set after the current sets instead. ઉમેરો તેના બદલે ડિફૉલ્ટ સેટને વર્તમાન સેટ પછી ઉમેરે છે. @@ -2093,6 +2124,7 @@ Loads native code નેટિવ કોડ લોડ કરે છે Local Libraries સ્થાનિક લાઇબ્રેરીઓ Locate Library… લાઇબ્રેરી શોધો… + Locate Layer લેયર શોધો Locate Object ઑબ્જેક્ટ શોધો Locate Selected Objects પસંદ કરેલા ઑબ્જેક્ટ શોધો Location સ્થાન @@ -2610,6 +2642,9 @@ Overprint Stroke ઓવરપ્રિન્ટ સ્ટ્રોક Overprint and Transparency Flattener ઓવરપ્રિન્ટ અને પારદર્શિતા ફ્લેટનર Overprint and Transparency Flattener Options ઓવરપ્રિન્ટ અને પારદર્શિતા ફ્લેટનર વિકલ્પો + Custom… કસ્ટમ… + Custom Transparency Flattener Options કસ્ટમ પારદર્શિતા ફ્લેટનર વિકલ્પો + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS માં આલ્ફા પારદર્શિતા નથી, અને ઓવરપ્રિન્ટ્સ નક્કી કરે છે કે ઓવરપ્રિન્ટ્સ જાળવવામાં આવે કે નહીં. Overprint: ઓવરપ્રિન્ટ: Overprints: ઓવરપ્રિન્ટ્સ: Override Character Color અક્ષરનો રંગ ઓવરરાઇડ કરો @@ -2757,6 +2792,10 @@ Polish પોલિશ Polygon બહુકોણ Polygon Properties: બહુકોણના ગુણધર્મો: + Line Properties: રેખાના ગુણધર્મો: + Line Length: રેખાની લંબાઈ: + Line Angle: રેખાનો કોણ: + Constrain Pie Angle પાઇ કોણ મર્યાદિત કરો Polygon Tool બહુકોણ ટૂલ Polygonal Lasso બહુકોણીય લાસો Polygonal Lasso Tool બહુકોણીય લાસો ટૂલ @@ -3111,6 +3150,8 @@ Reset રીસેટ કરો Reset Bar Position બાર સ્થિતિ રીસેટ કરો Reset Bounding Box બાઉન્ડિંગ બોક્સ રીસેટ કરો + Rotate Bounding Box બાઉન્ડિંગ બોક્સ ફેરવો + Rotate Bounding Box… બાઉન્ડિંગ બોક્સ ફેરવો… Reset Envelope Mesh એન્વેલપ મેશ રીસેટ કરો Reset Envelope Shape એન્વેલપ આકાર રીસેટ કરો Reset Essentials એસેન્શિયલ્સ રીસેટ કરો @@ -3152,6 +3193,7 @@ Resize Artboard આર્ટબોર્ડનું માપ બદલો Resize Slice સ્લાઇસનું માપ બદલો Resize Type Area ટાઇપ એરિયાનું માપ બદલો + Resolution રિઝોલ્યુશન Resolution: રિઝોલ્યુશન: Responsive રિસ્પોન્સિવ Restore પુનઃસ્થાપિત કરો @@ -3179,6 +3221,7 @@ The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Cmd/Ctrl દબાવી રાખીને માઉસ વ્હીલ ફેરવવાથી કેનવાસ બાજુમાં સ્ક્રોલ થાય છે. Dragging sideways on a numeric field's label changes the field's value. સંખ્યાત્મક ફીલ્ડના લેબલ પર બાજુમાં ખેંચવાથી ફીલ્ડનું મૂલ્ય બદલાય છે. A two-finger rotate gesture on a trackpad rotates the canvas view. ટ્રેકપેડ પર બે આંગળીથી ફેરવવાનો હાવભાવ કેનવાસનું દૃશ્ય ફેરવે છે. + When you move anchor points, each curve with one moved end keeps its shape relative to its ends. જ્યારે તમે એન્કર પોઇન્ટ ખસેડો છો, ત્યારે એક ખસેલા છેડાવાળો દરેક વળાંક તેના છેડાઓની સાપેક્ષે પોતાનો આકાર જાળવે છે. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. ટૂલની શોર્ટકટ કી દબાવી રાખવાથી છોડો ત્યાં સુધી તે ટૂલ પસંદ રહે છે, પછી અગાઉનું ટૂલ ફરી પસંદ થાય છે. Shows the bounding box while you move the selection or draw a shape. તમે પસંદગી ખસેડો કે આકાર દોરો ત્યારે બાઉન્ડિંગ બોક્સ બતાવે છે. Create Trim Marks draws Japanese-style marks instead of Roman ones. ટ્રિમ માર્ક્સ બનાવો રોમન ને બદલે જાપાની શૈલીના ચિહ્નો દોરે છે. @@ -3209,6 +3252,29 @@ The unit for East Asian type measurements, which no field uses yet. પૂર્વ એશિયાઈ ટાઇપના માપ માટેનો એકમ, જેનો હજી કોઈ ફીલ્ડ ઉપયોગ કરતું નથી. When on, a number typed without a unit into a field in picas is read in points. ચાલુ હોય ત્યારે, પાઇકામાં હોય તેવા ફીલ્ડમાં એકમ વિના ટાઇપ કરેલી સંખ્યા પોઇન્ટ્સમાં વંચાય છે. With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options. XML ID પસંદ હોય ત્યારે ઑબ્જેક્ટનાં નામ લેયર્સ, વેરિએબલ્સ અને લેયર વિકલ્પોમાં XML ID તરીકે દેખાય છે. + The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl. ટાઇપ કદ અને લીડિંગનું પગલું: Cmd/Ctrl+Shift+. અને Cmd/Ctrl+Shift+, કદને એક પગલું બદલે છે, અને Alt સાથે પાંચ પગલાં; આડા ટાઇપમાં Alt સાથે ઉપર કે નીચેનો એરો લીડિંગને એક પગલું બદલે છે, અને Cmd/Ctrl સાથે પાંચ પગલાં. + The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl. ટ્રેકિંગ અને કર્નિંગનું પગલું, em ના હજારમા ભાગમાં: આડા ટાઇપમાં Alt સાથે ડાબો કે જમણો એરો કેરેટ પરનું કર્નિંગ અથવા પસંદ કરેલા ટેક્સ્ટનું ટ્રેકિંગ એક પગલું બદલે છે, અને Cmd/Ctrl સાથે પાંચ પગલાં. + The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. બેઝલાઇન શિફ્ટનું પગલું: આડા ટાઇપમાં Alt અને Shift સાથે ઉપર કે નીચેનો એરો બેઝલાઇનને એક પગલું ખસેડે છે, અને Cmd/Ctrl સાથે પાંચ પગલાં. + Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. અક્ષર, ફકરો, OpenType અને ગ્લિફ્સ પેનલમાં જાપાની અને અન્ય પૂર્વ એશિયન ટાઇપના વિકલ્પો, અને કમ્પોઝિટ ફોન્ટ્સ આદેશ બતાવે છે. + Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. અક્ષર અને ફકરો પેનલમાં અરબી, હિબ્રુ અને ભારતીય ટાઇપના વિકલ્પો બતાવે છે, જેમ કે ફકરાની દિશા, કશીદા અને અંકો. + The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. પસંદગી ટૂલ્સ ટાઇપને ફક્ત તેની બેઝલાઇન, એરિયા ટાઇપની ફ્રેમ કે તેના પાથ પર પસંદ કરે છે, તેના બૉક્સની અંદર ગમે ત્યાં નહીં. + Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. ફોન્ટ મેનૂ દરેક ફોન્ટને તેના અંગ્રેજી નામથી બતાવે છે; બંધ હોય ત્યારે, જે ફોન્ટનું પોતાની ભાષામાં પણ નામ હોય તે એ નામ બતાવે છે. + New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. નવો એરિયા ટાઇપ ઑટો સાઇઝ ચાલુ સાથે શરૂ થાય છે, તેથી આડા ટાઇપની લંબચોરસ ફ્રેમ તેના ટેક્સ્ટ મુજબ ઊંચાઈમાં વધે કે ઘટે છે. + Font lists and the Type › Font menu show a sample of each font beside its name. ફોન્ટ યાદીઓ અને ફોન્ટ મેનૂ દરેક ફોન્ટના નામની બાજુમાં તેનો નમૂનો બતાવે છે. + Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on. ઇન્ટરફેસની તેજસ્વિતા ગમે તે હોય, ફોન્ટ નમૂના સફેદ પર ઘેરા ટાઇપમાં દોરાય છે; આ ફક્ત મેનૂમાં ફોન્ટ પૂર્વાવલોકન ચાલુ હોય ત્યારે જ લાગુ પડે છે. + How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is. ફોન્ટ ફીલ્ડની યાદીઓમાં, જેમ કે અક્ષર પેનલની, દરેક હરોળ કેટલી ઊંચી છે, અને તેથી દરેક નમૂનો કેટલો મોટો છે. + How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first. તાજેતરના ફોન્ટ્સ અને ફોન્ટ યાદીઓ છેલ્લે વાપરેલા કેટલા ફોન્ટ બતાવે છે, 1 થી 15, સૌથી નવો પહેલાં. + When you change the font or font style of text, characters the new font has no glyph for keep the font they had. તમે ટેક્સ્ટનો ફોન્ટ અથવા ફોન્ટ શૈલી બદલો ત્યારે, જે અક્ષરો માટે નવા ફોન્ટમાં ગ્લિફ નથી તે પોતાનો જૂનો ફોન્ટ રાખે છે. + A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export. કૅનવાસ પર ગુલાબી હાઇલાઇટ OpenType સુવિધાઓએ બદલેલા ગ્લિફ્સ દર્શાવે છે, જેમ કે લિગેચર; તે પ્રિન્ટ કે નિકાસ થતું નથી. + With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from. ટાઇપ ટૂલથી એક અક્ષર પસંદ કરતાં કૅનવાસ પર તેની બાજુમાં પસંદ કરવા માટે તેના વૈકલ્પિક ગ્લિફ્સની એક હરોળ દેખાય છે. + A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export. કૅનવાસ પર ગુલાબી હાઇલાઇટ એ ટેક્સ્ટ દર્શાવે છે જે પોતાનો ફોન્ટ ખૂટતો હોવાથી બદલીના ફોન્ટમાં દોરાયું છે; તે પ્રિન્ટ કે નિકાસ થતું નથી. + New type made with a Type tool starts with placeholder text, selected, so typing replaces it. ટાઇપ ટૂલથી બનેલો નવો ટાઇપ પસંદ કરેલા પ્લેસહોલ્ડર ટેક્સ્ટથી શરૂ થાય છે, જેને તમે ટાઇપ કરો તે બદલી નાખે છે. + Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list. ફકરાની શરૂઆતમાં 1. કે * જેવું યાદી ચિહ્ન અને પછી સ્પેસ ટાઇપ કરવાથી ફકરો યાદી બની જાય છે. + Fonts in this folder show in the font menus and can be used without being installed. આ ફોલ્ડરના ફોન્ટ ફોન્ટ મેનૂમાં દેખાય છે અને ઇન્સ્ટોલ કર્યા વિના વાપરી શકાય છે. + Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows. ટાઇપ પર ગ્રાફિક સ્ટાઇલ લાગુ કરવાથી, જ્યાં સ્ટાઇલમાં ફિલ કે સ્ટ્રોક હોય ત્યાં અક્ષરોનું પોતાનું ફિલ કે સ્ટ્રોક દૂર થાય છે, જેથી સ્ટાઇલનો રંગ દેખાય. + Align and Distribute measure point type by the ink of its glyphs instead of its em box. સંરેખિત કરો અને વિતરિત કરો પોઇન્ટ ટાઇપને તેના em બૉક્સને બદલે તેના ગ્લિફ્સની શાહીથી માપે છે. + Align and Distribute measure area type by the ink of its glyphs instead of its frame. સંરેખિત કરો અને વિતરિત કરો એરિયા ટાઇપને તેની ફ્રેમને બદલે તેના ગ્લિફ્સની શાહીથી માપે છે. + The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box. બાઉન્ડિંગ બૉક્સ અને ટ્રાન્સફોર્મ પેનલ પોઇન્ટ ટાઇપને તેના em બૉક્સને બદલે તેના ગ્લિફ્સની શાહીથી માપે છે. Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply. ગ્રિડ છુપાયેલી હોય ત્યારે પણ દોરવું, ખસેડવું અને સ્કેલ કરવું ગ્રિડના ઉપવિભાગો પર સ્નેપ કરે છે; આ ચાલુ હોય ત્યાં સુધી પિક્સેલ પર સ્નેપ લાગુ પડતું નથી. The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead. પસંદ ન કરેલી ગાઇડ્સનો રંગ; ગાઇડ લેબલવાળું આર્ટબોર્ડ પોતાની ગાઇડ્સ લેબલના રંગમાં દોરે છે. Draws guides as solid lines or as dots, including the guides already in the document. દસ્તાવેજમાં પહેલેથી રહેલી ગાઇડ્સ સહિત, ગાઇડ્સને ઘન રેખાઓ અથવા બિંદુઓ તરીકે દોરે છે. @@ -3280,6 +3346,7 @@ Rotation Y પરિભ્રમણ Y Rotation Z પરિભ્રમણ Z Rotation relative to: આના સાપેક્ષે પરિભ્રમણ: + Hue Jitter: રંગછટામાં ફેરફાર: Rotation: પરિભ્રમણ: Rough Pastels… રફ પેસ્ટલ્સ… Roughen… રફ બનાવો… @@ -3291,8 +3358,10 @@ Rounded Rectangle ગોળાકાર લંબચોરસ Rounded Rectangle Tool ગોળાકાર લંબચોરસ ટૂલ Rounded Rectangle… ગોળાકાર લંબચોરસ… + Roundness ગોળાઈ Roundness: ગોળાઈ: Row Size: પંક્તિનું માપ: + Rows પંક્તિઓ Rows: પંક્તિઓ: Ruby રૂબી Ruby… રૂબી… @@ -3500,6 +3569,12 @@ Search commands, tools, panels and effects… આદેશો, ટૂલ્સ, પેનલ્સ અને ઇફેક્ટ્સ શોધો… No commands match કોઈ આદેશ મેળ ખાતો નથી {pos} of {total}: {name} {total} માંથી {pos}: {name} + No menu item કોઈ મેનૂ આઇટમ નથી + Toolbar ટૂલબાર + {toolbar}, in the {tool} group {toolbar}, {tool} જૂથમાં + Tool ટૂલ + Command કમાન્ડ + Panel પેનલ @plural {n} result|{n} results {n} પરિણામ|{n} પરિણામો @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {n} માંથી {shown} પરિણામ. તેમને સંકુચિત કરવા લખતા રહો.|{n} માંથી {shown} પરિણામો. તેમને સંકુચિત કરવા લખતા રહો. Recent Commands તાજેતરના આદેશો @@ -3614,6 +3689,7 @@ Set Zoom ઝૂમ સેટ કરો Set as Default ડિફૉલ્ટ તરીકે સેટ કરો Set base color to the current color બેઝ રંગ વર્તમાન રંગ પર સેટ કરો + Set the current fill or stroke to the selected color વર્તમાન ભરો અથવા સ્ટ્રોક પસંદ કરેલ રંગ પર સેટ કરો Set the selected color to the current color પસંદ કરેલ રંગ વર્તમાન રંગ પર સેટ કરો Set {n} {n} સેટ કરો Settings સેટિંગ્સ @@ -3731,7 +3807,7 @@ Show its progress, see Cancel and write log lines તેની પ્રગતિ બતાવવી, રદ કરવાની વિનંતી જોવી અને લૉગ લાઇનો લખવી Show segmented color wheel સેગમેન્ટેડ રંગ ચક્ર બતાવો Show smooth color wheel સ્મૂધ રંગ ચક્ર બતાવો - Show/hide plate (Alt-click: only this plate) પ્લેટ બતાવો/છુપાવો (Alt-ક્લિક: માત્ર આ પ્લેટ) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) પ્લેટ બતાવો/છુપાવો (Alt-ક્લિક: માત્ર આ પ્લેટ; ફરી Alt-ક્લિક: બધી પ્લેટ) Show: બતાવો: Shown with the optimised preview. ઑપ્ટિમાઇઝ્ડ પ્રીવ્યૂ સાથે બતાવેલ. Side 1: બાજુ 1: @@ -3806,6 +3882,8 @@ Report Results પરિણામોનો અહેવાલ Smooth સ્મૂધ Smooth Anchors… એન્કર સ્મૂધ કરો… + Smooth Bridge સ્મૂધ બ્રિજ + Smooth Bridge… સ્મૂધ બ્રિજ… Smooth Tool સ્મૂધ ટૂલ Smooth… સ્મૂધ કરો… Smudge Stick… સ્મજ સ્ટિક… @@ -3881,6 +3959,7 @@ Start Normally સામાન્ય રીતે શરૂ કરો Start Tile શરૂઆતની ટાઇલ Start arrowhead શરૂઆતનું એરોહેડ + Start at: આનાથી શરૂ કરો: Start from VectorCraft Defaults VectorCraft ડિફૉલ્ટથી શરૂ કરો Start in Safe Mode સેફ મોડમાં શરૂ કરો Start: શરૂ: @@ -4037,6 +4116,8 @@ Thai થાઈ The Print Tiling tool placed the pages. પ્રિન્ટ ટાઇલિંગ ટૂલે પૃષ્ઠો ગોઠવ્યાં. The Scripts folder cannot be read સ્ક્રિપ્ટ્સ ફોલ્ડર વાંચી શકાતું નથી + Loading scripts… સ્ક્રિપ્ટ લોડ થઈ રહી છે… + The Scripts folder is still being read સ્ક્રિપ્ટ્સ ફોલ્ડર હજી વંચાઈ રહ્યું છે The VECTORCRAFT_TITLEBAR environment variable chooses the title bar while it is set. જ્યારે VECTORCRAFT_TITLEBAR એન્વાયર્નમેન્ટ વેરિએબલ સેટ હોય ત્યારે તે ટાઇટલ બાર પસંદ કરે છે. The active document changed while the screen color sampler was open સ્ક્રીન રંગ સેમ્પલર ખુલ્લું હતું ત્યારે સક્રિય દસ્તાવેજ બદલાયો The art keeps its own colors. આર્ટમાં પોતાના રંગો રહે છે. @@ -4081,6 +4162,13 @@ Three Point Perspective Preset 5 ત્રણ બિંદુ પર્સ્પેક્ટિવ પ્રીસેટ 5 Thumbnails: થંબનેલ: Tile ટાઇલ + Tile All Vertically બધું ઊભી રીતે ટાઇલ કરો + Tile All Horizontally બધું આડી રીતે ટાઇલ કરો + 2-Up Layout 2 નું લેઆઉટ + 3-Up Layout 3 નું લેઆઉટ + 4-Up Layout 4 નું લેઆઉટ + 6-Up Layout 6 નું લેઆઉટ + Arrange Documents દસ્તાવેજો ગોઠવો Tile Edge Color ટાઇલ કિનારીનો રંગ Tile Edge Color… ટાઇલ કિનારીનો રંગ… Tile Range: ટાઇલ શ્રેણી: @@ -4217,6 +4305,8 @@ Uniform યુનિફોર્મ Uniformly Scaled સમાન રીતે સ્કેલ કરેલ Unite યુનાઇટ + Unit Converter એકમ રૂપાંતરક + Unit Converter Panel એકમ રૂપાંતરક પેનલ Units એકમો Units: એકમો: Units: {units} એકમો: {units} @@ -4320,6 +4410,8 @@ Variable Font વેરિએબલ ફૉન્ટ Variable Options… વેરિએબલ વિકલ્પો… Variable Width Profile વેરિએબલ પહોળાઈ પ્રોફાઇલ + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. સ્ટ્રોકનું બ્રશ પોતાનું કદ જાળવે છે, તેથી પહોળાઈ પ્રોફાઇલ તેને બદલતી નથી. પ્રોફાઇલ વાપરવા માટે બ્રશ દૂર કરો. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. સ્ટ્રોકનું બ્રશ પોતાનું કદ જાળવે છે, તેથી પહોળાઈ પ્રોફાઇલ તેને બદલતી નથી. પ્રોફાઇલ વાપરવા માટે બ્રશ દૂર કરો. Variables વેરિએબલ્સ Variation: વેરિએશન: Vector Effects વેક્ટર અસરો @@ -4363,7 +4455,7 @@ Video વિડિયો Video Ruler Pixel Aspect Ratio: વિડિયો રૂલર પિક્સેલ ગુણોત્તર: View વ્યૂ - View Artboard Only માત્ર આર્ટબોર્ડ જુઓ + View Artboard Contents Only માત્ર આર્ટબોર્ડની સામગ્રી જુઓ View Opacity Mask ઓપેસિટી માસ્ક જુઓ View PDF after saving સાચવ્યા પછી PDF જુઓ Viewing Angle: જોવાનો ખૂણો: @@ -4468,6 +4560,10 @@ tile {number} ટાઇલ {number} to થી x-Height x-ઊંચાઈ + Ascent એસેન્ટ + x Height x ઊંચાઈ + Fixed નિશ્ચિત + Em Box Height Em બૉક્સ ઊંચાઈ {count} of {total} artboards {total} માંથી {count} આર્ટબોર્ડ {effect} is already applied {effect} પહેલેથી લાગુ છે {file}, line {line} {file}, લાઇન {line} @@ -4476,6 +4572,11 @@ {kind} Gradient {kind} ગ્રેડિયન્ટ {kind}, {model} {kind}, {model} {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View વ્હીલ વ્યૂ + Box View બૉક્સ વ્યૂ + Box Channel બૉક્સ ચેનલ + Color box રંગ બૉક્સ + Color Wheel Options રંગ વ્હીલ વિકલ્પો {name} (spot) {name} (સ્પૉટ) {pages} in all, {count} per copy કુલ {pages}, પ્રતિ નકલ {count} {page} of {count} {count} માંથી {page} @@ -4619,6 +4720,7 @@ antiAlias Sharp શાર્પ Include Placed Images પ્લેસ કરેલી ઇમેજો સામેલ કરો Include Fill Hatches ફિલ હેચિસ સામેલ કરો Use Monitor Profile for Canvas કેનવાસ માટે મોનિટર પ્રોફાઇલ વાપરો + Refresh Monitor Profile મોનિટર પ્રોફાઇલ તાજી કરો The canvas is drawn in sRGB. કેનવાસ sRGBમાં દોરાય છે. Canvas display profile: કેનવાસ ડિસ્પ્લે પ્રોફાઇલ: The system matches the window to the display's colors. સિસ્ટમ વિન્ડોના રંગો ડિસ્પ્લેના રંગો સાથે મેળવે છે. @@ -4945,6 +5047,13 @@ swatch [Registration] [રજિસ્ટ્રેશન] Repeat Objects પુનરાવર્તિત ઑબ્જેક્ટ્સ @msg `{path}` must be one of {_1}, not {got} `{path}` એ {_1}માંથી એક હોવું જોઈએ, {got} નહીં Path Length પાથની લંબાઈ + Grid Size ગ્રિડ સાઇઝ + Grid Colors ગ્રિડ રંગો + Flattener Preset ફ્લેટનર પ્રીસેટ + X X + Y Y + Orange નારંગી + Purple જાંબલી Packaging Tools પેકેજિંગ ટૂલ્સ Fold Lines ફોલ્ડ લાઇન્સ Make Cut Line કટ લાઇન બનાવો @@ -4982,6 +5091,16 @@ swatch [Registration] [રજિસ્ટ્રેશન] @msg A panel is not joined to the rest by a crease. એક પેનલ કોઈ ક્રીઝ લાઇનથી બાકીના સાથે જોડાયેલી નથી. @msg A fold line is on a non-printing layer. એક ફોલ્ડ લાઇન નોન-પ્રિન્ટિંગ લેયર પર છે. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} પેનલ: {panels}, હિન્જ: {hinges}, ભૂલો: {errors}, ચેતવણીઓ: {warnings} + Fold Preview ફોલ્ડ પ્રિવ્યૂ + Fold ફોલ્ડ + Show Fold Lines ફોલ્ડ લાઇન્સ બતાવો + Three-Quarter ત્રણ-ચતુર્થાંશ + Open a document to preview its folded shape. તેનો ફોલ્ડ કરેલો આકાર જોવા દસ્તાવેજ ખોલો. +@msg Check the fold lines first. પહેલાં ફોલ્ડ લાઇન્સ ચેક કરો. +@msg Panels: {panels}, hinges: {hinges} પેનલ: {panels}, હિન્જ: {hinges} +@msg Other blanks not shown: {count} બીજા બ્લેન્ક બતાવ્યા નથી: {count} +@msg A joint does not close by {gap} pt. એક સાંધો {gap} pt થી બંધ થતો નથી. +@msg Two panels pass through each other. બે પેનલ એકબીજામાંથી પસાર થાય છે. Middle Eastern & South Asian Single-line Composer સિંગલ-લાઇન કમ્પોઝર (મધ્ય પૂર્વ અને દક્ષિણ એશિયા) Middle Eastern & South Asian Every-line Composer એવરી-લાઇન કમ્પોઝર (મધ્ય પૂર્વ અને દક્ષિણ એશિયા) Standard Single-line Composer સ્ટાન્ડર્ડ સિંગલ-લાઇન કમ્પોઝર diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index cbfb4f51d1..98866a4a85 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -213,6 +213,7 @@ Add Anchor Point एंकर पॉइंट जोड़ें Add Anchor Point Tool ऐड एंकर पॉइंट टूल Add Anchor Points एंकर पॉइंट जोड़ें + Add Around ऑब्जेक्ट के चारों ओर जोड़ें Add Anchors एंकर जोड़ें Add Anchors… एंकर जोड़ें… Add as Effect इफ़ेक्ट के रूप में जोड़ें @@ -256,7 +257,11 @@ Add Used Colors उपयोग किए रंग जोड़ें Additional Fonts Folder अतिरिक्त फ़ॉन्ट फ़ोल्डर Additional Plug-ins Folder अतिरिक्त प्लग-इन फ़ोल्डर + Plug-in Instruction Budget प्लग-इन निर्देश बजट Adjust Adjoining Width Points सटे हुए चौड़ाई पॉइंट समायोजित करें + Incoming आने वाली ओर + Outgoing जाने वाली ओर + Single Width Only केवल एक चौड़ाई Adjust Color Balance… कलर बैलेंस समायोजित करें… Adjust Colors रंग समायोजित करें Adjust Options: समायोजन ऑप्शन्स: @@ -343,6 +348,7 @@ Angular कोणीय Angular Guides कोणीय गाइड्स Animated Zoom एनिमेटेड ज़ूम + Anti Alias एंटी-एलियासिंग Anti-alias एंटी-एलियास Anti-Alias एंटी-एलियास Anti-alias Rasters रास्टर एंटी-एलियास करें @@ -532,6 +538,7 @@ antiAlias Sharp शार्प Average… औसत… Away from the Line लाइन से दूर Axis अक्ष + Axis Angle अक्ष कोण Axis side अक्ष की तरफ़ Axis: अक्ष: B4 B4 @@ -692,6 +699,12 @@ antiAlias Sharp शार्प Brush Library ब्रश लाइब्रेरी Brush Options ब्रश ऑप्शन्स Brush Options… ब्रश ऑप्शन्स… + Options of Selected Object… सिलेक्टेड ऑब्जेक्ट के ऑप्शन्स… + Options of Selected Object सिलेक्टेड ऑब्जेक्ट के ऑप्शन्स +@msg no path painted with a brush is selected ब्रश से पेंट किया गया कोई पाथ नहीं चुना गया +@msg the selected paths are painted with brushes of different types चुने गए पाथ अलग-अलग प्रकार के ब्रश से पेंट किए गए हैं +@msg give `params` or `reset`, not both `params` या `reset` दें, दोनों नहीं +@msg a bristle brush has no options of its own on a path ब्रिसल ब्रश के किसी पाथ पर अपने ऑप्शन्स नहीं होते Brush Scale Options ब्रश स्केल ऑप्शन्स Brush Size ब्रश साइज़ Brush Strokes ब्रश स्ट्रोक्स @@ -793,6 +806,11 @@ antiAlias Sharp शार्प Character Direction कैरेक्टर दिशा Character options कैरेक्टर ऑप्शन्स Character Rotation कैरेक्टर रोटेशन + Chinese Big 5 चीनी Big 5 + Cyrillic सिरिलिक + Greek ग्रीक + Baltic बाल्टिक + Central European मध्य यूरोपीय Character Set: कैरेक्टर सेट: Character Style कैरेक्टर स्टाइल Character Style Options कैरेक्टर स्टाइल ऑप्शन्स @@ -820,6 +838,8 @@ antiAlias Sharp शार्प Chrome क्रोम Chrome… क्रोम… Circle वृत्त + Circle Tool वृत्त टूल + Circle too large वृत्त बहुत बड़ा है Circle (open) सर्किल (ओपन) Circle: वृत्त: Classic क्लासिक @@ -936,6 +956,7 @@ antiAlias Sharp शार्प Color Mixer (Shift-click the chip) कलर मिक्सर (रंग चिप पर Shift-क्लिक करें) Color Mode रंग मोड Color Mode: रंग मोड: + Color Model रंग मॉडल Color Model: रंग मॉडल: Color Models रंग मॉडल Color Panel Options रंग पैनल ऑप्शन्स @@ -958,6 +979,11 @@ antiAlias Sharp शार्प Saturation and brightness सैचुरेशन और ब्राइटनेस Color field कलर फ़ील्ड {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View व्हील व्यू + Box View बॉक्स व्यू + Box Channel बॉक्स चैनल + Color box कलर बॉक्स + Color Wheel Options कलर व्हील ऑप्शन्स Color Type: रंग का प्रकार: Color wheel कलर व्हील Color: रंग: @@ -973,6 +999,7 @@ antiAlias Sharp शार्प Column Type: स्तंभ प्रकार: Column Width: कॉलम चौड़ाई: Column… स्तंभ… + Columns कॉलम Columns: कॉलम: Combine Point Text पॉइंट टेक्स्ट को मिलाएं Combine Slices संयोजन स्लाइस @@ -1086,6 +1113,7 @@ antiAlias Sharp शार्प Copy Selected Style सिलेक्टेड स्टाइल को कॉपी करें Copy to User Defined उपयोगकर्ता परिभाषित करने के लिए कॉपी करें Copy Width Point कॉपी चौड़ाई पॉइंट + Copy with Units इकाइयों के साथ कॉपी करें Copyright कॉपीराइट Copyright and Contact Info कॉपीराइट और संपर्क जानकारी Copyright Info URL: कॉपीराइट जानकारी URL: @@ -1289,6 +1317,8 @@ antiAlias Sharp शार्प Delete Artboard आर्टबोर्ड हटाएँ Delete Artboards आर्टबोर्ड्स हटाएँ Delete Brush ब्रश हटाएँ + Delete Color रंग हटाएँ + Restore Generated Table जनरेट की गई तालिका पुनर्स्थापित करें Delete Character Style कैरेक्टर स्टाइल हटाएँ Delete Data Set डेटा सेट हटाएँ Delete Data Sets डेटा सेट्स हटाएँ @@ -1395,6 +1425,7 @@ antiAlias Sharp शार्प Direction: दिशा: Directives निर्देश Disable Auto Add/Delete ऑटो जोड़ना/हटाना अक्षम करें + Interpolate Control Points When Moving Anchors एंकर पॉइंट खिसकाते समय निर्देशन हैंडल इंटरपोलेट करें Disable Opacity Mask ओपेसिटी मास्क अक्षम करें Discard डिस्कर्ड Discard Empty Type खाली टाइप हटाएँ @@ -1696,6 +1727,7 @@ antiAlias Sharp शार्प Enable text access for screen readers स्क्रीन रीडर के लिए टेक्स्ट एक्सेस सक्षम करें Enable Touch Gestures टच जेस्चर ऑन करें Switch Selection and Drawing Modes चयन और ड्रॉइंग मोड के बीच बदलें + Select Last Selection Tool पिछला सिलेक्शन टूल चुनें Enable Touch Workspace टच वर्कस्पेस सक्षम करें Enclosing Lasso लासो संलग्न करना Enclosing Lasso Tool लासो टूल संलग्न करना @@ -1898,6 +1930,8 @@ antiAlias Sharp शार्प Files फ़ाइलें Files of a PDF standard can't be password-protected. एक PDF मानक की फ़ाइलें पासवर्ड की रक्षा नहीं की जा सकती है। Files of this standard tag their colours with ICC profiles. इस मानक की फ़ाइलें ICC प्रोफ़ाइल के साथ उनके रंगों को टैग करती हैं। + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. इस मानक की फ़ाइलें ICC प्रोफ़ाइल के साथ उनके रंगों को टैग करती हैं, आउटपुट इंटेंट प्रोफ़ाइल के CMYK रंगों को छोड़कर, जो DeviceCMYK के रूप में लिखे जाते हैं। + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. “प्रोफ़ाइल शामिल नहीं है” और CMYK आउटपुट इंटेंट के साथ, हर CMYK रंग DeviceCMYK के रूप में लिखा जाता है, जब तक कि उसे किसी अन्य प्रोफ़ाइल के CMYK गंतव्य में रूपांतरित न किया जाए। Fill फ़िल Fill (X), double-click for the Color Picker फ़िल (X), कलर पिकर के लिए डबल-क्लिक करें Fill & Stroke भरें और स्ट्रोक करें @@ -2057,8 +2091,10 @@ antiAlias Sharp शार्प Fresco… फ़्रेस्को… from the format's public description फ़ॉर्मैट के सार्वजनिक विवरण से from your earlier imports अपने पहले आयात से + From Selection सिलेक्शन से From: से: Front सामने + Side बगल Frosted फ़्रॉस्टेड Full Document पूरा डॉक्यूमेंट Full Justify फुल जस्टिफ़ाई @@ -2338,6 +2374,8 @@ antiAlias Sharp शार्प Highlight anchors on mouse over माउस ओवर पर हाइलाइट एंकर Highlight Area हाइलाइट क्षेत्र Highlight Font Name हाइलाइट फ़ॉन्ट नाम + Highlight Font Size हाइलाइट फ़ॉन्ट साइज़ + Other… अन्य… Highlight Kerning हाइलाइट कर्निंग Highlight Rows हाइलाइट पंक्तियाँ Highlight Substituted Fonts हाईलाइट सबस्टिट्यूटेड फ़ॉन्ट @@ -2563,6 +2601,7 @@ antiAlias Sharp शार्प Keep graphics, colors and text styles here to use them in any document. Libraries are stored on this machine — no account required. ग्राफ़िक्स, रंग और टेक्स्ट स्टाइल्स यहाँ रखें ताकि किसी भी डॉक्यूमेंट में उपयोग कर सकें। लाइब्रेरीज़ इसी कंप्यूटर पर रहती हैं — अकाउंट की ज़रूरत नहीं है। Keep Handles हैंडल रखें Keep Original मूल रखें + Keep Originals मूल रखें Keep Plain Text प्लेन टेक्स्ट रखें Keep selected सिलेक्ट करें Keep Shared Points Together साझा पॉइंट्स एक साथ रखें @@ -2744,6 +2783,7 @@ antiAlias Sharp शार्प Linked Files लिंक्ड फ़ाइलें Links लिंक Linux Display Server Linux डिस्प्ले सर्वर + Low-Latency Drawing कम विलंब वाली ड्राइंग Liquify लिक्विफ़ाई List Data Sets सूची डेटा सेट List Folder सूची फ़ोल्डर @@ -2767,6 +2807,7 @@ antiAlias Sharp शार्प Live Shape लाइव आकार Live Shape Properties लाइव शेप प्रॉपर्टीज़ Load Actions… एक्शन्स लोड करें… + Replace Actions… एक्शन्स रिप्लेस करें… Reset Actions एक्शन्स रीसेट करें Replace the current actions with the default set? मौजूदा एक्शन्स को डिफ़ॉल्ट सेट से बदलें? Append adds the default set after the current sets instead. जोड़ें इसके बजाय डिफ़ॉल्ट सेट को मौजूदा सेट के बाद जोड़ता है। @@ -2787,6 +2828,7 @@ antiAlias Sharp शार्प Loads native code मूल कोड लोड करता है Local Libraries स्थानीय लाइब्रेरी Locate Library… लाइब्रेरी… + Locate Layer लेयर का पता लगाएं Locate Object ऑब्जेक्ट का पता लगाएं Locate Selected Objects सिलेक्टेड ऑब्जेक्ट्स का पता लगाएँ Location स्थान @@ -3430,6 +3472,9 @@ antiAlias Sharp शार्प Overprint ओवरप्रिंट Overprint and Transparency Flattener ओवरप्रिंट और ट्रांसपेरेंसी फ़्लैटनर Overprint and Transparency Flattener Options ओवरप्रिंट और ट्रांसपेरेंसी फ़्लैटनर ऑप्शन्स + Custom… कस्टम… + Custom Transparency Flattener Options कस्टम ट्रांसपेरेंसी फ़्लैटनर ऑप्शन्स + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS में अल्फा पारदर्शिता नहीं होती, और ओवरप्रिंट तय करता है कि ओवरप्रिंट रखे जाएँ या नहीं। Overprint Black ओवरप्रिंट ब्लैक Overprint Black… ओवरप्रिंट ब्लैक… Overprint Fill फ़िल ओवरप्रिंट करें @@ -3498,6 +3543,11 @@ antiAlias Sharp शार्प Path Eraser पाथ इरेज़र Path Eraser Tool पाथ इरेज़र टूल Path Length पाथ की लंबाई + Grid Size ग्रिड साइज़ + Grid Colors ग्रिड रंग + Flattener Preset फ़्लैटनर प्रीसेट + X X + Y Y Path Only केवल पाथ Path Precision Tools पाथ परिशुद्धता टूल Path: पाथ: @@ -3697,6 +3747,10 @@ antiAlias Sharp शार्प Polish पोलिश Polygon बहुभुज Polygon Properties: बहुभुज प्रॉपर्टीज़: + Line Properties: रेखा प्रॉपर्टीज़: + Line Length: रेखा की लंबाई: + Line Angle: रेखा का कोण: + Constrain Pie Angle पाई एंगल बनाए रखें Polygon Tool पॉलीगोन टूल Polygonal Lasso बहुभुज लैस्सो Polygonal Lasso Tool बहुभुज लैस्सो टूल @@ -3901,6 +3955,9 @@ antiAlias Sharp शार्प Real World: रियल वर्ल्ड: Real-time Drawing and Editing रियल टाइम ड्राइंग और संपादन Use Monitor Profile for Canvas कैनवास के लिए मॉनिटर प्रोफ़ाइल का उपयोग करें + Refresh Monitor Profile मॉनिटर प्रोफ़ाइल रिफ्रेश करें +@msg turn on Use Monitor Profile for Canvas first पहले "कैनवास के लिए मॉनिटर प्रोफ़ाइल का उपयोग करें" चालू करें +@msg this build doesn't read display profiles यह बिल्ड डिस्प्ले प्रोफ़ाइल नहीं पढ़ता The canvas is drawn in sRGB. कैनवास sRGB में बनाया जाता है। Canvas display profile: कैनवास की डिस्प्ले प्रोफ़ाइल: The system matches the window to the display's colors. सिस्टम विंडो को डिस्प्ले के रंगों से मिलाता है। @@ -4124,6 +4181,8 @@ antiAlias Sharp शार्प Reset Automation स्वचालन रीसेट करें Reset Bar Position बार स्थिति रीसेट करें Reset Bounding Box बाउंडिंग बॉक्स रीसेट करें + Rotate Bounding Box बाउंडिंग बॉक्स घुमाएँ + Rotate Bounding Box… बाउंडिंग बॉक्स घुमाएँ… Reset Envelope Mesh एन्वेलप मेश रीसेट करें Reset Envelope Shape एन्वेलप शेप रीसेट करें Reset Essentials एसेंशियल्स रीसेट करें @@ -4189,6 +4248,7 @@ antiAlias Sharp शार्प Resize panels पैनलों का साइज़ बदलें Resize Slice स्लाइस का आकार Resize Type Area टाइप एरिया का आकार बदलें + Resolution रिज़ॉल्यूशन Resolution: रिज़ॉल्यूशन: Responsive उत्तरदायी Restore पुनर्स्थापित करें @@ -4215,6 +4275,7 @@ antiAlias Sharp शार्प The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Cmd/Ctrl दबाकर माउस व्हील घुमाने से कैनवास बगल की ओर स्क्रॉल होता है। Dragging sideways on a numeric field's label changes the field's value. किसी संख्या वाले फ़ील्ड के लेबल पर बगल की ओर ड्रैग करने से फ़ील्ड का मान बदलता है। A two-finger rotate gesture on a trackpad rotates the canvas view. ट्रैकपैड पर दो उंगलियों से घुमाने का जेस्चर कैनवास के व्यू को घुमाता है। + When you move anchor points, each curve with one moved end keeps its shape relative to its ends. जब आप एंकर पॉइंट हिलाते हैं, तो एक हिले हुए सिरे वाला हर वक्र अपने सिरों के सापेक्ष अपना आकार बनाए रखता है। Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. किसी टूल की शॉर्टकट कुंजी दबाए रखने पर वह टूल छोड़ने तक चुना रहता है, फिर पिछला टूल दोबारा चुना जाता है। Shows the bounding box while you move the selection or draw a shape. सिलेक्शन खिसकाते या आकार ड्रॉ करते समय बाउंडिंग बॉक्स दिखाता है। Create Trim Marks draws Japanese-style marks instead of Roman ones. ट्रिम मार्क्स बनाएं रोमन की जगह जापानी शैली के निशान ड्रॉ करता है। @@ -4245,6 +4306,29 @@ antiAlias Sharp शार्प The unit for East Asian type measurements, which no field uses yet. पूर्वी एशियाई टाइप के माप की इकाई, जिसका अभी कोई फ़ील्ड उपयोग नहीं करता। When on, a number typed without a unit into a field in picas is read in points. चालू होने पर, पाइका वाले फ़ील्ड में बिना इकाई के टाइप की गई संख्या पॉइंट्स में पढ़ी जाती है। With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options. XML ID चुनने पर ऑब्जेक्ट के नाम लेयर्स, वेरिएबल्स और लेयर ऑप्शन्स में XML ID के रूप में दिखते हैं। + The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl. टाइप साइज़ और लीडिंग का स्टेप: Cmd/Ctrl+Shift+. और Cmd/Ctrl+Shift+, साइज़ को एक स्टेप बदलते हैं, और Alt के साथ पाँच स्टेप; क्षैतिज टाइप में Alt के साथ ऊपर या नीचे का एरो लीडिंग को एक स्टेप बदलता है, और Cmd/Ctrl के साथ पाँच स्टेप। + The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl. ट्रैकिंग और कर्निंग का स्टेप, em के हज़ारवें हिस्सों में: क्षैतिज टाइप में Alt के साथ बायाँ या दायाँ एरो कैरेट पर कर्निंग या चुने हुए टेक्स्ट की ट्रैकिंग को एक स्टेप बदलता है, और Cmd/Ctrl के साथ पाँच स्टेप। + The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. बेसलाइन शिफ़्ट का स्टेप: क्षैतिज टाइप में Alt और Shift के साथ ऊपर या नीचे का एरो बेसलाइन को एक स्टेप खिसकाते हैं, और Cmd/Ctrl के साथ पाँच स्टेप। + Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. कैरेक्टर, पैराग्राफ़, OpenType और ग्लिफ़्स पैनल में जापानी और दूसरे पूर्वी एशियाई टाइप के ऑप्शन्स, और कंपोज़िट फ़ॉन्ट कमांड दिखाता है। + Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. कैरेक्टर और पैराग्राफ़ पैनल में अरबी, हिब्रू और भारतीय टाइप के ऑप्शन्स दिखाता है, जैसे पैराग्राफ़ की दिशा, कशीदे और अंक। + The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. सिलेक्शन टूल टाइप को सिर्फ़ उसकी बेसलाइन, एरिया टाइप के फ़्रेम या उसके पाथ पर चुनते हैं, उसके बॉक्स के अंदर कहीं भी नहीं। + Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. फ़ॉन्ट मेनू हर फ़ॉन्ट को उसके अंग्रेज़ी नाम से दिखाते हैं; बंद होने पर, जिस फ़ॉन्ट का अपनी भाषा में भी नाम है, वह वही नाम दिखाता है। + New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. नया एरिया टाइप ऑटो साइज़ चालू होकर शुरू होता है, इसलिए क्षैतिज टाइप का आयताकार फ़्रेम अपने टेक्स्ट के हिसाब से ऊँचाई में बढ़ता या घटता है। + Font lists and the Type › Font menu show a sample of each font beside its name. फ़ॉन्ट सूचियाँ और फ़ॉन्ट मेनू हर फ़ॉन्ट के नाम के पास उसका नमूना दिखाते हैं। + Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on. फ़ॉन्ट नमूने इंटरफ़ेस की चमक चाहे जो हो, सफ़ेद पर गहरे टाइप में बनाए जाते हैं; यह तभी लागू होता है जब मेनू में फ़ॉन्ट प्रीव्यू चालू हों। + How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is. फ़ॉन्ट फ़ील्ड की सूचियों में, जैसे कैरेक्टर पैनल वाली में, हर पंक्ति कितनी ऊँची है, और इसलिए हर नमूना कितना बड़ा है। + How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first. हाल के फ़ॉन्ट्स और फ़ॉन्ट सूचियाँ आख़िरी बार इस्तेमाल किए गए कितने फ़ॉन्ट दिखाती हैं, 1 से 15 तक, सबसे नया पहले। + When you change the font or font style of text, characters the new font has no glyph for keep the font they had. जब आप टेक्स्ट का फ़ॉन्ट या फ़ॉन्ट स्टाइल बदलते हैं, तो जिन कैरेक्टर का ग्लिफ़ नए फ़ॉन्ट में नहीं है, वे अपना पुराना फ़ॉन्ट रखते हैं। + A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export. कैनवस पर गुलाबी हाइलाइट उन ग्लिफ़्स को दिखाता है जिन्हें OpenType फ़ीचर्स ने बदला है, जैसे लिगेचर; यह प्रिंट या एक्सपोर्ट नहीं होता। + With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from. टाइप टूल से एक कैरेक्टर चुनने पर कैनवस पर उसके पास चुनने के लिए उसके वैकल्पिक ग्लिफ़्स की एक पंक्ति दिखती है। + A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export. कैनवस पर गुलाबी हाइलाइट उस टेक्स्ट को दिखाता है जो अपना फ़ॉन्ट न होने के कारण किसी दूसरे फ़ॉन्ट में बना है; यह प्रिंट या एक्सपोर्ट नहीं होता। + New type made with a Type tool starts with placeholder text, selected, so typing replaces it. टाइप टूल से बना नया टाइप चुने हुए प्लेसहोल्डर टेक्स्ट से शुरू होता है, जिसे टाइप करने पर आपका टेक्स्ट बदल देता है। + Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list. पैराग्राफ़ की शुरुआत में 1. या * जैसा सूची चिह्न और फिर स्पेस टाइप करने से पैराग्राफ़ सूची बन जाता है। + Fonts in this folder show in the font menus and can be used without being installed. इस फ़ोल्डर के फ़ॉन्ट फ़ॉन्ट मेनू में दिखते हैं और इंस्टॉल किए बिना इस्तेमाल किए जा सकते हैं। + Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows. टाइप पर ग्राफ़िक स्टाइल लगाने से, जहाँ स्टाइल में फ़िल या स्ट्रोक है वहाँ कैरेक्टर का अपना फ़िल या स्ट्रोक हट जाता है, ताकि स्टाइल का पेंट दिखे। + Align and Distribute measure point type by the ink of its glyphs instead of its em box. अलाइन और डिस्ट्रिब्यूट पॉइंट टाइप को उसके em बॉक्स के बजाय उसके ग्लिफ़्स की स्याही से मापते हैं। + Align and Distribute measure area type by the ink of its glyphs instead of its frame. अलाइन और डिस्ट्रिब्यूट एरिया टाइप को उसके फ़्रेम के बजाय उसके ग्लिफ़्स की स्याही से मापते हैं। + The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box. बाउंडिंग बॉक्स और ट्रांसफ़ॉर्म पैनल पॉइंट टाइप को उसके em बॉक्स के बजाय उसके ग्लिफ़्स की स्याही से मापते हैं। Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply. ग्रिड छिपी होने पर भी ड्रॉ करना, खिसकाना और स्केल करना ग्रिड के उप-विभाजनों पर स्नैप करता है; इसके चालू रहने तक पिक्सेल के लिए स्नैप लागू नहीं होता। The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead. उन गाइड्स का रंग जो चयनित नहीं हैं; गाइड लेबल वाला आर्टबोर्ड अपनी गाइड्स लेबल के रंग में बनाता है। Draws guides as solid lines or as dots, including the guides already in the document. दस्तावेज़ में पहले से मौजूद गाइड्स सहित, गाइड्स को ठोस रेखाओं या बिंदुओं के रूप में बनाता है। @@ -4337,6 +4421,7 @@ antiAlias Sharp शार्प Rotate… घुमाव… Rotation घुमाव Rotation relative to: इसके सापेक्ष: + Hue Jitter: रंगत में भिन्नता: Rotation X रोटेशन X Rotation Y रोटेशन वाई Rotation Z रोटेशन Z @@ -4357,8 +4442,10 @@ antiAlias Sharp शार्प Rounded Rectangle गोल आयत Rounded Rectangle Tool राउंडेड रेक्टेंगल टूल Rounded Rectangle… गोल आयत… + Roundness राउंडनेस Roundness: राउंडनेस: Row Size: पंक्ति का आकार: + Rows पंक्तियाँ Rows: पंक्तियाँ: Ruby रूबी Ruby… रूबी… @@ -4567,6 +4654,9 @@ antiAlias Sharp शार्प Search commands, tools, panels and effects… आदेश, टूल, पैनल्स और इफ़ेक्ट्स खोजें… No commands match कोई आदेश मेल नहीं खाता {pos} of {total}: {name} {total} में से {pos}: {name} + No menu item कोई मेनू आइटम नहीं + Toolbar टूलबार + {toolbar}, in the {tool} group {toolbar}, {tool} समूह में @plural {n} result|{n} results {n} परिणाम|{n} परिणाम @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {n} में से {shown} परिणाम। इन्हें सीमित करने के लिए लिखते रहें।|{n} में से {shown} परिणाम। इन्हें सीमित करने के लिए लिखते रहें। Recent Commands हाल के आदेश @@ -4699,6 +4789,7 @@ antiAlias Sharp शार्प Set Slice Rectangle सेट स्लाइस आयत Set Tab Stops टैब स्टॉप्स सेट करें Set Text टेक्स्ट सेट करें + Set the current fill or stroke to the selected color वर्तमान फ़िल या स्ट्रोक को सिलेक्टेड रंग में सेट करें Set the selected color to the current color सिलेक्टेड रंग को वर्तमान रंग में सेट करें Set Zoom ज़ूम सेट करें Set: सेट: @@ -4873,7 +4964,7 @@ antiAlias Sharp शार्प Show Vivid/Muted चमकीले/मंद दिखाएँ Show Warm/Cool शो वार्म / कूल Show: दिखाएँ: - Show/hide plate (Alt-click: only this plate) प्लेट दिखाएँ/छिपाएँ (Alt-क्लिक: केवल यही प्लेट) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) प्लेट दिखाएँ/छिपाएँ (Alt-क्लिक: केवल यही प्लेट; फिर से Alt-क्लिक: सभी प्लेटें) Shown with the optimised preview. आशावादी प्रीव्यू के साथ दिखाया गया है। Shrink Text to Fit टेक्स्ट को फिट करने के लिए सिकोड़ें Side 1: साइड 1: @@ -4968,6 +5059,8 @@ antiAlias Sharp शार्प Smooth स्मूथ Smooth Anchors चिकना एंकर Smooth Anchors… चिकना एंकर… + Smooth Bridge स्मूद ब्रिज + Smooth Bridge… स्मूद ब्रिज… Smooth Color चिकना रंग Smooth Tool चिकना टूल Smooth… चिकना करें… @@ -5283,7 +5376,7 @@ antiAlias Sharp शार्प Composite Fonts कंपोज़िट फ़ॉन्ट Export Composite Fonts कंपोज़िट फ़ॉन्ट एक्सपोर्ट करें Import Composite Fonts कंपोज़िट फ़ॉन्ट इम्पोर्ट करें -@msg each font must be {name, parts} हर फ़ॉन्ट {name, parts} होना चाहिए +@msg each font must be {{name, parts}} हर फ़ॉन्ट {{name, parts}} होना चाहिए @msg unknown key `{k}`; a font takes name and parts अज्ञात कुंजी `{k}`; फ़ॉन्ट name और parts लेता है @msg each font needs a name हर फ़ॉन्ट का एक नाम होना चाहिए @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` कंपोज़िट फ़ॉन्ट का नाम नहीं हो सकता (1 से {COMPOSITE_NAME_MAX} अक्षर, कोई नियंत्रण अक्षर नहीं) @@ -5296,7 +5389,10 @@ antiAlias Sharp शार्प @msg two composite fonts are named `{_1}` दो कंपोज़िट फ़ॉन्ट का नाम `{_1}` है @msg `{_1}` is the name of an installed font `{_1}` एक इंस्टॉल किए गए फ़ॉन्ट का नाम है @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2} `{font}` में सेट है, जो एक कंपोज़िट फ़ॉन्ट है -@msg give fonts: [{name, parts}…] fonts दें: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] fonts दें: [{{name, parts}}…] +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` को "document", {{artboards: [index, …]}} या {{layers: [id, …]}} होना चाहिए +@msg numbers out of order in {{}} quantifier {{}} क्वांटिफ़ायर में संख्याएँ क्रम में नहीं हैं +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) पेंट फ्रीफॉर्म ग्रेडिएंट नहीं है (paint.editGradient {{kind: "freeform"}} से एक लागू करें) @msg path is empty path खाली है @msg fonts must be a list of composite fonts fonts कंपोज़िट फ़ॉन्ट की सूची होनी चाहिए @msg names must be strings names स्ट्रिंग होने चाहिए @@ -5417,6 +5513,13 @@ antiAlias Sharp शार्प TIFF (8-bit Color) TIFF (8-बिट रंग) TIFF (Black & White) TIFF (ब्लैक एंड व्हाइट) Tile टाइल + Tile All Vertically सभी को लंबवत टाइल करें + Tile All Horizontally सभी को क्षैतिज टाइल करें + 2-Up Layout 2 का लेआउट + 3-Up Layout 3 का लेआउट + 4-Up Layout 4 का लेआउट + 6-Up Layout 6 का लेआउट + Arrange Documents दस्तावेज़ व्यवस्थित करें tile {number} टाइल {number} Tile Edge Color टाइल एज रंग Tile Edge Color… टाइल एज रंग… @@ -5599,6 +5702,8 @@ antiAlias Sharp शार्प Unique अनोखा Unite मिलाएँ Unite and Simplify एकजुट और सरलीकरण + Unit Converter इकाई कनवर्टर + Unit Converter Panel इकाई कनवर्टर पैनल Units इकाइयाँ Units & Scale इकाइयों और स्केल Units: इकाइयाँ: @@ -5722,6 +5827,8 @@ antiAlias Sharp शार्प Variable Options वेरिएबल ऑप्शन्स Variable Options… वेरिएबल ऑप्शन्स… Variable Width Profile वेरिएबल चौड़ाई प्रोफ़ाइल + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. स्ट्रोक का ब्रश अपना आकार बनाए रखता है, इसलिए चौड़ाई प्रोफ़ाइल उसे नहीं बदलती। प्रोफ़ाइल का उपयोग करने के लिए ब्रश निकालें। +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. स्ट्रोक का ब्रश अपना आकार बनाए रखता है, इसलिए चौड़ाई प्रोफ़ाइल उसे नहीं बदलती। प्रोफ़ाइल का उपयोग करने के लिए ब्रश निकालें। Variables वेरिएबल्स Variation वैरिएशन Variation: भिन्नता: @@ -5779,7 +5886,7 @@ antiAlias Sharp शार्प Video Thumbnail 1280×720 वीडियो थंबनेल 1280 × 720 View व्यू View {n} {n} - View Artboard Only केवल आर्टबोर्ड देखें + View Artboard Contents Only केवल आर्टबोर्ड की सामग्री देखें View Opacity Mask ओपेसिटी मास्क देखें View PDF after saving सेव करने के बाद PDF देखें View: व्यू: @@ -5852,6 +5959,7 @@ antiAlias Sharp शार्प Write Layers लेयर लिखें Writes, moves or deletes files फ़ाइलों को राइट्स, मूव या डिलीट करता है x Height x ऊँचाई + Em Box Height एम बॉक्स ऊँचाई X Position X स्थिति x-height x-ऊँचाई x-Height x-ऊँचाई @@ -6162,6 +6270,8 @@ antiAlias Sharp शार्प @msg {label}: lost track of a shape's style {label}: एक आकार की स्टाइल का ट्रैक खो गया @msg {label}: select paths {label}: चुनें पाथ @msg {label}: select paths, compound paths, groups or text {label}: चुनें पाथ, यौगिक पाथ, समूह या टेक्स्ट +@msg a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first कोई रेखा या अन्य खुला पाथ जो कोई क्षेत्र नहीं घेरता, परिणाम के आकार को नहीं बदलता; इसे शामिल करने के लिए पहले उस पर ऑब्जेक्ट › पाथ › स्ट्रोक को आउटलाइन में बदलें लागू करें +@msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first {label} ने खाली परिणाम का उत्पादन किया: कोई रेखा या अन्य खुला पाथ कोई क्षेत्र नहीं घेरता; इसे शामिल करने के लिए पहले उस पर ऑब्जेक्ट › पाथ › स्ट्रोक को आउटलाइन में बदलें लागू करें @msg {label}… {label}... @msg {name} `{s}`: {ids} {name} `{s}`: {ids} @msg {name} is built in and can't be deleted {name} बनाया गया है और इसे हटाया नहीं जा सकता है। @@ -6184,6 +6294,8 @@ antiAlias Sharp शार्प @msg {std} files embed their fonts, and the file would have one that isn't {std} फ़ाइलें अपने फ़ॉन्ट एम्बेड करती हैं, और इस फ़ाइल में एक ऐसा फ़ॉन्ट होता जो एम्बेड नहीं है @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} से पढ़ा गया था और पढ़ते समय कुछ चीज़ें छूट गईं ({what}): उसी फ़ाइल पर लिखने से वे स्थायी रूप से खो जाएँगी। दूसरी फ़ाइल लिखें या फिर भी बदलने के लिए acknowledgeLoss: true दें @msg {tool} isn't in a toolbar group of several tools {tool} कई टूल्स के टूलबार समूह में नहीं है +@msg Presentation Mode hides the toolbars: change the screen mode to show them प्रस्तुति मोड टूलबार्स छिपाता है: उन्हें दिखाने के लिए स्क्रीन मोड बदलें +@msg Tab has hidden the toolbars: press Tab to show them Tab ने टूलबार्स छिपा दिए हैं: उन्हें दिखाने के लिए Tab दबाएँ @msg {ty} brushes need selected art (or params.{k}) {ty} ब्रश के लिए सिलेक्टेड आर्टवर्क (या params.{k}) चाहिए @msg {v} is not an asset id {v} एक परिसंपत्ति आईडी नहीं है @msg {what} can't be intertwined {what} अंतर नहीं किया जा सकता है @@ -6213,6 +6325,8 @@ antiAlias Sharp शार्प @msg `{id}` is no writable format (see document.formats) `{id}` लिखने योग्य फ़ॉर्मैट नहीं है (document.formats देखें) @msg `{id}` is not a colour adjustment `{id}` एक रंग समायोजन नहीं है @msg `{id}` isn't a loaded library `{id}` एक लोड लाइब्रेरी नहीं है +@msg `{file}` has no swatches of its own `{file}` में अपने कोई स्वॉचेस नहीं हैं +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` में पैटर्न स्वॉचेस हैं, जिन्हें .vcswatches फ़ाइल नहीं रख सकती @msg `{k}.family` is required `{k}.family` की आवश्यकता है @msg `{k}` is a number 0..1 `{k}` एक नंबर 0..1 है। @msg `{k}` is true or false `{k}` true या false है @@ -6460,6 +6574,8 @@ antiAlias Sharp शार्प @msg `mode` must be "handles", "straight" or "smooth" `mode` को "handles", "straight" या "smooth" होना चाहिए @msg `mode` must be "straight", "bezier" or "arc" `mode` को "straight", "bezier" या "arc" होना चाहिए @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` को grayscale, rgb, hsb, cmyk या websafe होना चाहिए +@msg `view` must be wheel or box `view` को wheel या box होना चाहिए +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` को hue, saturation, brightness, red, green या blue होना चाहिए @msg `mode` must be one of {_1} `mode` को {_1} में से एक होना चाहिए @msg `mojikumi` must be "none", "yakumonoHankaku", "gyomatsuYakumonoHankaku", "gyomatsuYakumonoZenkaku", "yakumonoZenkaku" or "lineEndHalf" `mojikumi` "none", "yakumonoHankaku", "gyomatsuYakumonoHankaku", "gyomatsuYakumonoZenkaku", "yakumonoZenkaku" या "lineEndHalf" होना चाहिए। @msg `name` is empty `name` खाली है @@ -6738,6 +6854,9 @@ antiAlias Sharp शार्प @msg automation path rejected: outside the read root {root}: {path} स्वचालन पाथ खारिज: पढ़ने की जड़ के बाहर {root}: {path} @msg automation path rejected: outside the read roots {roots}: {path} स्वचालन पाथ खारिज: पढ़ने की जड़ों के बाहर {roots}: {path} @msg a linked JavaScript file is outside the read roots एक लिंक की गई जावास्क्रिप्ट फ़ाइल पढ़ने की जड़ों के बाहर है +@msg a linked image file is outside the read roots एक लिंक की गई छवि फ़ाइल पढ़ने की जड़ों के बाहर है +@msg a linked file's export folder is outside the read roots एक लिंक की गई फ़ाइल का निर्यात फ़ोल्डर पढ़ने की जड़ों के बाहर है +@msg a linked file's editing data can't be read to check it against the read roots एक लिंक की गई फ़ाइल का संपादन डेटा पढ़ने की जड़ों से जाँचने के लिए पढ़ा नहीं जा सकता @msg the library's file is outside the read roots लाइब्रेरी की फ़ाइल पढ़ने की जड़ों के बाहर है @msg {file} names more than one linked JavaScript file {file} एक से अधिक लिंक की गई जावास्क्रिप्ट फ़ाइलों से मेल खाता है @msg automation path rejected: outside the write root {root}: {path} स्वचालन पाथ खारिज: लिखने की जड़ के बाहर {root}: {path} @@ -6785,6 +6904,7 @@ antiAlias Sharp शार्प @msg bad trailer size बुरा ट्रेलर आकार @msg balance must be between 0 and 100 balance 0 से 100 के बीच होना चाहिए @msg batch step {_1} (`{id}`) failed: {e} बैच चरण {_1} (`{id}`) विफल: {e} +@msg action step {_1} (`{id}`) failed: {reason} कार्रवाई चरण {_1} (`{id}`) विफल: {reason} @msg Batch: {count} processed बैच: {count} संसाधित @msg Batch: {count} processed, {failed} failed बैच: {count} संसाधित, {failed} विफल @msg batches cannot nest बैच घोंसला नहीं कर सकते @@ -6859,11 +6979,18 @@ antiAlias Sharp शार्प @msg color.profile: no RGB or CMYK profile is called “{profile}” color.profile: "{profile}" नाम की कोई RGB या CMYK प्रोफ़ाइल नहीं है @msg colorMode must be rgb or cmyk, not `{m}` colorMode को rgb या cmyk होना चाहिए, `{m}` नहीं @msg colorModel must be {own} (the document's mode), grayscale or bitmap colorModel को {own} (डॉक्यूमेंट का मोड), grayscale या bitmap होना चाहिए +@msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: रंग तालिका में कम से कम एक रंग रहना चाहिए @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}`, "#ff8800" जैसा रंग नहीं है @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: अधिकतम {MAX_TABLE} रंग @msg colour groups can't go into colour groups रंग समूह रंग समूहों में नहीं जा सकते हैं @msg colour, mode and spot apply to solid-colour swatches only रंग, मोड और स्पॉट केवल ठोस रंग वाले स्वॉच पर लागू होते हैं -@msg column {column}: `{cell}` is a `%` column of graph data files, which are not read कॉलम {column}: `{cell}` ग्राफ़ डेटा फ़ाइल का `%` कॉलम है, जिसे पढ़ा नहीं जाता +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path लाइन {line}, कॉलम {column}: `{var}` के लिए ग्राफ़ डेटा फ़ाइल `{path}` एक सापेक्ष पाथ है: `base` या एक पूर्ण पाथ दें +@msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} लाइन {line}, कॉलम {column}: `{var}` के लिए ग्राफ़ डेटा फ़ाइल पढ़ी नहीं जा सकती: {e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` isn't followed: {r} लाइन {line}, कॉलम {column}: `{var}` के लिए ग्राफ़ डेटा फ़ाइल `{path}` का पालन नहीं किया गया है: {r} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes लाइन {line}, कॉलम {column}: `{var}` के लिए ग्राफ़ डेटा फ़ाइल `{path}` {MAX_GRAPH_DATA_FILE} बाइट्स से बड़ी है +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes लाइन {line}, कॉलम {column}: `{var}` के लिए ग्राफ़ डेटा फ़ाइल `{path}` से मिलने वाला ग्राफ़ मूल्य {MAX_GRAPH_CSV} बाइट्स से अधिक है +@msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all लाइन {line}, कॉलम {column}: ग्राफ़ डेटा फ़ाइलों में कुल मिलाकर {MAX_GRAPH_FILES_TOTAL} बाइट्स से अधिक हैं +@msg `base` is empty `base` खाली है @msg column {column}: `{cell}` names `{name}`, which is a {_1} variable कॉलम {column}: `{cell}` में `{name}` नाम का {_1} वेरिएबल है @msg column {column}: `{cell}` names no variable कॉलम {column}: `{cell}` किसी वेरिएबल का नाम नहीं है @msg column {column}: the variable name is longer than {MAX_NAME} characters कॉलम {column}: वेरिएबल का नाम {MAX_NAME} कैरेक्टर से लंबा है @@ -6883,6 +7010,7 @@ antiAlias Sharp शार्प @msg compressed (RLE) bitmaps can't be read yet संकुचित (RLE) bitmaps अभी तक पढ़ा नहीं जा सकता है @msg connect end must be "start" or "end" कनेक्ट अंत "start" या "end" होना चाहिए @msg connect needs a path other than the one extended connect के लिए बढ़ाए गए पाथ के अलावा कोई दूसरा पाथ चाहिए +@msg connect needs extend connect के लिए extend चाहिए @msg connect needs id connect के लिए id चाहिए @msg connect path has no open end कनेक्ट पाथ का कोई खुला अंत नहीं है @msg Contour: select paths or shapes कंटूर: पाथ या आकृतियों सिलेक्ट करें @@ -6896,6 +7024,13 @@ antiAlias Sharp शार्प Show External Script Warning बाहरी स्क्रिप्ट की चेतावनी दिखाएँ A Script Is Running एक स्क्रिप्ट चल रही है Script Alert स्क्रिप्ट सूचना + Script File Access स्क्रिप्ट की फ़ाइल पहुँच + The script asks to read a file you choose. स्क्रिप्ट आपकी चुनी हुई फ़ाइल पढ़ने की अनुमति माँगती है। + The script asks to read and write a file you choose. स्क्रिप्ट आपकी चुनी हुई फ़ाइल पढ़ने और लिखने की अनुमति माँगती है। + The script asks to read and write a folder you choose, with everything in it. स्क्रिप्ट आपका चुना हुआ फ़ोल्डर और उसकी सारी सामग्री पढ़ने और लिखने की अनुमति माँगती है। + Allow Once एक बार अनुमति दें + Always Allow This Script इस स्क्रिप्ट को हमेशा अनुमति दें + Deny अस्वीकार करें A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. स्क्रिप्ट खुले दस्तावेज़ बदल सकती है और अपने चलाए कमांड से फ़ाइलें लिख सकती है। केवल भरोसेमंद स्क्रिप्ट चलाएँ। Do not show this warning again यह चेतावनी फिर न दिखाएँ Stop the script and undo what it did? Then quit again. स्क्रिप्ट रोककर उसके बदलाव पूर्ववत करें? फिर दोबारा बाहर निकलें। @@ -6912,6 +7047,8 @@ antiAlias Sharp शार्प @msg the script is no longer in the Scripts folder स्क्रिप्ट अब Scripts फ़ोल्डर में नहीं है Some scripts were not listed कुछ स्क्रिप्ट सूचीबद्ध नहीं की गईं The Scripts folder cannot be read Scripts फ़ोल्डर पढ़ा नहीं जा सकता + Loading scripts… स्क्रिप्ट लोड हो रही हैं… + The Scripts folder is still being read Scripts फ़ोल्डर अभी भी पढ़ा जा रहा है @msg the script's run is no longer available स्क्रिप्ट का रन अब उपलब्ध नहीं है @msg a failed command changed undo steps that could not be put back, so the script was stopped एक विफल कमांड ने पूर्ववत चरण बदल दिए जिन्हें वापस नहीं रखा जा सका, इसलिए स्क्रिप्ट रोक दी गई @msg a recovery copy could not be written, so the script was not run रिकवरी प्रति नहीं लिखी जा सकी, इसलिए स्क्रिप्ट नहीं चलाई गई @@ -6924,8 +7061,6 @@ antiAlias Sharp शार्प @msg Script file could not be read स्क्रिप्ट फ़ाइल पढ़ी नहीं जा सकी @msg Script folder has more than 2,048 entries स्क्रिप्ट फ़ोल्डर में 2,048 से अधिक प्रविष्टियाँ हैं @msg Script file open mode must be r, w, e or a स्क्रिप्ट फ़ाइल खोलने का मोड r, w, e या a होना चाहिए -@msg Script file writing is not available स्क्रिप्ट फ़ाइल लिखना उपलब्ध नहीं है -@msg Script file dialogs are not available स्क्रिप्ट फ़ाइल संवाद उपलब्ध नहीं हैं @msg Script files cannot be opened in another application स्क्रिप्ट फ़ाइलें किसी अन्य ऐप्लिकेशन में नहीं खोली जा सकतीं @msg Script file access is unavailable on the web वेब पर स्क्रिप्ट फ़ाइल पहुँच उपलब्ध नहीं है @msg Script has 256 files open स्क्रिप्ट ने 256 फ़ाइलें खोल रखी हैं @@ -7065,8 +7200,37 @@ liquify-list-end {0}, {1} {0} और {1} @msg is a prompt's answer, whose `value` must be a string or null यह prompt का उत्तर है, इसलिए इसका `value` स्ट्रिंग या null होना चाहिए @msg must have `kind` alert, confirm or prompt `kind` alert, confirm या prompt होना चाहिए @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` केवल ऐसे रन के लिए है जिसमें पूछने के लिए कोई नहीं है: ऐप में, व्यक्ति हर डायलॉग का उत्तर देता है +@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` 1 से {_1} तक की पूर्ण संख्या होनी चाहिए +@msg `args{place}` is nested more than 64 levels deep `args{place}` 64 से अधिक स्तर गहराई तक नेस्ट किया गया है +@msg `args` must be an object `args` एक ऑब्जेक्ट होना चाहिए +@msg `args` is larger than 1 MiB `args` 1 MiB से बड़ा है +@msg `path` is empty `path` खाली है +@msg `installed` takes a `path`, not a `source` `installed` एक `path` लेता है, `source` नहीं +@msg `path` must name a .js or .jsx file `path` में किसी .js या .jsx फ़ाइल का नाम होना चाहिए +@msg give exactly one of `path` and `source` `path` और `source` में से ठीक एक दें @msg Running a script स्क्रिप्ट चल रही है @msg Copied the script report Copied स्क्रिप्ट रिपोर्ट +@msg Script file access denied: {path} स्क्रिप्ट की फ़ाइल पहुँच अस्वीकार की गई: {path} +@msg Script file access to the app's own folders is not allowed स्क्रिप्ट को ऐप के अपने फ़ोल्डरों तक पहुँचने की अनुमति नहीं है +@msg Script file cannot encode the text स्क्रिप्ट फ़ाइल टेक्स्ट को एन्कोड नहीं कर सकती +@msg Script file could not be written स्क्रिप्ट फ़ाइल लिखी नहीं जा सकी +@msg Script file dialogs need a person to answer them स्क्रिप्ट के फ़ाइल डायलॉग को उत्तर देने के लिए किसी व्यक्ति की ज़रूरत है +@msg Script file is not open for writing स्क्रिप्ट फ़ाइल लिखने के लिए खुली नहीं है +@msg Script file name is already in use स्क्रिप्ट फ़ाइल का नाम पहले से उपयोग में है +@msg Script file name must be a name without a folder स्क्रिप्ट फ़ाइल का नाम बिना फ़ोल्डर वाला नाम होना चाहिए +@msg Script file permission can be kept only for a script run from a file फ़ाइल अनुमति केवल फ़ाइल से चलाई गई स्क्रिप्ट के लिए रखी जा सकती है +@msg Script file permission could not be saved स्क्रिप्ट की फ़ाइल अनुमति सेव नहीं की जा सकी +@msg Script folder is not empty स्क्रिप्ट फ़ोल्डर खाली नहीं है +@msg Script files cannot make aliases स्क्रिप्ट फ़ाइलें उपनाम नहीं बना सकतीं +@msg Script file hidden setting cannot be changed स्क्रिप्ट फ़ाइल की छिपी सेटिंग बदली नहीं जा सकती +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: फ़ाइल डायलॉग किसी बिल्ट-इन फ़ंक्शन, getter, रूपांतरण या $.evalFile द्वारा चलाई गई फ़ाइल के callback के भीतर नहीं खुल सकता; इसे स्क्रिप्ट के अपने कोड से कॉल करें +@msg the script wrote more file data than one run may write (32 MiB) स्क्रिप्ट ने एक रन में लिखे जा सकने वाले फ़ाइल डेटा से अधिक लिखा (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop स्क्रिप्ट के फ़ाइल डायलॉग के लिए `answer` इनमें से एक होना चाहिए: once, always, deny, stop +@msg choose a file or folder first, or deny पहले कोई फ़ाइल या फ़ोल्डर चुनें, या अस्वीकार करें +@msg the script file permissions could not be saved: {e} स्क्रिप्ट की फ़ाइल अनुमतियाँ सेव नहीं की जा सकीं: {e} +@msg this script's file access can be allowed only once इस स्क्रिप्ट की फ़ाइल पहुँच केवल एक बार दी जा सकती है +@msg Only the person at the keyboard can allow a script's file access किसी स्क्रिप्ट को फ़ाइल पहुँच केवल कीबोर्ड पर मौजूद व्यक्ति दे सकता है +@msg A script is given at most 2,048 files: the files picked after them were left out किसी स्क्रिप्ट को अधिकतम 2,048 फ़ाइलें दी जाती हैं: उनके बाद चुनी गई फ़ाइलें छोड़ दी गईं @msg Copied the link info लिंक जानकारी कॉपी की गई @msg copy needs path: the file to copy into the document's folder copy के लिए path चाहिए: डॉक्यूमेंट के फ़ोल्डर में कॉपी करने वाली फ़ाइल @msg copy takes images only: relink placed documents where their files are copy केवल इमेज लेता है: प्लेस किए गए डॉक्यूमेंट्स को वहीं फिर से लिंक करें जहाँ उनकी फ़ाइलें हैं @@ -7630,9 +7794,15 @@ liquify-list-end {0}, {1} {0} और {1} @msg no active data set कोई सक्रिय डेटा सेट नहीं @msg no active document कोई सक्रिय डॉक्यूमेंट @msg no active perspective plane कोई सक्रिय पर्सपेक्टिव विमान नहीं +@msg the perspective grid is hidden पर्सपेक्टिव ग्रिड छिपा हुआ है +@msg Automatic Plane Positioning is off: turn on anchorPoint or gridlineIntersection (perspective.widget.options) स्वचालित प्लेन पोज़िशनिंग बंद है: anchorPoint या gridlineIntersection चालू करें (perspective.widget.options) +@msg anchorPoint must be true or false anchorPoint को true या false होना चाहिए +@msg gridlineIntersection must be true or false gridlineIntersection को true या false होना चाहिए +@msg tolerance must be 0 or more tolerance को 0 या अधिक होना चाहिए +@msg give `at` or `clear`, not both `at` या `clear` दें, दोनों नहीं @msg no anchor points selected कोई एंकर पॉइंट सिलेक्ट नहीं है -@msg `points` must be three [x, y] pairs of numbers `points` में संख्याओं के तीन [x, y] जोड़े होने चाहिए -@msg direct-select three anchor points, or give `points` तीन एंकर पॉइंट्स डायरेक्ट-सिलेक्ट करें, या `points` दें +@msg `points` must be two or three [x, y] pairs of numbers `points` में संख्याओं के दो या तीन [x, y] जोड़े होने चाहिए +@msg direct-select two or three anchor points, or give `points` दो या तीन एंकर पॉइंट्स डायरेक्ट-सिलेक्ट करें, या `points` दें @msg no circle passes through these points: two are the same or all three lie on one line इन पॉइंट्स से होकर कोई वृत्त नहीं गुज़रता: दो एक जैसे हैं या तीनों एक ही रेखा पर हैं @msg no app to open files here यहां फ़ाइलों को ओपन करने के लिए कोई ऐप नहीं है @msg no appearance item {index} कोई उपस्थिति आइटम {index} @@ -7831,6 +8001,9 @@ liquify-list-end {0}, {1} {0} और {1} @msg no such user library ऐसी कोई उपयोगकर्ता लाइब्रेरी नहीं @msg no such view कोई ऐसा दृश्य नहीं @msg no such width point ऐसी कोई चौड़ाई बिंदु नहीं +@msg `single` must be `incoming` or `outgoing` `single` का मान `incoming` या `outgoing` होना चाहिए +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` और `outIndex` एक ही असतत चौड़ाई बिंदु के दो हिस्से होने चाहिए +@msg a discontinuous width point keeps its place असतत चौड़ाई बिंदु अपनी जगह पर रहता है @msg no swatch `{keep}` कोई स्वॉच `{keep}` नहीं @msg no swatch `{n}` कोई स्वॉच `{n}` नहीं @msg no swatch `{n}` (swatches and colour groups move separately) कोई स्वॉच `{n}` नहीं (स्वॉच और रंग समूह अलग-अलग मूव होते हैं) @@ -7978,6 +8151,7 @@ liquify-list-end {0}, {1} {0} और {1} @msg Offset Path: the offset leaves nothing of the selected paths (an inset larger than the shapes) ऑफसेट पाथ: ऑफ़सेट सिलेक्टेड पाथ की कुछ भी नहीं छोड़ता है (आकार की तुलना में एक निर्धारित बड़ा) @msg Offset Path: the path is too complex to offset ऑफसेट पाथ: पाथ ऑफसेट करने के लिए बहुत जटिल है @msg on must be true or false on को true या false होना चाहिए +@msg one circle is inside the other एक वृत्त दूसरे के अंदर है @msg only a dock group above or below others collapses, not one beside another केवल दूसरों के ऊपर या नीचे एक डॉक समूह गिर जाता है, एक दूसरे के बगल में नहीं @msg only an exporter or an importer declares `extensions` केवल एक्सपोर्टर या इंपोर्टर `extensions` घोषित करता है @msg only an object of the Global Edit other than the one it started from can be left out केवल ग्लोबल एडिट का एक ऑब्जेक्ट, इसके अलावा इसे शुरू किया जा सकता है, छोड़ दिया जा सकता है @@ -8323,6 +8497,7 @@ liquify-list-end {0}, {1} {0} और {1} @msg select the objects to attach to the path ऑब्जेक्ट्स का सिलेक्ट करने के लिए संलग्न करने के लिए पाथ @msg select the objects to bind ऑब्जेक्ट्स को बांधने के लिए चुनें @msg select the objects to transform in perspective ऑब्जेक्ट्स को पर्सपेक्टिव में बदलने के लिए चुनें +@msg select two circles to bridge जोड़ने के लिए दो वृत्त चुनें @msg select two open path ends, or two open paths, to average and join औसत निकालकर जोड़ने के लिए दो खुले पाथ एंड पॉइंट्स या दो खुले पाथ सिलेक्ट करें @msg select two or more graphic styles to merge दो या अधिक ग्राफिक स्टाइल्स का सिलेक्ट करने के लिए विलय @msg select two or more objects to distribute वितरित करने के लिए दो या दो से अधिक ऑब्जेक्ट चुनें @@ -8342,6 +8517,7 @@ liquify-list-end {0}, {1} {0} और {1} @msg shadings of more than 4096 patches or triangles were left out 4096 से अधिक पैच या त्रिकोणों के छायांकन को छोड़ दिया गया था @msg shadings whose functions are of an unknown type are filled with their middle colour छायांकन जिसका कार्य अज्ञात प्रकार के होते हैं, उनके मध्य रंग से भरे होते हैं @msg Shape Builder: no region under the pointer आकृति बिल्डर: सूचक के तहत कोई क्षेत्र नहीं +@msg Shape Builder: select all paths you want to merge आकृति बिल्डर: वे सभी पाथ सिलेक्ट करें जिन्हें आप मर्ज करना चाहते हैं @msg Shape Builder: select paths or compound paths आकृति बिल्डर: पाथ या मिश्रित पाथ सिलेक्ट करें @msg Shaper needs 1–64 source paths शेपर के लिए 1–64 स्रोत पाथ चाहिए @msg shortcut for `{k}` must be a string `{k}` के लिए शॉर्टकट एक स्ट्रिंग होना चाहिए @@ -8466,7 +8642,7 @@ liquify-list-end {0}, {1} {0} और {1} @msg each of `{GRAPHICS}` must be an object `{GRAPHICS}` की हर प्रविष्टि एक ऑब्जेक्ट होनी चाहिए @msg `{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}` `{GRAPHICS}` की प्रविष्टियाँ symbol, face, x, y, scale और rotation लेती हैं, `{k}` नहीं @msg each of `{GRAPHICS}` needs `symbol`, the name of a symbol `{GRAPHICS}` की हर प्रविष्टि को `symbol` चाहिए, यानी किसी सिंबल का नाम -@msg `{GRAPHICS}` face must be front or back `{GRAPHICS}` का face, front या back होना चाहिए +@msg `{GRAPHICS}` face must be front, back or side `{GRAPHICS}` का face, front, back या side होना चाहिए @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} `{GRAPHICS}` का {key}, {lo} से {hi} तक की संख्या होना चाहिए @msg `{GRAPHICS}` must be an array `{GRAPHICS}` एक ऐरे होना चाहिए @msg Graphics map onto the Plane, Extrude and Revolve object types ग्राफ़िक्स समतल, एक्सट्रूड और रिवॉल्व ऑब्जेक्ट प्रकारों पर लगते हैं @@ -8507,6 +8683,8 @@ liquify-list-end {0}, {1} {0} और {1} @msg the background worker stopped पृष्ठभूमि कार्यकर्ता बंद कर दिया @msg the blend has no spine मिश्रण में कोई रीढ़ नहीं है @msg the character's size can't be measured कैरेक्टर का आकार मापा नहीं जा सकता है +@msg the circles are too far apart for this radius इस त्रिज्या के लिए वृत्त एक-दूसरे से बहुत दूर हैं +@msg the circles are too far apart for this radius: raise the radius इस त्रिज्या के लिए वृत्त एक-दूसरे से बहुत दूर हैं: त्रिज्या बढ़ाएँ @msg the CMYK image couldn't be written CMYK इमेज को नहीं लिखा जा सकता @msg the Color Picker is not open रंग पिकर खुला नहीं है @msg the compound shape is too complex to expand मिश्रित आकार का विस्तार करने के लिए बहुत जटिल है @@ -8832,6 +9010,8 @@ liquify-list-end {0}, {1} {0} और {1} @msg type that changes writing direction inside a text object opens in the direction of its first character टेक्स्ट ऑब्जेक्ट के भीतर लेखन दिशा बदलने वाला टेक्स्ट अपने पहले वर्ण की दिशा में खुलता है @msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip लिंक्ड एरिया, रैपअराउंड टेक्स्ट या कंपाउंड पाथ में मास्क के रूप में इस्तेमाल किया गया टाइप क्लिप नहीं करता @msg Unembedded to {_1} एम्बेड हटाकर {_1} में रखा गया +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} {n} इमेज का एम्बेड हटाकर {folder} में रखा गया|{n} इमेज का एम्बेड हटाकर {folder} में रखा गया +@msg every numbered name for {name} is taken in that folder {name} के लिए हर नंबर वाला नाम उस फ़ोल्डर में पहले से लिया गया है @msg unexpected host trap होस्ट में अप्रत्याशित ट्रैप @msg unexpected resources अप्रत्याशित संसाधन @msg unknown {k} key `{key}` (size, position) अज्ञात {k} कुंजी `{key}` (size, position) @@ -8988,7 +9168,14 @@ liquify-list-end {0}, {1} {0} और {1} @msg variable `{name}` is declared twice वेरिएबल `{name}` दो बार घोषित है @msg variable `{to}` already exists वेरिएबल `{to}` पहले से मौजूद है @msg variables are locked वेरिएबल्स लॉक हैं -@msg variables that aren't text were left out: {kinds} वेरिएबल जो टेक्स्ट नहीं छोड़े गए थे: {kinds} +@msg variables that aren't text were left out: {kinds} जो वेरिएबल टेक्स्ट नहीं हैं, उन्हें छोड़ दिया गया: {kinds} +variable-kind Visibility दृश्यता +variable-kind Linked File लिंक्ड फ़ाइल +variable-kind Graph Data ग्राफ़ डेटा +variable-kind Unknown अज्ञात +variable-list-two {0}, {1} {0} और {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} और {1} @msg vc_abi_version returned {v}; this host implements version {ABI_VERSION} vc_abi_version ने {v} लौटाया; यह होस्ट संस्करण {ABI_VERSION} लागू करता है @msg vc_alloc returned 0 (out of memory) vc_alloc ने 0 लौटाया (मेमोरी खत्म) @msg vc_alloc returned a block outside memory vc_alloc ने मेमोरी के बाहर का ब्लॉक लौटाया @@ -9064,6 +9251,9 @@ liquify-list-end {0}, {1} {0} और {1} @msgplural Relinked {n} image|Relinked {n} images {n} इमेज दोबारा लिंक हुई|{n} इमेज दोबारा लिंक हुईं @msgplural Replaced {n} image|Replaced {n} images {n} इमेज बदली गई|{n} इमेज बदली गईं @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them {n} रिकवर किया डॉक्यूमेंट बहाल हुआ: रखने के लिए उसे सेव करें|{n} रिकवर किए डॉक्यूमेंट बहाल हुए: रखने के लिए उन्हें सेव करें +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} कॉपी किया गया, {n} नोट के साथ: {first}|कॉपी किया गया, {n} नोट्स के साथ: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} काटा गया, {n} नोट के साथ: {first}|काटा गया, {n} नोट्स के साथ: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} इमेज ट्रेस किया गया, {n} नोट के साथ: {first}|इमेज ट्रेस किया गया, {n} नोट्स के साथ: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} {path} सेव किया गया, {n} नोट के साथ: {first}|{path} सेव किया गया, {n} नोट्स के साथ: {first} @msgplural Selected {n} embedded image|Selected {n} embedded images {n} एम्बेड की गई इमेज सिलेक्टेड|{n} एम्बेड की गई इमेज सिलेक्टेड @msgplural Selected {n} image|Selected {n} images {n} इमेज सिलेक्टेड|{n} इमेज सिलेक्टेड @@ -9524,3 +9714,13 @@ theme Appearance अपीयरेंस @msg A panel is not joined to the rest by a crease. कोई पैनल किसी क्रीज़ लाइन से बाकी से जुड़ा नहीं है। @msg A fold line is on a non-printing layer. एक फ़ोल्ड लाइन नॉन-प्रिंटिंग लेयर पर है। @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} पैनल: {panels}, हिंज: {hinges}, एरर: {errors}, वॉर्निंग: {warnings} + Fold Preview फ़ोल्ड प्रीव्यू + Fold फ़ोल्ड + Show Fold Lines फ़ोल्ड लाइनें दिखाएँ + Three-Quarter तीन-चौथाई + Open a document to preview its folded shape. इसका फ़ोल्ड किया हुआ आकार देखने के लिए कोई डॉक्यूमेंट ओपन करें। +@msg Check the fold lines first. पहले फ़ोल्ड लाइनें चेक करें। +@msg Panels: {panels}, hinges: {hinges} पैनल: {panels}, हिंज: {hinges} +@msg Other blanks not shown: {count} दूसरे ब्लैंक नहीं दिखाए गए: {count} +@msg A joint does not close by {gap} pt. एक जोड़ {gap} pt से बंद नहीं होता। +@msg Two panels pass through each other. दो पैनल एक-दूसरे के आर-पार जाते हैं। diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 0f81a72036..4fb8eb2a15 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -183,6 +183,7 @@ Add Anchor Point Horgonypont hozzáadása Add Anchor Point Tool Horgonypont hozzáadása Add Anchor Points Horgonypontok hozzáadása + Add Around Hozzáadás az objektum körül Add Content Tartalom hozzáadása Add Effect Effektus hozzáadása Add Font Files Betűtípusfájlok hozzáadása @@ -210,7 +211,11 @@ Add Used Colors Használt színek hozzáadása Additional Fonts Folder További betűtípusok mappája Additional Plug-ins Folder További bővítmények mappája + Plug-in Instruction Budget Bővítmények utasításkerete Adjust Adjoining Width Points Szomszédos szélességi pontok igazítása + Incoming Bejövő + Outgoing Kimenő + Single Width Only Csak egy szélesség Adjust Color Balance… Színegyensúly beállítása… Adjust Colors Színek beállítása Adjust Options: Módosítandó: @@ -277,6 +282,7 @@ Angled Strokes… Ferde vonások… Angles Szögek Animated Zoom Animált nagyítás + Anti Alias Élsimítás Anti-alias Élsimítás Anti-Alias Élsimítás Anti-alias Rasters Raszterek élsimítása @@ -382,6 +388,7 @@ font-technology Variable Változó Average Átlagolás Average… Átlagolás… Axis Tengely + Axis Angle Tengely szöge Axis side Tengely oldala Axis: Tengely: B4 B4 @@ -496,6 +503,12 @@ font-technology Variable Változó Brush Definition Ecsetdefiníció Brush Libraries Ecsetkönyvtárak Brush Options… Ecset beállításai… + Options of Selected Object… Kijelölt objektum beállításai… + Options of Selected Object Kijelölt objektum beállításai +@msg no path painted with a brush is selected nincs kijelölt ecsettel festett útvonal +@msg the selected paths are painted with brushes of different types a kijelölt útvonalak különböző típusú ecsetekkel vannak festve +@msg give `params` or `reset`, not both `params` vagy `reset` adható meg, a kettő együtt nem +@msg a bristle brush has no options of its own on a path a sörteecsetnek nincsenek saját beállításai egy útvonalon Brush Scale Options Ecsetméretezési beállítások Brush Strokes Ecsetvonások Brushes Ecsetek @@ -576,6 +589,12 @@ font-technology Variable Változó Character options Karakterbeállítások Paragraph options Bekezdésbeállítások Character Rotation Karakterforgatás + Chinese Big 5 Kínai Big 5 + Cyrillic Cirill + Greek Görög + Turkish Török + Baltic Balti + Central European Közép-európai Character Set: Karakterkészlet: Character Style Karakterstílus Character Style Options Karakterstílus beállításai @@ -641,6 +660,8 @@ font-technology Variable Változó Choose a folder Válassz mappát Choose… Kiválasztás… Circle Kör + Circle Tool Kör eszköz + Circle too large A kör túl nagy Circle (open) Kör (nyitott) Classic Defaults Klasszikus alapértékek Clean Up… Tisztítás… @@ -734,6 +755,7 @@ font-technology Variable Változó Color Mixer (Shift-click the chip) Színkeverő (Shift+kattintás a színmezőre) Color Mode Színmód Color Mode: Színmód: + Color Model Színmodell Color Model: Színmodell: Color Models Színmodellek Color Picker Színválasztó @@ -755,6 +777,11 @@ font-technology Variable Változó Saturation and brightness Telítettség és fényesség Color field Színmező {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Körnézet + Box View Négyzetnézet + Box Channel Négyzet csatornája + Color box Színnégyzet + Color Wheel Options Színkör beállításai Color Type: Színtípus: Color: Szín: Colorization Színezés @@ -762,6 +789,7 @@ font-technology Variable Változó Colors Színek Colors: Színek: Column Graph Tool Oszlopdiagram + Columns Oszlopok Columns: Oszlopok: Column… Oszlop… Combine Slices Szeletek egyesítése @@ -1018,6 +1046,8 @@ font-technology Variable Változó Delete Artboard Rajztábla törlése Delete Artboards Rajztáblák törlése Delete Brush Ecset törlése + Delete Color Szín törlése + Restore Generated Table Előállított tábla visszaállítása Delete Character Style Karakterstílus törlése Delete Data Set Adatkészlet törlése Delete Empty Artboards Üres rajztáblák törlése @@ -1106,6 +1136,7 @@ font-technology Variable Változó Direction Handles Iránykezelő fogantyúk Direction: Irány: Disable Auto Add/Delete Automatikus hozzáadás és törlés kikapcsolása + Interpolate Control Points When Moving Anchors Iránykezelő fogantyúk interpolálása horgonypontok mozgatásakor Disable Opacity Mask Átlátszósági maszk kikapcsolása Discard Elvetés Discard Empty Type Üres szöveg elvetése @@ -1357,6 +1388,7 @@ font-technology Variable Változó Enable text access for screen readers Szöveghozzáférés engedélyezése képernyőolvasóknak Enable Touch Gestures Érintési kézmozdulatok Switch Selection and Drawing Modes Váltás a kijelölési és a rajzolási mód között + Select Last Selection Tool Az utoljára használt kijelölőeszköz kiválasztása Enable Touch Workspace Érintőképernyős munkaterület Encoding Kódolás Encoding: Kódolás: @@ -1565,6 +1597,8 @@ digits Malayalam Malajálam Files Fájlok Files of a PDF standard can't be password-protected. A PDF-szabványnak megfelelő fájlok nem védhetők jelszóval. Files of this standard tag their colours with ICC profiles. Ennek a szabványnak a fájljai ICC-profillal jelölik a színeiket. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Ennek a szabványnak a fájljai ICC-profillal jelölik a színeiket, kivéve a kimeneti cél profiljában lévő CMYK-színeket, amelyek DeviceCMYK-ként íródnak. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. „Profilok nélkül” beállítással és CMYK kimeneti céllal minden CMYK-szín DeviceCMYK-ként íródik, kivéve, ha egy másik profil CMYK-céljába konvertálódik. Fill Kitöltés Fill & Stroke Kitöltés és körvonal Fill (X), double-click for the Color Picker Kitöltés (X), dupla kattintás: Színválasztó @@ -2498,6 +2532,7 @@ file-filter Templates Sablonok Linked File Not Found A csatolt fájl nem található Links Csatolások Linux Display Server Linuxos megjelenítőszerver + Low-Latency Drawing Alacsony késleltetésű rajzolás Liquify Folyékony torzítás List Data Sets Adatkészletek listázása List Folder Mappa listázása @@ -2531,6 +2566,7 @@ file-filter Templates Sablonok Load Texture… Textúra betöltése… Loaded Texture Betöltött textúra Local Libraries Helyi könyvtárak + Locate Layer Réteg megkeresése Locate Object Objektum megkeresése Locate Selected Objects Kijelölt objektumok megkeresése Location Hely @@ -3056,6 +3092,9 @@ file-filter Templates Sablonok Overprint Felülnyomás Overprint and Transparency Flattener Felülnyomás és átlátszóság-lapítás Overprint and Transparency Flattener Options Felülnyomás és átlátszóság-lapítás beállításai + Custom… Egyéni… + Custom Transparency Flattener Options Egyéni átlátszóság-lapítási beállítások + EPS has no alpha transparency, and Overprints sets whether overprints are kept. Az EPS-ben nincs alfa-átlátszóság, és a Felülnyomások beállítás dönti el, hogy megmaradnak-e a felülnyomások. Overprint Black… Fekete felülnyomása… Overprint Fill Kitöltés felülnyomása Overprint Preview Felülnyomás-előnézet @@ -3112,6 +3151,11 @@ file-filter Templates Sablonok Pathfinders: Útvonalkezelők: Paths Útvonalak Path Length Útvonalak hossza + Grid Size Rácsméret + Grid Colors Rács színei + Flattener Preset Lapítási előbeállítás + X X + Y Y Paths: {paths} Anchors: {anchors} Colors: {colors} Útvonalak: {paths} Horgonypontok: {anchors} Színek: {colors} Pattern Mintázat Pattern Brush Mintázatecset @@ -3220,6 +3264,7 @@ diagnostics ui felület Play Current Selection Kijelölt művelet lejátszása Save Actions… Műveletek mentése… Load Actions… Műveletek betöltése… + Replace Actions… Műveletek cseréje… Reset Actions Műveletek visszaállítása Replace the current actions with the default set? Lecseréled az aktuális műveleteket az alapértelmezett készletre? Append adds the default set after the current sets instead. A Hozzáfűzés ehelyett az aktuális készletek után adja hozzá az alapértelmezett készletet. @@ -3239,6 +3284,10 @@ diagnostics ui felület Polar Grid Tool Polárrács Polygon Sokszög Polygon Properties: Sokszög tulajdonságai: + Line Properties: Vonal tulajdonságai: + Line Length: Vonal hossza: + Line Angle: Vonal szöge: + Constrain Pie Angle Körcikk szögének megtartása Polygon Tool Sokszög Portrait Álló Portrait (flipped) Álló (megfordítva) @@ -3418,6 +3467,9 @@ mark-style Japanese Japán Real World: Valós méret: Real-time Drawing and Editing Valós idejű rajzolás és szerkesztés Use Monitor Profile for Canvas Monitorprofil használata a vászonhoz + Refresh Monitor Profile Monitorprofil frissítése +@msg turn on Use Monitor Profile for Canvas first előbb kapcsolja be a „Monitorprofil használata a vászonhoz” beállítást +@msg this build doesn't read display profiles ez a változat nem olvassa be a kijelzőprofilokat The canvas is drawn in sRGB. A vászon sRGB-ben jelenik meg. Canvas display profile: A vászon kijelzőprofilja: The system matches the window to the display's colors. A rendszer a kijelző színeihez igazítja az ablakot. @@ -3601,6 +3653,8 @@ mark-style Japanese Japán Reset Automation Automation visszaállítása Reset Bar Position Sáv helyének visszaállítása Reset Bounding Box Befoglaló keret visszaállítása + Rotate Bounding Box Befoglaló keret elforgatása + Rotate Bounding Box… Befoglaló keret elforgatása… Reset Envelope Mesh Burkolóháló visszaállítása Reset Envelope Shape Burkoló alakjának visszaállítása Reset Essentials Essentials visszaállítása @@ -3641,6 +3695,8 @@ mark-style Japanese Japán Reset Tracing Tracing visszaállítása Reset Tracking and Kerning Betűköz és alávágás visszaállítása Highlight Font Name Betűtípusnév kiemelése + Highlight Font Size Betűméret kiemelése + Other… Egyéb… Highlight Kerning Alávágás kiemelése Highlight Tracking Betűköz kiemelése Reset Typography Typography visszaállítása @@ -3660,6 +3716,7 @@ mark-style Japanese Japán Resize Átméretezés Resize panel window Panelablak átméretezése Resize panels Panelek átméretezése + Resolution Felbontás Resolution: Felbontás: Responsive Reszponzív Restore Visszaállít @@ -3686,6 +3743,7 @@ mark-style Japanese Japán The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Az egérgörgő lenyomott Cmd/Ctrl billentyűvel oldalirányban görgeti a vásznat. Dragging sideways on a numeric field's label changes the field's value. Egy számmező címkéjén oldalirányban húzva módosul a mező értéke. A two-finger rotate gesture on a trackpad rotates the canvas view. Az érintőpadon végzett kétujjas forgató kézmozdulat elforgatja a vászon nézetét. + When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Horgonypontok mozgatásakor minden olyan görbe, amelynek egyik vége elmozdul, megtartja az alakját a végeihez képest. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Egy eszköz billentyűparancsát lenyomva tartva az eszköz a felengedésig ki van választva, utána ismét az előző eszköz lesz kiválasztva. Shows the bounding box while you move the selection or draw a shape. Megjeleníti a befoglaló keretet, miközben a kijelölést mozgatja vagy alakzatot rajzol. Create Trim Marks draws Japanese-style marks instead of Roman ones. A Vágójelek létrehozása római helyett japán stílusú jeleket rajzol. @@ -3716,6 +3774,29 @@ mark-style Japanese Japán The unit for East Asian type measurements, which no field uses yet. A kelet-ázsiai szöveg méreteinek mértékegysége, amelyet egyelőre egyetlen mező sem használ. When on, a number typed without a unit into a field in picas is read in points. Bekapcsolva egy pica mértékegységű mezőbe mértékegység nélkül beírt számot pontként értelmez a program. With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options. XML-azonosító esetén az objektumnevek XML-azonosítóként jelennek meg a Rétegek, a Változók és a Rétegbeállítások ablakban. + The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl. A betűméret és a sortávolság lépésköze: a Cmd/Ctrl+Shift+. és a Cmd/Ctrl+Shift+, egy lépéssel, Alt billentyűvel is öttel változtatja a méretet; vízszintes szövegben az Alt és a fel vagy le nyíl egy lépéssel, Cmd/Ctrl billentyűvel öttel változtatja a sortávolságot. + The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl. A betűköz és az alávágás lépésköze em ezredrészében: vízszintes szövegben az Alt és a bal vagy jobb nyíl egy lépéssel, Cmd/Ctrl billentyűvel öttel változtatja a szövegkurzornál az alávágást vagy a kijelölt szöveg betűközét. + The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. Az alapvonal-eltolás lépésköze: vízszintes szövegben az Alt, a Shift és a fel vagy le nyíl egy lépéssel, Cmd/Ctrl billentyűvel öttel tolja el az alapvonalat. + Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. Megjeleníti a japán és más kelet-ázsiai szöveg beállításait a Karakter, a Bekezdés, az OpenType és a Glifák panelen, valamint az Összetett betűtípusok parancsot. + Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. Megjeleníti az arab, héber és indiai szöveg beállításait a Karakter és a Bekezdés panelen, például a bekezdés irányát, a kasidákat és a számjegyeket. + The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. A kijelölőeszközök a szöveget csak az alapvonalán, a területi szöveg keretén vagy az útvonalán jelölik ki, nem bárhol a dobozán belül. + Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. A betűtípusmenük minden betűtípust angol nevén mutatnak; kikapcsolva a saját nyelvén is elnevezett betűtípus azt a nevet mutatja. + New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. Az új területi szöveg bekapcsolt automatikus mérettel indul, így a vízszintes szöveg téglalap alakú kerete a szöveghez igazodva nő vagy csökken magasságban. + Font lists and the Type › Font menu show a sample of each font beside its name. A betűtípuslisták és a Betűtípus menü minden betűtípus neve mellett mintát mutatnak. + Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on. A betűtípusminták sötét szöveggel fehérre rajzolódnak a felület fényerejétől függetlenül; ez csak a menükben bekapcsolt betűtípus-előnézetek mellett érvényes. + How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is. Milyen magas egy sor a betűtípusmezők listáiban, például a Karakter panelén, és így mekkora egy minta. + How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first. A legutóbb használt betűtípusok közül hányat mutat 1 és 15 között a Legutóbbi betűtípusok és a betűtípuslisták, a legújabbal kezdve. + When you change the font or font style of text, characters the new font has no glyph for keep the font they had. Ha megváltoztatja egy szöveg betűtípusát vagy betűstílusát, azok a karakterek, amelyekhez az új betűtípusban nincs glifa, megtartják korábbi betűtípusukat. + A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export. A vásznon rózsaszín kiemelés jelöli az OpenType-funkciók által cserélt glifákat, például a ligatúrákat; nyomtatásban és exportban nem jelenik meg. + With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from. A Szöveg eszközzel egyetlen karaktert kijelölve mellette a vásznon megjelenik alternatív glifáinak sora, amelyből választhat. + A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export. A vásznon rózsaszín kiemelés jelöli a helyettesítő betűtípussal rajzolt szöveget, mert a saját betűtípusa hiányzik; nyomtatásban és exportban nem jelenik meg. + New type made with a Type tool starts with placeholder text, selected, so typing replaces it. A szövegeszközzel készített új szöveg kijelölt helyőrző szöveggel indul, amelyet a gépelés lecserél. + Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list. Ha egy bekezdés elejére listajelet, például 1. vagy * jelet, majd szóközt gépel, a bekezdés lista lesz. + Fonts in this folder show in the font menus and can be used without being installed. A mappában lévő betűtípusok megjelennek a betűtípusmenükben, és telepítés nélkül használhatók. + Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows. Ha grafikai stílust alkalmaz szövegre, a karakterek saját kitöltése vagy körvonala eltűnik ott, ahol a stílusnak van ilyen, így a stílus festéke látszik. + Align and Distribute measure point type by the ink of its glyphs instead of its em box. Az Igazítás és az Elosztás a pontszöveget glifáinak tintája szerint méri az em-doboza helyett. + Align and Distribute measure area type by the ink of its glyphs instead of its frame. Az Igazítás és az Elosztás a területi szöveget glifáinak tintája szerint méri a kerete helyett. + The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box. A határolókeret és az Átalakítás panel a pontszöveget glifáinak tintája szerint méri az em-doboza helyett. Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply. A rajzolást, mozgatást és méretezést a rács osztásaihoz illeszti, akkor is, ha a rács rejtve van; amíg be van kapcsolva, az Illesztés pixelhez nem érvényes. The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead. A nem kijelölt segédvonalak színe; a Segédvonalak címkéjével rendelkező rajztábla a saját segédvonalait a címke színével rajzolja. Draws guides as solid lines or as dots, including the guides already in the document. A segédvonalakat folytonos vonalként vagy pontokként rajzolja, a dokumentumban már meglévőket is. @@ -3801,6 +3882,7 @@ mark-style Japanese Japán Rotate… Elforgatás… Rotation Elforgatás Rotation relative to: Elforgatás viszonyítási alapja: + Hue Jitter: Színárnyalat-szórás: Rotation X X-elforgatás Rotation Y Y-elforgatás Rotation Z Z-elforgatás @@ -3819,8 +3901,10 @@ mark-style Japanese Japán Rounded Rectangle Lekerekített téglalap Rounded Rectangle Tool Lekerekített téglalap Rounded Rectangle… Lekerekített téglalap… + Roundness Kerekség Roundness: Kerekség: Row Size: Sorméret: + Rows Sorok Rows: Sorok: Rule: Szabály: Ruler Origin Vonalzók origója @@ -4011,6 +4095,9 @@ mark-style Japanese Japán Search commands, tools, panels and effects… Parancsok, eszközök, panelek és effektusok keresése… No commands match Nincs egyező parancs {pos} of {total}: {name} {pos}/{total}: {name} + No menu item Nincs menüpont + Toolbar Eszköztár + {toolbar}, in the {tool} group {toolbar}, a(z) {tool} csoportjában @plural {n} result|{n} results {n} találat @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {n} találatból {shown} látható. Gépeljen tovább a szűkítéshez. Recent Commands Legutóbbi parancsok @@ -4104,6 +4191,7 @@ mark-style Japanese Japán Set Slice Rectangle Szelet téglalapjának beállítása Set Tab Stops Tabulátorpontok beállítása Set Text Szöveg beállítása + Set the current fill or stroke to the selected color Az aktuális kitöltés vagy körvonal legyen a kijelölt szín Set the selected color to the current color A kijelölt szín legyen az aktuális szín Set Zoom Nagyítás beállítása Set: Készlet: @@ -4246,7 +4334,7 @@ mark-style Japanese Japán Show Vivid/Muted Élénk/tompa változatok Show Warm/Cool Meleg/hideg változatok Show {kind} Brushes Ecsetek megjelenítése: {kind} - Show/hide plate (Alt-click: only this plate) Nyomólemez megjelenítése/elrejtése (Alt+kattintás: csak ez a lemez) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Nyomólemez megjelenítése/elrejtése (Alt+kattintás: csak ez a lemez; újabb Alt+kattintás: minden lemez) Show: Megjelenítés: Shown with the optimised preview. Az optimalizált előnézettel együtt látható. Shrink Text to Fit Szöveg zsugorítása a kerethez @@ -4577,7 +4665,7 @@ mark-style Japanese Japán Composite Fonts Összetett betűtípusok Export Composite Fonts Összetett betűtípusok exportálása Import Composite Fonts Összetett betűtípusok importálása -@msg each font must be {name, parts} minden betűtípusnak {name, parts} alakúnak kell lennie +@msg each font must be {{name, parts}} minden betűtípusnak {{name, parts}} alakúnak kell lennie @msg unknown key `{k}`; a font takes name and parts ismeretlen kulcs: `{k}`; egy betűtípus name és parts kulcsot fogad @msg each font needs a name minden betűtípusnak kell egy név @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` nem lehet összetett betűtípus neve (1–{COMPOSITE_NAME_MAX} karakter, vezérlőkarakterek nélkül) @@ -4590,7 +4678,7 @@ mark-style Japanese Japán @msg two composite fonts are named `{_1}` két összetett betűtípus neve is `{_1}` @msg `{_1}` is the name of an installed font `{_1}` egy telepített betűtípus neve @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: a(z) {_2} a(z) `{font}` összetett betűtípust használja -@msg give fonts: [{name, parts}…] adja meg: fonts: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] adja meg: fonts: [{{name, parts}}…] @msg path is empty a path üres @msg fonts must be a list of composite fonts a fonts értékének összetett betűtípusok listájának kell lennie @msg names must be strings a names elemeinek karakterláncoknak kell lenniük @@ -4691,6 +4779,13 @@ mark-style Japanese Japán TIFF (8-bit Color) TIFF (8 bites színes) TIFF (Black & White) TIFF (fekete-fehér) Tile Mozaikelrendezés + Tile All Vertically Összes mozaikelrendezése függőlegesen + Tile All Horizontally Összes mozaikelrendezése vízszintesen + 2-Up Layout 2-es elrendezés + 3-Up Layout 3-as elrendezés + 4-Up Layout 4-es elrendezés + 6-Up Layout 6-os elrendezés + Arrange Documents Dokumentumok elrendezése Tile Edge Color Csempeszél színe Tile Edge Color… Csempeszél színe… Tile Full Pages Teljes oldalak csempézése @@ -4940,6 +5035,8 @@ mark-style Japanese Japán Variable Options Változó beállításai Variable Options… Változó beállításai… Variable Width Profile Változó szélességprofil + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. A körvonal ecsetje megtartja a saját méretét, ezért a szélességprofil nem változtatja meg. Profil használatához távolítsa el az ecsetet. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. A körvonal ecsetje megtartja a saját méretét, ezért a szélességprofil nem változtatja meg. Profil használatához távolítsa el az ecsetet. Variables Változók Variation Ingadozás Variation: Ingadozás: @@ -4988,7 +5085,7 @@ mark-style Japanese Japán Video Banner 2560×1440 Videós szalagcím 2560×1440 Video Thumbnail 1280×720 Videó-bélyegkép 1280×720 View Nézet - View Artboard Only Csak a rajztábla látszik + View Artboard Contents Only Csak a rajztábla tartalma látszik View Opacity Mask Átlátszósági maszk megtekintése View PDF after saving PDF megtekintése mentés után View {n} Nézet {n} @@ -5051,6 +5148,7 @@ mark-style Japanese Japán Wrinkle Tool Gyűrés Write Layers Rétegek írása x Height x-magasság + Em Box Height Kvirtmező magassága X11 (XWayland) When a Pen Is Attached X11 (XWayland), ha toll csatlakozik If a drawing tablet's pen doesn't draw, choose an X11 (XWayland) option. Ha a grafikus tábla tolla nem rajzol, válassz egy X11 (XWayland) beállítást. X11 (XWayland) X11 (XWayland) @@ -5200,6 +5298,8 @@ imageTrace Outline Körvonal @msg `{min_key}` is greater than `{max_key}` `{min_key}` nagyobb, mint `{max_key}` @msg give at least one of `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` adj meg legalább egyet ezek közül: `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode`: grayscale, rgb, hsb, cmyk vagy websafe kell +@msg `view` must be wheel or box `view`: wheel vagy box kell +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel`: hue, saturation, brightness, red, green vagy blue kell @msg `{k}` must be [x, y] `{k}`: [x, y] kell @msg `{name}` has no options ennek nincsenek beállításai: `{name}` @msg `{name}` is a built-in workspace; choose another name beépített munkaterület: `{name}`; válassz másik nevet @@ -5301,6 +5401,9 @@ imageTrace Outline Körvonal @msg automation path rejected: outside the read root {root}: {path} az automatizálás útvonala elutasítva: kívül esik az olvasási gyökéren ({root}): {path} @msg automation path rejected: outside the read roots {roots}: {path} az automatizálás útvonala elutasítva: kívül esik az olvasási gyökereken ({roots}): {path} @msg a linked JavaScript file is outside the read roots egy csatolt JavaScript-fájl kívül esik az olvasási gyökereken +@msg a linked image file is outside the read roots egy csatolt képfájl kívül esik az olvasási gyökereken +@msg a linked file's export folder is outside the read roots egy csatolt fájl exportálási mappája kívül esik az olvasási gyökereken +@msg a linked file's editing data can't be read to check it against the read roots egy csatolt fájl szerkesztési adatai nem olvashatók be az olvasási gyökerekkel való ellenőrzéshez @msg automation path rejected: outside the write root {root}: {path} az automatizálás útvonala elutasítva: kívül esik az írási gyökéren ({root}): {path} @msg automation path rejected: outside the write roots {roots}: {path} az automatizálás útvonala elutasítva: kívül esik az írási gyökereken ({roots}): {path} @msg automation path rejected: parent traversal below a folder that doesn't exist: {path} az automatizálás útvonala elutasítva: szülőmappára lépés egy nem létező mappa alatt: {path} @@ -5325,6 +5428,7 @@ imageTrace Outline Körvonal @msg bad trailer hibás záró rész (trailer) @msg balance must be between 0 and 100 a balance értéke 0 és 100 között lehet @msg batch step {_1} (`{id}`) failed: {e} a kötegelt lépés sikertelen: {_1} (`{id}`): {e} +@msg action step {_1} (`{id}`) failed: {reason} a művelet lépése sikertelen: {_1} (`{id}`): {reason} @msg before must name a panel a before egy panelt kell megnevezzen @msg below and above must name a panel floating in another group a below és az above egy másik csoportban lebegő panelt kell megnevezzen @msg Blend colors: select at least three objects with filled colours Színek összemosása: jelölj ki legalább három kitöltött objektumot @@ -5349,6 +5453,7 @@ imageTrace Outline Körvonal @msg choose the font files to add válaszd ki a hozzáadandó betűtípusfájlokat @msg clipboard is empty a vágólap üres @msg closing needs three anchors a lezáráshoz három horgonypont kell +@msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: legalább egy színnek a színtáblában kell maradnia @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` nem szín (például "#ff8800") @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: legfeljebb {MAX_TABLE} szín @msg column must be true or a number from 1 a column értéke true vagy 1-től kezdődő szám lehet @@ -5365,6 +5470,13 @@ imageTrace Outline Körvonal Show External Script Warning Figyelmeztetés külső parancsfájlok előtt A Script Is Running Egy parancsfájl fut Script Alert Parancsfájl-értesítés + Script File Access Parancsfájl fájlhozzáférése + The script asks to read a file you choose. A parancsfájl egy Ön által választott fájl olvasását kéri. + The script asks to read and write a file you choose. A parancsfájl egy Ön által választott fájl olvasását és írását kéri. + The script asks to read and write a folder you choose, with everything in it. A parancsfájl egy Ön által választott mappa és teljes tartalma olvasását és írását kéri. + Allow Once Engedélyezés egyszer + Always Allow This Script A parancsfájl engedélyezése mindig + Deny Elutasítás A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. A parancsfájl módosíthatja a megnyitott dokumentumokat, és a futtatott parancsokkal fájlokat írhat. Csak megbízható parancsfájlokat futtasson. Do not show this warning again Ne jelenjen meg többé ez a figyelmeztetés Stop the script and undo what it did? Then quit again. Leállítja a parancsfájlt, és visszavonja a módosításait? Ezután lépjen ki újra. @@ -5381,6 +5493,8 @@ imageTrace Outline Körvonal @msg the script is no longer in the Scripts folder a parancsfájl már nincs a Scripts mappában Some scripts were not listed Néhány szkript nem szerepel a listában The Scripts folder cannot be read A Scripts mappa nem olvasható + Loading scripts… Szkriptek betöltése… + The Scripts folder is still being read A Scripts mappa olvasása még tart @msg the script's run is no longer available a parancsfájl futása már nem érhető el @msg a failed command changed undo steps that could not be put back, so the script was stopped egy sikertelen parancs olyan visszavonási lépéseket módosított, amelyeket nem lehetett visszaállítani, ezért a parancsfájl leállt @msg a recovery copy could not be written, so the script was not run a helyreállítási másolatot nem sikerült kiírni, ezért a parancsfájl nem futott le @@ -5393,8 +5507,6 @@ imageTrace Outline Körvonal @msg Script file could not be read A parancsfájlt nem sikerült beolvasni @msg Script folder has more than 2,048 entries A parancsfájlmappában 2048-nál több bejegyzés van @msg Script file open mode must be r, w, e or a A parancsfájl megnyitási módja r, w, e vagy a lehet -@msg Script file writing is not available A parancsfájlok írása nem érhető el -@msg Script file dialogs are not available A parancsfájlok fájlpárbeszédpanelei nem érhetők el @msg Script files cannot be opened in another application A parancsfájlok nem nyithatók meg másik alkalmazásban @msg Script file access is unavailable on the web A parancsfájlok elérése a weben nem érhető el @msg Script has 256 files open A parancsfájlnak 256 megnyitott fájlja van @@ -5511,8 +5623,37 @@ liquify-list-end {0}, {1} {0} és {1} @msg there is no script engine named {name} nincs {name} nevű parancsfájlmotor @msg `answers[{i}]` {e} `answers[{i}]`: {e} @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog az `answers` csak olyan futtatáshoz való, ahol nincs kit megkérdezni: az alkalmazásban minden párbeszédpanelre a felhasználó válaszol +@msg `maxFuel` must be a whole number from 1 to {_1} a `maxFuel` értéke 1 és {_1} közötti egész szám lehet +@msg `args{place}` is nested more than 64 levels deep az `args{place}` 64 szintnél mélyebben van egymásba ágyazva +@msg `args` must be an object az `args` értékének objektumnak kell lennie +@msg `args` is larger than 1 MiB `args`: nagyobb 1 MiB-nál +@msg `path` is empty a `path` üres +@msg `installed` takes a `path`, not a `source` az `installed` `path` értéket vár, nem `source` értéket +@msg `path` must name a .js or .jsx file a `path` értékének .js vagy .jsx fájlt kell megadnia +@msg give exactly one of `path` and `source` pontosan egyet adj meg ezek közül: `path`, `source` @msg Running a script Parancsfájl futtatása @msg Copied the script report Szkriptjelentés másolva +@msg Script file access denied: {path} A parancsfájl fájlhozzáférése megtagadva: {path} +@msg Script file access to the app's own folders is not allowed A parancsfájlok nem férhetnek hozzá az alkalmazás saját mappáihoz +@msg Script file cannot encode the text A parancsfájl fájlja nem tudja kódolni a szöveget +@msg Script file could not be written A parancsfájl fájlját nem sikerült írni +@msg Script file dialogs need a person to answer them A parancsfájl fájlpárbeszédpaneleire egy személynek kell válaszolnia +@msg Script file is not open for writing A parancsfájl fájlja nincs írásra megnyitva +@msg Script file name is already in use A parancsfájl fájljának neve már használatban van +@msg Script file name must be a name without a folder A parancsfájl fájljának neve mappa nélküli név kell legyen +@msg Script file permission can be kept only for a script run from a file A fájlengedély csak fájlból futtatott parancsfájlnál tartható meg +@msg Script file permission could not be saved A parancsfájl fájlengedélyét nem sikerült menteni +@msg Script folder is not empty A parancsfájl mappája nem üres +@msg Script files cannot make aliases A parancsfájl fájljai nem hozhatnak létre álneveket +@msg Script file hidden setting cannot be changed A parancsfájl fájljának rejtett beállítása nem módosítható +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: fájlpárbeszédpanel nem nyílhat meg beépített függvény, getter, átalakítás vagy a $.evalFile által futtatott fájl visszahívásán belül; hívja meg a parancsfájl saját kódjából +@msg the script wrote more file data than one run may write (32 MiB) a parancsfájl több fájladatot írt, mint amennyit egy futás írhat (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop a parancsfájl fájlpárbeszédpaneléhez tartozó `answer` értéke a következők egyike kell legyen: once, always, deny, stop +@msg choose a file or folder first, or deny először válasszon fájlt vagy mappát, vagy utasítsa el +@msg the script file permissions could not be saved: {e} a parancsfájlok fájlengedélyeit nem sikerült menteni: {e} +@msg this script's file access can be allowed only once ennek a parancsfájlnak a fájlhozzáférése csak egyszer engedélyezhető +@msg Only the person at the keyboard can allow a script's file access Parancsfájl fájlhozzáférését csak a billentyűzetnél ülő személy engedélyezheti +@msg A script is given at most 2,048 files: the files picked after them were left out Egy parancsfájl legfeljebb 2 048 fájlt kap: az ezek után kiválasztott fájlok kimaradtak @msg Copied the link info Csatolás adatai másolva @msg Corners edits the corners of a path a Sarkok parancs egy útvonal sarkait szerkeszti @msg could not decode image: {0} a kép nem dekódolható: {0} @@ -5681,9 +5822,15 @@ liquify-list-end {0}, {1} {0} és {1} @msg name the file adj nevet a fájlnak @msg no active document nincs aktív dokumentum @msg no active perspective plane nincs aktív perspektivikus sík +@msg the perspective grid is hidden a perspektivikus rács rejtett +@msg Automatic Plane Positioning is off: turn on anchorPoint or gridlineIntersection (perspective.widget.options) Az automatikus síkpozicionálás ki van kapcsolva: kapcsold be az anchorPoint vagy a gridlineIntersection beállítást (perspective.widget.options) +@msg anchorPoint must be true or false anchorPoint: true vagy false kell +@msg gridlineIntersection must be true or false gridlineIntersection: true vagy false kell +@msg tolerance must be 0 or more tolerance: 0 vagy nagyobb érték kell +@msg give `at` or `clear`, not both az `at` vagy a `clear` értéket add meg, ne mindkettőt @msg no anchor points selected nincs kijelölt horgonypont -@msg `points` must be three [x, y] pairs of numbers a `points` három [x, y] számpár legyen -@msg direct-select three anchor points, or give `points` jelölj ki közvetlen kijelöléssel három horgonypontot, vagy add meg a `points` értéket +@msg `points` must be two or three [x, y] pairs of numbers a `points` két vagy három [x, y] számpár legyen +@msg direct-select two or three anchor points, or give `points` jelölj ki közvetlen kijelöléssel két vagy három horgonypontot, vagy add meg a `points` értéket @msg no circle passes through these points: two are the same or all three lie on one line ezeken a pontokon nem halad át kör: kettő egybeesik, vagy mindhárom egy egyenesen van @msg no app to open files here itt nincs fájlmegnyitó alkalmazás @msg no artboard nincs rajztábla @@ -5794,6 +5941,9 @@ liquify-list-end {0}, {1} {0} és {1} @msg no such user library nincs ilyen felhasználói könyvtár @msg no such view nincs ilyen nézet @msg no such width point nincs ilyen szélességi pont +@msg `single` must be `incoming` or `outgoing` a `single` értéke `incoming` vagy `outgoing` lehet +@msg `index` and `outIndex` must be the two halves of one discontinuous width point az `index` és az `outIndex` egyetlen szakadásos szélességi pont két fele kell legyen +@msg a discontinuous width point keeps its place a szakadásos szélességi pont megtartja a helyét @msg no swatch `{name}` nincs ilyen színminta: `{name}` @msg no swatch library `{l}` (see swatch.library.list) nincs ilyen színminta-könyvtár: `{l}` (lásd: swatch.library.list) @msg no symbol instances selected nincs kijelölt szimbólumpéldány @@ -5942,6 +6092,9 @@ liquify-list-end {0}, {1} {0} és {1} @msg Saved to User Defined: {_1} Mentve a felhasználóiak közé: {_1} @msg Saved {n} files beside {path} Mentett fájlok: {n}, a következő mellett: {path} @msg Saved {path} Mentve: {path} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Másolva; megjegyzések: {n}, az első: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Kivágva; megjegyzések: {n}, az első: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Kép vektorizálva; megjegyzések: {n}, az első: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} Mentve: {path}; megjegyzések: {n}, az első: {first} @msg Saving Mentés @msg Saving recovery data for {_1} Helyreállítási adatok mentése: {_1} @@ -6020,6 +6173,7 @@ liquify-list-end {0}, {1} {0} és {1} @msg shadings of more than 4096 patches or triangles were left out kimaradtak a 4096-nál több foltból vagy háromszögből álló árnyalások @msg shadings whose functions are of an unknown type are filled with their middle colour az ismeretlen típusú függvényt használó árnyalások a középső színükkel kitöltve jelennek meg @msg Shape Builder: no region under the pointer Alakzatépítő: a mutató alatt nincs terület +@msg Shape Builder: select all paths you want to merge Alakzatépítő: jelöld ki az összes egyesítendő útvonalat @msg Shape Builder: select paths or compound paths Alakzatépítő: jelölj ki útvonalakat vagy összetett útvonalakat @msg shortcut for `{k}` must be a string `{k}` billentyűparancsa csak szöveg lehet @msg Show All Hidden Attributes: nothing is hidden Összes rejtett attribútum megjelenítése: nincs rejtett elem @@ -6145,6 +6299,8 @@ liquify-list-end {0}, {1} {0} és {1} @msg tool shortcuts must be a single key (optionally with Shift) eszköz billentyűparancsa egyetlen billentyű lehet (Shifttel vagy anélkül) @msg truncated csonka @msg Unembedded to {_1} Beágyazás megszüntetve, ide: {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} Beágyazás megszüntetve, képek: {n}, ide: {folder} +@msg every numbered name for {name} is taken in that folder abban a mappában minden sorszámozott név foglalt: {name} @msg unknown command `{0}` ismeretlen parancs: `{0}` @msg step {step} of “{action}” runs the unknown command `{command}` „{action}”, lépés: {step}: ismeretlen parancsot futtat: `{command}` @msg unknown command `{0}`; did you mean `{1}`? ismeretlen parancs: `{0}`; erre gondolt: `{1}`? @@ -6191,6 +6347,13 @@ liquify-list-end {0}, {1} {0} és {1} @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} több mint {MAX_CSV_ROWS} adatkészlet: az Adatkészletek importálása legfeljebb {MAX_CSV_ROWS} adatkészletet olvas be @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} több mint {MAX_CSV_COLS} változó: az Adatkészletek importálása legfeljebb {MAX_CSV_COLS} változót olvas be @msg variables that aren't text were left out: {kinds} a nem szöveges változók kimaradtak: {kinds} +variable-kind Visibility Láthatóság +variable-kind Linked File Csatolt fájl +variable-kind Graph Data Diagramadatok +variable-kind Unknown Ismeretlen +variable-list-two {0}, {1} {0} és {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} és {1} @msg a new document won't read these variables back with their kind: {names} egy új dokumentum nem a fajtájukkal olvassa vissza ezeket a változókat: {names} @msg a new document refuses this file because of these variables: {names} egy új dokumentum ezen változók miatt elutasítja ezt a fájlt: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them a(z) `{name}` változó `{header}` fejléce a(z) `{other}` változóként olvasódna vissza: nevezze át az egyiket @@ -6236,6 +6399,8 @@ liquify-list-end {0}, {1} {0} és {1} @msg {label}: lost track of a shape's style {label}: egy alakzat stílusa elveszett @msg {label}: select paths {label}: jelölj ki útvonalakat @msg {label}: select paths, compound paths, groups or text {label}: jelölj ki útvonalakat, összetett útvonalakat, csoportokat vagy szöveget +@msg a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first egy vonal vagy más nyitott útvonal, amely nem zár közre területet, nem változtatja meg az eredmény alakját; a felvételéhez előbb alkalmazza rá az Objektum › Útvonal › Körvonal útvonallá alakítása parancsot +@msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first üres eredmény: {label}: egy vonal vagy más nyitott útvonal nem zár közre területet; a felvételéhez előbb alkalmazza rá az Objektum › Útvonal › Körvonal útvonallá alakítása parancsot @msg {label}… {label}… @msg {name}: CRC mismatch {name}: CRC-eltérés @msg {name}: no local header {name}: nincs helyi fejléc @@ -6247,6 +6412,8 @@ liquify-list-end {0}, {1} {0} és {1} @msg {path}: {e} {path}: {e} @msg {status} ({e}) {status} ({e}) @msg {tool} isn't in a toolbar group of several tools az eszköz nincs többeszközös eszköztár-csoportban: {tool} +@msg Presentation Mode hides the toolbars: change the screen mode to show them a Bemutató mód elrejti az eszköztárakat: a megjelenítésükhöz váltson képernyőmódot +@msg Tab has hidden the toolbars: press Tab to show them a Tab elrejtette az eszköztárakat: a megjelenítésükhöz nyomja meg a Tab billentyűt @msg the compressed file unpacks to more than VectorCraft reads ({_1} MB of document, {_2} MB per image) a tömörített fájl kicsomagolva nagyobb lenne, mint amennyit a VectorCraft beolvas ({_1} MB dokumentum, képenként {_2} MB) @msg the document is too large to save compressed ({0}): save it with Use Compression off a dokumentum túl nagy a tömörített mentéshez ({0}): mentsd a Tömörítés használata beállítás kikapcsolásával @msg the file stopped being read (please report this bug) a fájl beolvasása megszakadt (kérjük, jelentsd ezt a hibát) @@ -6267,6 +6434,7 @@ liquify-list-end {0}, {1} {0} és {1} Cove Homorú Depth Mélység Front Elölről + Side Oldalról Isometric Bottom Izometrikus alsó Isometric Left Izometrikus bal Isometric Right Izometrikus jobb @@ -6361,7 +6529,7 @@ liquify-list-end {0}, {1} {0} és {1} @msg each of `{GRAPHICS}` must be an object a `{GRAPHICS}` minden elemének objektumnak kell lennie @msg `{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}` a `{GRAPHICS}` elemei symbol, face, x, y, scale és rotation értéket fogadnak, nem `{k}` értéket @msg each of `{GRAPHICS}` needs `symbol`, the name of a symbol a `{GRAPHICS}` minden eleméhez kell `symbol`, egy szimbólum neve -@msg `{GRAPHICS}` face must be front or back a `{GRAPHICS}` face értéke front vagy back lehet +@msg `{GRAPHICS}` face must be front, back or side a `{GRAPHICS}` face értéke front, back vagy side lehet @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} a `{GRAPHICS}` {key} értéke {lo} és {hi} közötti szám lehet @msg `{GRAPHICS}` must be an array a `{GRAPHICS}` értéke tömb kell legyen @msg Graphics map onto the Plane, Extrude and Revolve object types A grafikák a Sík, a Kihúzás és a Forgatás tengely körül objektumtípusra kerülnek @@ -7365,6 +7533,12 @@ anchor Points: Pontok: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode`: "free", "keepAngles" vagy "symmetric" kell @msg `{key}` must be [x, y] `{key}`: [x, y] kell +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Mértékegység-átváltó + Unit Converter Panel Mértékegység-átváltó panel + Copy with Units Másolás mértékegységgel + From Selection A kijelölésből + # Color Effects add-on: Select by Color Kind. Select by Color Kind Kijelölés színtípus szerint Objects with Spot Colors Direkt színeket használó objektumok @@ -7589,6 +7763,14 @@ breakText Glyphs Glifák Remove Gaps Hézagok eltávolítása @msg that makes too many pieces (at most 100000): make the dashes longer ez túl sok darabot adna (legfeljebb 100000): hosszabbítsa meg a szaggatásokat @msg select paths, or segments, to divide jelöljön ki felosztandó útvonalakat vagy szakaszokat +# Path Precision Tools add-on: Smooth Bridge. + Smooth Bridge… Sima híd… + Smooth Bridge Sima híd + Keep Originals Eredetik megtartása +@msg select two circles to bridge jelöljön ki két kört az összekötéshez +@msg one circle is inside the other az egyik kör a másikon belül van +@msg the circles are too far apart for this radius: raise the radius a körök túl messze vannak egymástól ehhez a sugárhoz: növelje a sugarat +@msg the circles are too far apart for this radius a körök túl messze vannak egymástól ehhez a sugárhoz # Path Precision Tools add-on: Common Tangents. Common Tangents… Közös érintők… Common Tangents Közös érintők @@ -8178,7 +8360,7 @@ breakText Glyphs Glifák @msg `scale` must be a number from 0.001 to 1000 `scale`: 0.001 és 1000 közötti szám kell @msg `scale` must be a number in (0, 100] `scale`: a (0, 100] tartományba eső szám kell @msg `scope.{key}` must be a non-empty array `scope.{key}`: nem üres tömb kell -@msg `scope` must be "document", {artboards} or {layers} `scope`: "document", {artboards} vagy {layers} kell +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope`: "document", {{artboards: [index, …]}} vagy {{layers: [id, …]}} kell @msg `scope` must be "selection" or "document", not {other} `scope`: "selection" vagy "document" kell, ez nem az: {other} @msg `script` must be a string `script`: karakterlánc kell @msg `seriesIndexes` is a non-empty list of series indexes `seriesIndexes`: adatsorindexek nem üres listája @@ -8257,6 +8439,8 @@ breakText Glyphs Glifák @msg `{f}` is the copy of a document open now egy most megnyitott dokumentum másolata: `{f}` @msg `{id}` is no writable format (see document.formats) nem írható formátum: `{id}` (lásd: document.formats) @msg `{id}` isn't a loaded library nem betöltött könyvtár: `{id}` +@msg `{file}` has no swatches of its own nincsenek saját színminták: `{file}` +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold mintázatszínmintákat tartalmaz, amelyeket egy .vcswatches fájl nem tud tárolni: `{_1}` @msg `{key}` has no colours `{key}`: nincsenek benne színek @msg `{key}` holds more than {MAX_EDIT_WORDS} words `{key}`: több mint {MAX_EDIT_WORDS} szót tartalmaz @msg `{key}` is a design name `{key}`: diagramminta neve @@ -8548,7 +8732,13 @@ breakText Glyphs Glifák @msg colorModel must be {own} (the document's mode), grayscale or bitmap colorModel: {own} (a dokumentum módja), grayscale vagy bitmap kell @msg colour groups can't go into colour groups színcsoport nem kerülhet színcsoportba @msg colour, mode and spot apply to solid-colour swatches only colour, mode és spot: csak egyszínű színmintákra vonatkozik -@msg column {column}: `{cell}` is a `%` column of graph data files, which are not read {column}. oszlop: `{cell}` a diagramadat-fájlok `%` oszlopa, ezek beolvasása nem történik meg +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path {line}. sor, {column}. oszlop: a(z) `{var}` `{path}` diagramadat-fájlja relatív elérési út: adja meg a `base` értéket vagy egy abszolút elérési utat +@msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} {line}. sor, {column}. oszlop: a(z) `{var}` diagramadat-fájlja nem olvasható: {e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` isn't followed: {r} {line}. sor, {column}. oszlop: a(z) `{var}` diagramadat-fájlja nem lesz követve: `{path}`: {r} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes {line}. sor, {column}. oszlop: a(z) `{var}` `{path}` diagramadat-fájlja nagyobb {MAX_GRAPH_DATA_FILE} bájtnál +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes {line}. sor, {column}. oszlop: a(z) `{var}` `{path}` diagramadat-fájlja {MAX_GRAPH_CSV} bájtnál hosszabb diagramértéket ad +@msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all {line}. sor, {column}. oszlop: a diagramadat-fájlok összesen több mint {MAX_GRAPH_FILES_TOTAL} bájtot tartalmaznak +@msg `base` is empty a `base` üres @msg column {column}: `{cell}` names `{name}`, which is a {_1} variable {column}. oszlop: `{cell}` ezt nevezi meg: `{name}`, amely {_1} típusú változó @msg column {column}: `{cell}` names no variable {column}. oszlop: `{cell}` nem nevez meg változót @msg column {column}: the variable name is longer than {MAX_NAME} characters {column}. oszlop: a változó neve hosszabb {MAX_NAME} karakternél @@ -8559,6 +8749,7 @@ breakText Glyphs Glifák @msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes összetett alakzatba útvonalak, összetett útvonalak, csoportok, összetett alakzatok, szöveg, összemosások és burkolók kerülhetnek @msg compound {_1} must contain exactly one open path to join az összetett objektumnak ({_1}) pontosan egy összekapcsolható nyitott útvonalat kell tartalmaznia @msg connect needs a path other than the one extended connect: a meghosszabbított útvonaltól különböző útvonal kell +@msg connect needs extend connect: extend is kell hozzá @msg connect needs id connect: id is kell hozzá @msg connect path has no open end connect: az útvonalnak nincs nyitott vége @msg continuation must be an array of path chunks continuation: útvonaldarabok tömbje kell @@ -9071,7 +9262,7 @@ breakText Glyphs Glifák @msg nothing to print: every artboard picked is blank nincs mit nyomtatni: minden kiválasztott rajztábla üres @msg nothing to print: the document has no art that prints nincs mit nyomtatni: a dokumentumban nincs nyomtatásra kerülő grafika @msg nothing to repeat nincs mit ismételni -@msg numbers out of order in {_1} quantifier a számok rossz sorrendben vannak ebben a kvantorban: {_1} +@msg numbers out of order in {{}} quantifier a számok rossz sorrendben vannak ebben a kvantorban: {{}} @msg object is not a path az objektum nem útvonal @msg object transparency cannot be sampled onto highlighted characters; disable Transparency in Eyedropper Options or select the whole object az objektum átlátszósága nem vehető át kiemelt karakterekre; kapcsold ki az Átlátszóság beállítást a Pipetta beállításaiban, vagy jelöld ki a teljes objektumot @msg object {_1} can't be set as point type ez az objektum nem állítható be pontszövegként: {_1} @@ -9431,7 +9622,7 @@ breakText Glyphs Glifák @msg the page has no area az oldalnak nincs területe @msg the page's type in an unread object's box isn't in its page art az oldal egy be nem olvasott objektum keretében lévő szövege nincs benne az oldal grafikájában @msg the paint behind the proxy is not a gradient a mintadoboz mögötti festés nem színátmenet -@msg the paint is not a freeform gradient (apply one with paint.editGradient {kind}) a festés nem szabad formájú színátmenet (alkalmazz egyet a paint.editGradient {kind} paranccsal) +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) a festés nem szabad formájú színátmenet (alkalmazz egyet a paint.editGradient {{kind: "freeform"}} paranccsal) @msg the parameters or body do not form one function a paraméterek vagy a törzs nem alkotnak egyetlen függvényt @msg the parent must be a layer or sublayer a szülő réteg vagy alréteg kell legyen @msg the pasted SVG filter {name} draws differently from the document's filter of that name, and no free name fits it a beillesztett SVG-szűrő ({name}) másképp rajzol, mint a dokumentum azonos nevű szűrője, és nem jut neki szabad név @@ -9905,3 +10096,13 @@ breakText Glyphs Glifák @msg A panel is not joined to the rest by a crease. Egy panelt egyetlen bigvonal sem köt a többihez. @msg A fold line is on a non-printing layer. Egy hajtásvonal nem nyomtatható rétegen van. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panelek: {panels}, zsanérok: {hinges}, hibák: {errors}, figyelmeztetések: {warnings} + Fold Preview Hajtás előnézete + Fold Hajtás + Show Fold Lines Hajtásvonalak megjelenítése + Three-Quarter Háromnegyed + Open a document to preview its folded shape. Nyiss meg egy dokumentumot a hajtogatott alakja előnézetéhez. +@msg Check the fold lines first. Előbb ellenőrizd a hajtásvonalakat. +@msg Panels: {panels}, hinges: {hinges} Panelek: {panels}, zsanérok: {hinges} +@msg Other blanks not shown: {count} További kiterítékek nincsenek megjelenítve: {count} +@msg A joint does not close by {gap} pt. Egy illesztés {gap} pt-tal nem záródik. +@msg Two panels pass through each other. Két panel áthatol egymáson. diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 28ea2b5ab3..1cf9cd9a10 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -57,6 +57,8 @@ Check Script Periksa skrip Some scripts were not listed Beberapa skrip tidak dicantumkan The Scripts folder cannot be read Folder Scripts tidak dapat dibaca + Loading scripts… Memuat skrip… + The Scripts folder is still being read Folder Scripts masih dibaca Other Script… Skrip lain… Document Setup… Pengaturan dokumen… Switch Units Ganti satuan @@ -160,6 +162,8 @@ Shear… Miringkan… Transform Each… Transformasi masing-masing… Reset Bounding Box Atur ulang kotak pembatas + Rotate Bounding Box Putar kotak pembatas + Rotate Bounding Box… Putar kotak pembatas… Arrange Susun Bring to Front Bawa ke depan Bring Forward Majukan @@ -665,6 +669,13 @@ Previous Document Dokumen sebelumnya Cascade Bertingkat Tile Ubin + Tile All Vertically Ubin semua secara vertikal + Tile All Horizontally Ubin semua secara horizontal + 2-Up Layout Tata letak 2 + 3-Up Layout Tata letak 3 + 4-Up Layout Tata letak 4 + 6-Up Layout Tata letak 6 + Arrange Documents Susun dokumen Float in Window Mengambang di jendela Float All in Windows Mengambangkan semua di jendela Consolidate All Windows Konsolidasikan semua jendela @@ -710,6 +721,11 @@ Saturation and brightness Saturasi dan kecerahan Color field Kolom warna {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Tampilan roda + Box View Tampilan kotak + Box Channel Saluran kotak + Color box Kotak warna + Color Wheel Options Opsi roda warna CSS Properties Properti CSS Document Info Info dokumen Flattener Preview Pratinjau perata @@ -1446,6 +1462,7 @@ lighting Light Cahaya Play Current Selection Putar seleksi saat ini Save Actions… Simpan tindakan… Load Actions… Muat tindakan… + Replace Actions… Ganti tindakan… Reset Actions Atur ulang tindakan Replace the current actions with the default set? Ganti tindakan saat ini dengan set default? Append adds the default set after the current sets instead. Tambahkan justru menambahkan set default setelah set saat ini. @@ -1620,6 +1637,7 @@ digits Malayalam Malayalam Underline Garis bawah Vertical Scale % Skala vertikal % Axis Sumbu + Axis Angle Sudut sumbu ICF Top/Right ICF atas/kanan ICF Bottom/Left ICF bawah/kiri Show Font Height Options Tampilkan opsi tinggi font @@ -1662,6 +1680,7 @@ digits Malayalam Malayalam Rule: Aturan: Save changes to {name} Simpan perubahan ke {name} Save theme to My Themes Simpan tema ke Tema saya + Set the current fill or stroke to the selected color Atur isian atau stroke saat ini ke warna terpilih Set the selected color to the current color Atur warna terpilih ke warna saat ini Copy All Styles Salin semua gaya Exported {path} Diekspor ke {path} @@ -1877,7 +1896,7 @@ digits Malayalam Malayalam Stroke: click for swatches, Shift-click for the color mixer Stroke: klik untuk swatch, Shift+klik untuk pencampur warna This panel is on the roadmap (see the parity plan). Panel ini masih dalam roadmap (lihat rencana paritas). Open a document to navigate it. Buka dokumen untuk menjelajahinya. - View Artboard Only Tampilkan artboard saja + View Artboard Contents Only Tampilkan isi artboard saja Contextual Alternates Alternatif kontekstual Default Figure Angka default Discretionary Ligatures Ligatur opsional @@ -2020,7 +2039,7 @@ digits Malayalam Malayalam Overprint Preview (separations) Pratinjau overprint (separasi) Show All Plates Tampilkan semua pelat Show all plates Tampilkan semua pelat - Show/hide plate (Alt-click: only this plate) Tampilkan/sembunyikan pelat (Alt-klik: hanya pelat ini) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Tampilkan/sembunyikan pelat (Alt-klik: hanya pelat ini; Alt-klik lagi: semua pelat) Simulate Paper Simulasikan kertas Use Black Point Compensation Gunakan kompensasi titik hitam Working CMYK (don't tag) CMYK kerja (tanpa tag) @@ -2060,6 +2079,8 @@ digits Malayalam Malayalam Tip extends past the end point Ujung melewati titik akhir Tip on the end point Ujung pada titik akhir Variable Width Profile Profil lebar variabel + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Kuas pada guratan mempertahankan ukurannya sendiri, sehingga profil lebar tidak mengubahnya. Hapus kuas untuk menggunakan profil. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Kuas pada guratan mempertahankan ukurannya sendiri, sehingga profil lebar tidak mengubahnya. Hapus kuas untuk menggunakan profil. Weight: Ketebalan: Art using a deleted global swatch keeps its colour. Karya seni yang memakai swatch global terhapus tetap mempertahankan warnanya. Color Group: {name} Grup warna: {name} @@ -2169,6 +2190,10 @@ digits Malayalam Malayalam Flip Horizontal Balik horizontal Flip Vertical Balik vertikal Polygon Properties: Properti poligon: + Line Properties: Properti garis: + Line Length: Panjang garis: + Line Angle: Sudut garis: + Constrain Pie Angle Kendalikan sudut pai Rectangle Properties: Properti persegi panjang: Shape Properties: Properti bentuk: Shape Properties Properti bentuk @@ -2210,6 +2235,7 @@ digits Malayalam Malayalam Scatter: Sebaran: Rotation: Rotasi: Rotation relative to: Rotasi relatif terhadap: + Hue Jitter: Variasi rona: Brush Scale Options Opsi skala kuas Scale Proportionately Skalakan proporsional Stretch to Fit Stroke Length Regangkan sesuai panjang stroke @@ -2248,6 +2274,7 @@ digits Malayalam Malayalam Size: Ukuran: Calligraphic Brush Options Opsi kuas kaligrafi Bristle Brush Options Opsi kuas bristle + Roundness Kebulatan Roundness: Kebulatan: Shape: Bentuk: Bristle Length: Panjang bristle: @@ -2558,6 +2585,7 @@ digits Malayalam Malayalam BLANK DOCUMENT PRESETS PRESET DOKUMEN KOSONG Bleed Bleed Change to Right-to-Left Layout Ubah ke tata letak kanan ke kiri + Columns Kolom Columns: Kolom: Documents you create appear here. Dokumen yang Anda buat muncul di sini. More Settings Pengaturan lainnya @@ -2691,6 +2719,9 @@ digits Malayalam Malayalam Open a document to preview its pages Buka dokumen untuk melihat pratinjau halamannya Output › Mode Keluaran › Mode Overprint and Transparency Flattener Options Opsi overprint dan perataan transparansi + Custom… Kustom… + Custom Transparency Flattener Options Opsi perataan transparansi kustom + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS tidak memiliki transparansi alfa, dan Overprint menentukan apakah overprint dipertahankan. Place the pages with the placement again Tempatkan halaman lagi dengan penempatan tersebut Placement: Penempatan: Preserve CMYK Numbers Pertahankan angka CMYK @@ -2740,14 +2771,19 @@ digits Malayalam Malayalam Around Object Di sekeliling objek Background: Latar belakang: Changing these settings changes how raster effects look when exported, flattened or expanded. Mengubah pengaturan ini mengubah tampilan efek raster saat diekspor, diratakan, atau diperluas. + Add Around Tambah di sekeliling objek + Anti Alias Anti-aliasing + Color Model Model warna Color Model: Model warna: Create Clipping Mask Buat clipping mask Preserve Spot Colors Pertahankan warna spot + Resolution Resolusi Resolution: Resolusi: Transparent Transparan Layout Order: Urutan tata letak: Change to Left-to-Right Layout Ubah ke tata letak kiri ke kanan Artboards: {n} Artboard: {n} + Rows Baris Rows: Baris: Assign Tetapkan Color Group: Grup warna: @@ -2896,6 +2932,8 @@ antiAlias Sharp Tajam Every option matches {base}. Setiap opsi cocok dengan {base}. Files of a PDF standard can't be password-protected. File standar PDF tidak dapat dilindungi kata sandi. Files of this standard tag their colours with ICC profiles. File standar ini menandai warnanya dengan profil ICC. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. File standar ini menandai warnanya dengan profil ICC, kecuali warna CMYK dalam profil output intent, yang ditulis sebagai DeviceCMYK. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. Dengan “Jangan sertakan profil” dan output intent CMYK, setiap warna CMYK ditulis sebagai DeviceCMYK, kecuali dikonversi ke tujuan CMYK dengan profil lain. Flattener preset: Preset flattener: General › Thumbnails Umum › Miniatur Grayscale images Gambar skala abu-abu @@ -3079,6 +3117,12 @@ antiAlias Sharp Tajam LF (macOS, Linux) LF (macOS, Linux) CRLF (Windows) CRLF (Windows) Text Export Options Opsi ekspor teks + Chinese Big 5 Tionghoa Big 5 + Cyrillic Sirilik + Greek Yunani + Turkish Turki + Baltic Baltik + Central European Eropa Tengah Character Set: Set karakter: Join the lines of each paragraph Gabungkan baris setiap paragraf Line Breaks Pemisah baris @@ -3108,6 +3152,9 @@ antiAlias Sharp Tajam Variable Options Opsi variabel Define a variable first Tentukan variabel terlebih dahulu Adjust Adjoining Width Points Sesuaikan titik lebar bersebelahan + Incoming Masuk + Outgoing Keluar + Single Width Only Hanya satu lebar Keep both sides the same width Pertahankan kedua sisi tetap sama lebar Side 1: Sisi 1: Side 2: Sisi 2: @@ -3208,9 +3255,13 @@ theme Appearance Tampilan Break Link to Symbol Putuskan tautan ke simbol Brush Definition Definisi kuas Brush Options… Opsi kuas… + Options of Selected Object… Opsi objek yang dipilih… + Options of Selected Object Opsi objek yang dipilih Current Brush Kuas saat ini Current Symbol Simbol saat ini Delete Brush Hapus kuas + Delete Color Hapus warna + Restore Generated Table Pulihkan tabel yang dibuat Delete Symbol Hapus simbol Delete the selected symbol? Hapus simbol yang dipilih? Delete the selected symbols? Hapus simbol yang dipilih? @@ -3487,6 +3538,7 @@ theme Appearance Tampilan Select Art Pilih karya seni Set Current Layer Tetapkan lapisan saat ini Flatten Artwork Ratakan karya seni + Locate Layer Temukan lapisan Locate Object Temukan objek Lock Others Kunci lainnya Merge Selected Gabungkan terpilih @@ -3663,6 +3715,7 @@ theme Appearance Tampilan 90° & 45° Angles Sudut 90° & 45° 90° Angles Sudut 90° Additional Plug-ins Folder Folder plug-in tambahan + Plug-in Instruction Budget Anggaran instruksi plug-in Additional Fonts Folder Folder font tambahan Alignment Guides Panduan perataan Anchor Points, Handle, and Bounding Box Display Tampilan titik jangkar, pegangan, dan kotak pembatas @@ -3689,6 +3742,7 @@ theme Appearance Tampilan Data Recovery Pemulihan data Default Language Bahasa standar Disable Auto Add/Delete Nonaktifkan tambah/hapus otomatis + Interpolate Control Points When Moving Anchors Interpolasikan gagang arah saat memindahkan titik jangkar Display All Blacks Accurately Tampilkan semua warna hitam secara akurat Display All Blacks as Rich Black Tampilkan semua warna hitam sebagai rich black Display Bitmaps as Anti-aliased Images in Pixel Preview Tampilkan bitmap sebagai gambar anti-alias dalam pratinjau piksel @@ -3705,6 +3759,7 @@ theme Appearance Tampilan Enable Rubber Band for Aktifkan rubber band untuk Enable Touch Gestures Aktifkan gestur sentuh Switch Selection and Drawing Modes Beralih antara mode seleksi dan menggambar + Select Last Selection Tool Pilih alat seleksi terakhir Enable Touch Workspace Aktifkan ruang kerja sentuh English: UK Inggris: UK Every (minutes) Setiap (menit) @@ -3776,6 +3831,7 @@ theme Appearance Tampilan Printing / Exporting Pencetakan / Ekspor Real-time Drawing and Editing Penggambaran dan pengeditan waktu nyata Use Monitor Profile for Canvas Gunakan profil monitor untuk kanvas + Refresh Monitor Profile Segarkan profil monitor The canvas is drawn in sRGB. Kanvas digambar dalam sRGB. Canvas display profile: Profil layar kanvas: The system matches the window to the display's colors. Sistem menyesuaikan jendela dengan warna layar. @@ -3837,6 +3893,7 @@ theme Appearance Tampilan Scroll Sideways with Cmd/Ctrl + Wheel Gulir horizontal dengan Cmd/Ctrl + roda mouse Scrub Numeric Fields by Dragging Atur nilai kolom numerik dengan menyeret Linux Display Server Server tampilan Linux + Low-Latency Drawing Penggambaran latensi rendah Print Preview Pratinjau cetak Print Setup Pengaturan cetak Bitmap Bitmap @@ -4171,6 +4228,9 @@ font-technology Variable Variabel Search commands, tools, panels and effects… Cari perintah, alat, panel, dan efek… No commands match Tidak ada perintah yang cocok {pos} of {total}: {name} {pos} dari {total}: {name} + No menu item Tidak ada item menu + Toolbar Bilah alat + {toolbar}, in the {tool} group {toolbar}, dalam grup {tool} @plural {n} result|{n} results {n} hasil @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} dari {n} hasil. Terus ketik untuk mempersempitnya. Recent Commands Perintah terbaru @@ -4207,6 +4267,7 @@ font-technology Variable Variabel The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Roda mouse dengan Cmd/Ctrl ditahan menggulir kanvas ke samping. Dragging sideways on a numeric field's label changes the field's value. Menyeret ke samping pada label bidang angka mengubah nilai bidang itu. A two-finger rotate gesture on a trackpad rotates the canvas view. Gerakan putar dua jari pada trackpad memutar tampilan kanvas. + When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Saat Anda memindahkan titik jangkar, setiap kurva dengan satu ujung yang dipindahkan mempertahankan bentuknya terhadap ujung-ujungnya. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Menahan tombol pintasan alat memilih alat itu sampai Anda melepasnya, lalu alat sebelumnya dipilih lagi. Shows the bounding box while you move the selection or draw a shape. Menampilkan kotak pembatas saat Anda memindahkan seleksi atau menggambar bentuk. Create Trim Marks draws Japanese-style marks instead of Roman ones. Buat tanda potong menggambar tanda bergaya Jepang, bukan Romawi. @@ -4237,6 +4298,29 @@ font-technology Variable Variabel The unit for East Asian type measurements, which no field uses yet. Satuan untuk ukuran teks Asia Timur, yang belum digunakan bidang mana pun. When on, a number typed without a unit into a field in picas is read in points. Jika aktif, angka yang diketik tanpa satuan di bidang dalam pica dibaca dalam titik. With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options. Dengan ID XML, nama objek ditampilkan sebagai ID XML di Lapisan, Variabel, dan Opsi lapisan. + The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl. Langkah untuk ukuran teks dan spasi baris: Cmd/Ctrl+Shift+. dan Cmd/Ctrl+Shift+, mengubah ukuran satu langkah, atau lima dengan Alt juga; pada teks horizontal, Alt dengan panah atas atau bawah mengubah spasi baris satu langkah, atau lima dengan Cmd/Ctrl. + The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl. Langkah untuk tracking dan kerning, dalam perseribu em: pada teks horizontal, Alt dengan panah kiri atau kanan mengubah kerning di kursor atau tracking teks yang dipilih satu langkah, atau lima dengan Cmd/Ctrl. + The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. Langkah untuk pergeseran garis dasar: pada teks horizontal, Alt dan Shift dengan panah atas atau bawah menggeser garis dasar satu langkah, atau lima dengan Cmd/Ctrl. + Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. Menampilkan opsi untuk teks Jepang dan teks Asia Timur lainnya di panel Karakter, Paragraf, OpenType, dan Glif, serta perintah Font komposit. + Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. Menampilkan opsi untuk teks Arab, Ibrani, dan India di panel Karakter dan Paragraf, seperti arah paragraf, kashida, dan digit. + The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. Alat seleksi memilih teks hanya pada garis dasarnya, bingkai teks area, atau jalurnya, bukan di sembarang tempat di dalam kotaknya. + Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. Menu font mencantumkan setiap font dengan nama bahasa Inggrisnya; jika nonaktif, font yang juga punya nama dalam bahasanya sendiri menampilkan nama itu. + New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. Teks area baru dimulai dengan Ukuran otomatis aktif, sehingga bingkai persegi panjang berisi teks horizontal bertambah atau berkurang tingginya agar teksnya muat. + Font lists and the Type › Font menu show a sample of each font beside its name. Daftar font dan menu Font menampilkan contoh setiap font di samping namanya. + Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on. Contoh font digambar dengan teks gelap di atas putih, apa pun kecerahan antarmuka; ini hanya berlaku selama pratinjau font di menu aktif. + How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is. Tinggi setiap baris dalam daftar bidang font, seperti di panel Karakter, dan karenanya besar setiap contoh. + How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first. Berapa banyak font yang terakhir dipakai, dari 1 sampai 15, yang ditampilkan Font terbaru dan daftar font, yang terbaru lebih dulu. + When you change the font or font style of text, characters the new font has no glyph for keep the font they had. Saat Anda mengganti font atau gaya font teks, karakter yang tidak memiliki glif di font baru tetap memakai font sebelumnya. + A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export. Sorotan merah muda di kanvas menandai glif yang diganti oleh fitur OpenType, seperti ligatur; sorotan ini tidak dicetak atau diekspor. + With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from. Dengan alat teks, memilih satu karakter menampilkan deretan glif alternatifnya di sampingnya di kanvas untuk dipilih. + A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export. Sorotan merah muda di kanvas menandai teks yang digambar dengan font pengganti karena fontnya tidak ada; sorotan ini tidak dicetak atau diekspor. + New type made with a Type tool starts with placeholder text, selected, so typing replaces it. Teks baru yang dibuat dengan alat teks dimulai dengan teks pengganti yang terpilih, sehingga ketikan Anda menggantikannya. + Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list. Mengetik penanda daftar seperti 1. atau * lalu spasi di awal paragraf mengubah paragraf itu menjadi daftar. + Fonts in this folder show in the font menus and can be used without being installed. Font di folder ini muncul di menu font dan dapat dipakai tanpa diinstal. + Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows. Menerapkan gaya grafis pada teks menghapus isian atau garis milik karakter jika gaya memilikinya, sehingga cat gaya itu terlihat. + Align and Distribute measure point type by the ink of its glyphs instead of its em box. Sejajarkan dan Distribusikan mengukur teks titik menurut tinta glifnya, bukan kotak em-nya. + Align and Distribute measure area type by the ink of its glyphs instead of its frame. Sejajarkan dan Distribusikan mengukur teks area menurut tinta glifnya, bukan bingkainya. + The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box. Kotak pembatas dan panel Transformasi mengukur teks titik menurut tinta glifnya, bukan kotak em-nya. Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply. Menempelkan penggambaran, pemindahan, dan penskalaan ke subdivisi kisi, bahkan saat kisi disembunyikan; selama opsi ini aktif, Snap ke piksel tidak berlaku. The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead. Warna panduan yang tidak dipilih; artboard yang memiliki Label panduan menggambar panduannya sendiri dengan warna label tersebut. Draws guides as solid lines or as dots, including the guides already in the document. Menggambar panduan sebagai garis utuh atau sebagai titik, termasuk panduan yang sudah ada di dokumen. @@ -4280,6 +4364,8 @@ font-technology Variable Variabel Couldn't paste from the clipboard: {e} Tidak dapat menempel dari papan klip: {e} Channel Saluran Circle Lingkaran + Circle Tool Alat lingkaran + Circle too large Lingkaran terlalu besar Clip to Art Pangkas ke karya seni Colorize Warnai Gamma Gamma @@ -4496,6 +4582,13 @@ imageTrace Outline Kontur Show External Script Warning Tampilkan Peringatan Skrip Eksternal A Script Is Running Skrip Sedang Berjalan Script Alert Peringatan Skrip + Script File Access Akses Berkas Skrip + The script asks to read a file you choose. Skrip meminta izin untuk membaca berkas yang Anda pilih. + The script asks to read and write a file you choose. Skrip meminta izin untuk membaca dan menulis berkas yang Anda pilih. + The script asks to read and write a folder you choose, with everything in it. Skrip meminta izin untuk membaca dan menulis folder yang Anda pilih, beserta seluruh isinya. + Allow Once Izinkan Sekali + Always Allow This Script Selalu Izinkan Skrip Ini + Deny Tolak A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Skrip dapat mengubah dokumen yang terbuka dan menulis file melalui perintah yang dijalankannya. Jalankan hanya skrip yang Anda percayai. Do not show this warning again Jangan tampilkan peringatan ini lagi Stop the script and undo what it did? Then quit again. Hentikan skrip dan batalkan yang telah dilakukannya? Lalu keluar lagi. @@ -4697,6 +4790,7 @@ imageTrace Outline Kontur @msg choose a folder to export to pilih folder tujuan ekspor @msg choose a location for the package pilih lokasi untuk paket @msg clipboard is empty papan klip kosong +@msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: setidaknya satu warna harus tetap ada di tabel warna @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` bukan warna seperti "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: maksimal {MAX_TABLE} warna @msg command `{0}` is not available right now: {1} perintah `{0}` tidak tersedia saat ini: {1} @@ -4842,6 +4936,9 @@ imageTrace Outline Kontur @msg no such user library tidak ada pustaka pengguna seperti itu @msg no such view tidak ada tampilan seperti itu @msg no such width point tidak ada titik lebar seperti itu +@msg `single` must be `incoming` or `outgoing` `single` harus `incoming` atau `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` dan `outIndex` harus berupa dua bagian dari satu titik lebar terputus +@msg a discontinuous width point keeps its place titik lebar terputus tetap di tempatnya @msg no swatch `{name}` tidak ada swatch `{name}` @msg no swatch library `{l}` (see swatch.library.list) tidak ada pustaka swatch `{l}` (lihat swatch.library.list) @msg no symbol instances selected tidak ada instans simbol yang dipilih @@ -5101,6 +5198,9 @@ imageTrace Outline Kontur @msgplural Discarded {n} recovered document|Discarded {n} recovered documents {n} dokumen hasil pemulihan dibuang @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them {n} dokumen hasil pemulihan dipulihkan: simpan agar tidak hilang @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} Dibuka dengan {n} catatan: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Disalin dengan {n} catatan: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Dipotong dengan {n} catatan: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Gambar dilacak dengan {n} catatan: {first} @msgplural {notice}. Opened with {n} note: {first}|{notice}. Opened with {n} notes: {first} {notice}. Dibuka dengan {n} catatan: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} {path} disimpan dengan {n} catatan: {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first {n} gambar tersemat; {missing} hilang: tautkan ulang dulu @@ -5482,6 +5582,7 @@ imageTrace Outline Kontur Ascent Ascent Cap Height Tinggi kapital x Height Tinggi x + Em Box Height Tinggi Em Box Justify Ratakan First Baseline Baseline pertama Vertical Align Perataan vertikal @@ -5589,6 +5690,7 @@ mark-style Japanese Jepang Cove Cove Depth Kedalaman Front Depan + Side Samping Isometric Bottom Isometrik bawah Isometric Left Isometrik kiri Isometric Right Isometrik kanan @@ -5807,6 +5909,8 @@ mark-style Japanese Jepang Reset Tracking and Kerning Atur ulang tracking dan kerning Reset Horizontal Scale Atur ulang skala horizontal Highlight Font Name Sorot nama font + Highlight Font Size Sorot ukuran font + Other… Lainnya… Highlight Kerning Sorot kerning Highlight Tracking Sorot tracking @msg span must be "object" or "selection", got {v} span harus "object" atau "selection", diterima {v} @@ -5869,6 +5973,11 @@ mark-style Japanese Jepang Edge Only Hanya tepi Overlay Edge Hamparkan tepi Path Length Panjang jalur + Grid Size Ukuran kisi + Grid Colors Warna kisi + Flattener Preset Preset flattener + X X + Y Y @msg the file's layers weren't read ({_1}): it comes in as its page, in one layer lapisan file tidak terbaca ({_1}): file masuk sebagai halamannya, dalam satu lapisan @msg the file's layers weren't read from its editing data ({_1}): they come from its PDF part lapisan file tidak terbaca dari data pengeditannya ({_1}): lapisannya berasal dari bagian PDF file @msg the file's variable bindings weren't all read (bindings skipped: {_1}): those objects aren't bound to their variables tidak semua ikatan variabel file terbaca (ikatan yang dilewati: {_1}): objek-objek itu tidak terikat ke variabelnya @@ -5876,6 +5985,8 @@ mark-style Japanese Jepang @msg the file's variable library couldn't be read: the Variables panel doesn't list it pustaka variabel file tidak dapat dibaca: panel Variabel tidak menampilkannya @msg a variable of unknown kind can't be bound to objects variabel bertipe tidak dikenal tidak dapat diikat ke objek @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` harus grayscale, rgb, hsb, cmyk atau websafe +@msg `view` must be wheel or box `view` harus wheel atau box +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` harus hue, saturation, brightness, red, green atau blue @msg the Color Picker is not open Pemilih Warna tidak terbuka @msg the screen color sampler is already open pengambil warna layar sudah terbuka @msg this system has no screen color sampler sistem ini tidak memiliki pengambil warna layar @@ -6703,6 +6814,12 @@ anchor Points: Titik: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` harus "free", "keepAngles" atau "symmetric" @msg `{key}` must be [x, y] `{key}` harus [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Pengonversi Satuan + Unit Converter Panel Panel Pengonversi Satuan + Copy with Units Salin dengan Satuan + From Selection Dari Seleksi + # Color Effects add-on: Select by Color Kind. Select by Color Kind Pilih menurut Jenis Warna Objects with Spot Colors Objek dengan Warna Spot @@ -6904,6 +7021,14 @@ breakText Glyphs Glif Remove Gaps Hapus celah @msg that makes too many pieces (at most 100000): make the dashes longer itu menghasilkan terlalu banyak potongan (paling banyak 100000): perpanjang garisnya @msg select paths, or segments, to divide pilih jalur atau segmen yang akan dibagi +# Path Precision Tools add-on: Smooth Bridge. + Smooth Bridge… Jembatan Halus… + Smooth Bridge Jembatan Halus + Keep Originals Pertahankan Asli +@msg select two circles to bridge pilih dua lingkaran untuk dijembatani +@msg one circle is inside the other satu lingkaran berada di dalam lingkaran lainnya +@msg the circles are too far apart for this radius: raise the radius lingkaran terlalu berjauhan untuk radius ini: perbesar radius +@msg the circles are too far apart for this radius lingkaran terlalu berjauhan untuk radius ini # Path Precision Tools add-on: Common Tangents. Common Tangents… Garis Singgung Persekutuan… Common Tangents Garis Singgung Persekutuan @@ -7251,4 +7376,14 @@ breakText Glyphs Glif @msg A panel is not joined to the rest by a crease. Sebuah panel tidak tersambung ke bagian lain oleh garis lekuk apa pun. @msg A fold line is on a non-printing layer. Sebuah garis lipat berada di lapisan yang tidak dicetak. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panel: {panels}, engsel: {hinges}, galat: {errors}, peringatan: {warnings} + Fold Preview Pratinjau lipatan + Fold Lipat + Show Fold Lines Tampilkan garis lipat + Three-Quarter Tiga perempat + Open a document to preview its folded shape. Buka dokumen untuk melihat pratinjau bentuk terlipatnya. +@msg Check the fold lines first. Periksa garis lipat terlebih dahulu. +@msg Panels: {panels}, hinges: {hinges} Panel: {panels}, engsel: {hinges} +@msg Other blanks not shown: {count} Bentangan lain tidak ditampilkan: {count} +@msg A joint does not close by {gap} pt. Sebuah sambungan tidak menutup sejauh {gap} pt. +@msg Two panels pass through each other. Dua panel saling menembus. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer harus "singleLine", "everyLine", "standardSingleLine", atau "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 8f2ed3216c..e0c426bd1c 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -11,7 +11,7 @@ # Coverage: the whole interface — every menu string and every `tl!` literal (`complete_menus`, # `untranslated_report` lists gaps). Left in English on purpose (`MENU_KEEP_AS_IS` in the tests): the product name, language # names, OpenType, the built-in workspace names and the bracketed perspective grid preset names. -# Photoshop-style raster effects (Effect menu, their dialogs). +# Raster effects (Effect menu, their dialogs). Glowing Edges… Bordi luminosi… Glowing Edges Bordi luminosi Edge Width Larghezza bordo @@ -119,6 +119,7 @@ Add Anchor Point Aggiungi punto di ancoraggio Add Anchor Point Tool Strumento Aggiungi punto di ancoraggio Add Anchor Points Aggiungi punti di ancoraggio + Add Around Aggiungi attorno all'oggetto Add Effect Aggiungi effetto Add Freeform Line Aggiungi linea libera Add Freeform Point Aggiungi punto libero @@ -140,8 +141,12 @@ Add to Swatches Aggiungi ai campioni Add Used Colors Aggiungi colori usati Additional Plug-ins Folder Cartella plug-in aggiuntivi + Plug-in Instruction Budget Budget di istruzioni dei plug-in Additional Fonts Folder Cartella font aggiuntivi Adjust Adjoining Width Points Regola punti di larghezza adiacenti + Incoming In entrata + Outgoing In uscita + Single Width Only Solo una larghezza Adjust Color Balance… Regola bilanciamento colore… Adjust Colors Regola colori Adjust Options: Opzioni di regolazione: @@ -196,6 +201,7 @@ Angle: Angolo: Angles Angoli Animated Zoom Zoom animato + Anti Alias Anti-aliasing Anti-alias Anti-aliasing Anti-Alias Anti-aliasing Anti-alias Rasters Anti-aliasing per immagini raster @@ -363,6 +369,12 @@ font-technology Variable Variabili Brush Definition Definizione pennello Brush Libraries Librerie pennelli Brush Options… Opzioni pennello… + Options of Selected Object… Opzioni dell’oggetto selezionato… + Options of Selected Object Opzioni dell’oggetto selezionato +@msg no path painted with a brush is selected nessun tracciato dipinto con un pennello selezionato +@msg the selected paths are painted with brushes of different types i tracciati selezionati sono dipinti con pennelli di tipi diversi +@msg give `params` or `reset`, not both indica `params` o `reset`, non entrambi +@msg a bristle brush has no options of its own on a path un pennello a setole non ha opzioni proprie su un tracciato Brush Strokes Pennellate Brushes Pennelli Built-in Libraries Librerie integrate @@ -419,6 +431,12 @@ font-technology Variable Variabili Character Alignment Allineamento caratteri Character / Paragraph Carattere / Paragrafo Character Rotation Rotazione caratteri + Chinese Big 5 Cinese Big 5 + Cyrillic Cirillico + Greek Greco + Turkish Turco + Baltic Baltico + Central European Centroeuropeo Character Set: Set di caratteri: Character Style Stile carattere Character Style Options Opzioni stile carattere @@ -481,6 +499,8 @@ font-technology Variable Variabili Choose a folder Scegli una cartella Choose… Scegli… Circle Cerchio + Circle Tool Strumento Cerchio + Circle too large Cerchio troppo grande Classic Defaults Valori predefiniti classici Clean Up… Pulisci… Clear Cancella @@ -556,6 +576,7 @@ font-technology Variable Variabili Color Mixer (Shift-click the chip) Miscelatore colori (Shift+clic sul riquadro colore) Color Mode Metodo colore Color Mode: Metodo colore: + Color Model Modello colore Color Model: Modello colore: Color Models Modelli colore Color Picker Selettore colore @@ -576,12 +597,18 @@ font-technology Variable Variabili Saturation and brightness Saturazione e luminosità Color field Campo colore {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Vista ruota + Box View Vista riquadro + Box Channel Canale del riquadro + Color box Riquadro colore + Color Wheel Options Opzioni ruota dei colori Color Type: Tipo di colore: Color: Colore: Colorize Colora Colors Colori Colors: Colori: Column Graph Tool Strumento Grafico a colonne + Columns Colonne Columns: Colonne: Column… Colonna… Combine Slices Combina sezioni @@ -792,6 +819,8 @@ font-technology Variable Variabili Delete Artboard Elimina tavola da disegno Delete Artboards Elimina tavole da disegno Delete Brush Elimina pennello + Delete Color Elimina colore + Restore Generated Table Ripristina tabella generata Delete Character Style Elimina stile carattere Delete Empty Artboards Elimina tavole da disegno vuote Delete Freeform Point Elimina punto libero @@ -860,6 +889,7 @@ font-technology Variable Variabili Direct Selection Tool Strumento Selezione diretta Direction Handles Maniglie di direzione Disable Auto Add/Delete Disattiva aggiunta/eliminazione automatica + Interpolate Control Points When Moving Anchors Interpola le maniglie di direzione durante lo spostamento dei punti di ancoraggio Disable Opacity Mask Disattiva maschera di opacità Discard Scarta Preserve Mantieni @@ -1053,6 +1083,9 @@ font-technology Variable Variabili Cap Height Altezza maiuscole x-Height Altezza x ICF Box Riquadro ICF + Ascent Ascendente + x Height Altezza x + Em Box Height Altezza riquadro em Show Sample Mostra campione Hide Sample Nascondi campione Max Ascent/Descent Altezza/profondità max @@ -1085,6 +1118,7 @@ font-technology Variable Variabili Enable text access for screen readers Consenti l'accesso al testo per le utilità di lettura dello schermo Enable Touch Gestures Attiva gesti touch Switch Selection and Drawing Modes Passa tra modalità selezione e disegno + Select Last Selection Tool Scegli l'ultimo strumento di selezione Enable Touch Workspace Attiva area di lavoro touch Encoding Codifica Encoding: Codifica: @@ -1265,6 +1299,8 @@ font-technology Variable Variabili Files File Files of a PDF standard can't be password-protected. I file conformi a uno standard PDF non possono essere protetti da password. Files of this standard tag their colours with ICC profiles. I file conformi a questo standard contrassegnano i colori con profili ICC. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. I file conformi a questo standard contrassegnano i colori con profili ICC, tranne i colori CMYK nel profilo dell'intento di output, che vengono scritti come DeviceCMYK. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. Con «Non includere i profili» e un intento di output CMYK, ogni colore CMYK viene scritto come DeviceCMYK, a meno che non venga convertito in una destinazione CMYK di un altro profilo. Fill Riempimento Fill & Stroke Riempimento e traccia Fill (X), double-click for the Color Picker Riempimento (X), fai doppio clic per il selettore colore @@ -1314,6 +1350,8 @@ font-technology Variable Variabili Reset Tracking and Kerning Reimposta spaziatura caratteri e crenatura Reset Horizontal Scale Reimposta scala orizzontale Highlight Font Name Evidenzia nome del font + Highlight Font Size Evidenzia dimensione font + Other… Altro… Highlight Kerning Evidenzia crenatura Highlight Tracking Evidenzia spaziatura caratteri Spacing Spaziatura @@ -2068,6 +2106,7 @@ file-filter Templates Modelli Load SVG into Clipboard Carica SVG negli appunti Load Text into Clipboard Carica testo negli appunti Local Libraries Librerie locali + Locate Layer Individua livello Locate Object Individua oggetto Locate Selected Objects Individua oggetti selezionati Location Posizione @@ -2264,6 +2303,7 @@ file-filter Templates Modelli Scatter: Dispersione: Rotation: Rotazione: Rotation relative to: Rotazione relativa a: + Hue Jitter: Variazione tonalità: Brush Scale Options Opzioni di scala del pennello Scale Proportionately Ridimensiona proporzionalmente Stretch to Fit Stroke Length Allunga per adattare alla lunghezza del tratto @@ -2300,6 +2340,7 @@ file-filter Templates Modelli Black becomes the stroke color and white stays white. Other colors become tints of the stroke color by their lightness. Il nero diventa il colore della traccia e il bianco resta bianco. Gli altri colori diventano tinte del colore della traccia, e più un colore è chiaro, più è chiara la sua tinta. Black and white stay as they are. Dark colors become shades of the stroke color and light colors become tints of it. Il nero resta nero e il bianco resta bianco. Gli altri colori diventano ombre del colore della traccia quando sono scuri e tinte di esso quando sono chiari. The key color becomes the stroke color. The other colors shift their hue by the same amount and keep their saturation and brightness. Il colore chiave diventa il colore della traccia. Gli altri colori ruotano sulla ruota dei colori quanto il colore chiave e mantengono la loro saturazione e luminosità. + Roundness Rotondità Roundness: Rotondità: Fixed Fisso Pressure Pressione @@ -2605,6 +2646,9 @@ file-filter Templates Modelli Overprint Sovrastampa Overprint and Transparency Flattener Sovrastampa e appiattimento trasparenza Overprint and Transparency Flattener Options Opzioni sovrastampa e appiattimento trasparenza + Custom… Personalizzato… + Custom Transparency Flattener Options Opzioni di appiattimento trasparenza personalizzate + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS non ha trasparenza alfa, e Sovrastampe stabilisce se le sovrastampe vengono mantenute. Overprint Black… Sovrastampa nero… Overprint Fill Sovrastampa riempimento Overprint Preview Anteprima sovrastampa @@ -2654,6 +2698,13 @@ file-filter Templates Modelli Pathfinders: Elaborazioni tracciati: Paths Tracciati Path Length Lunghezza dei tracciati + Grid Size Dimensione griglia + Grid Colors Colori griglia + Flattener Preset Preset di appiattimento + X X + Y Y + Orange Arancione + Purple Viola Paths: {paths} Anchors: {anchors} Colors: {colors} Tracciati: {paths} Ancoraggi: {anchors} Colori: {colors} Pattern Motivo Pattern Editing Modifica motivo @@ -2713,6 +2764,7 @@ diagnostics ui interfaccia Play Current Selection Esegui selezione corrente Save Actions… Salva azioni… Load Actions… Carica azioni… + Replace Actions… Sostituisci azioni… Reset Actions Ripristina azioni Replace the current actions with the default set? Sostituire le azioni correnti con il set predefinito? Append adds the default set after the current sets instead. Aggiungi aggiunge invece il set predefinito dopo i set correnti. @@ -2728,6 +2780,10 @@ diagnostics ui interfaccia Polar Grid Tool Strumento Griglia polare Polygon Poligono Polygon Properties: Proprietà poligono: + Line Properties: Proprietà linea: + Line Length: Lunghezza linea: + Line Angle: Angolo linea: + Constrain Pie Angle Vincola angolo del settore Polygon Tool Strumento Poligono Portrait Verticale Power Saving (integrated) Risparmio energetico (integrata) @@ -2889,6 +2945,9 @@ digits Malayalam Malayalam Real World: Mondo reale: Real-time Drawing and Editing Disegno e modifica in tempo reale Use Monitor Profile for Canvas Usa il profilo del monitor per l'area di disegno + Refresh Monitor Profile Aggiorna profilo del monitor +@msg turn on Use Monitor Profile for Canvas first attiva prima «Usa il profilo del monitor per l'area di disegno» +@msg this build doesn't read display profiles questa versione non legge i profili dei display The canvas is drawn in sRGB. L'area di disegno è visualizzata in sRGB. Canvas display profile: Profilo del display per l'area di disegno: The system matches the window to the display's colors. Il sistema adatta la finestra ai colori del display. @@ -3081,6 +3140,8 @@ digits Malayalam Malayalam Reselect Riseleziona Reset Reimposta Reset Bounding Box Reimposta riquadro di delimitazione + Rotate Bounding Box Ruota riquadro di delimitazione + Rotate Bounding Box… Ruota riquadro di delimitazione… Reset Envelope Mesh Reimposta trama involucro Reset Envelope Shape Reimposta forma involucro Reset Essentials Reimposta Essentials @@ -3122,6 +3183,7 @@ digits Malayalam Malayalam Reshape Segment Rimodella segmento Reshape Tool Strumento Rimodella Reshape Type Area Rimodella area di testo + Resolution Risoluzione Resolution: Risoluzione: Responsive Adattivo Restore Ripristina @@ -3148,6 +3210,7 @@ digits Malayalam Malayalam The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. La rotellina del mouse con Cmd/Ctrl premuto scorre l'area di lavoro in orizzontale. Dragging sideways on a numeric field's label changes the field's value. Trascinare in orizzontale sull'etichetta di un campo numerico ne cambia il valore. A two-finger rotate gesture on a trackpad rotates the canvas view. Un gesto di rotazione con due dita sul trackpad ruota la vista dell'area di lavoro. + When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Quando sposti i punti di ancoraggio, ogni curva con un’estremità spostata mantiene la propria forma rispetto alle sue estremità. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Tenere premuta la scorciatoia di uno strumento lo sceglie finché non la rilasci, poi viene scelto di nuovo lo strumento precedente. Shows the bounding box while you move the selection or draw a shape. Mostra il riquadro di delimitazione mentre sposti la selezione o disegni una forma. Create Trim Marks draws Japanese-style marks instead of Roman ones. Crea segni di taglio disegna segni in stile giapponese invece di quelli romani. @@ -3178,6 +3241,29 @@ digits Malayalam Malayalam The unit for East Asian type measurements, which no field uses yet. L'unità per le misure del testo dell'Asia orientale, che nessun campo usa ancora. When on, a number typed without a unit into a field in picas is read in points. Se attiva, un numero digitato senza unità in un campo in pica viene letto in punti. With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options. Con ID XML, i nomi degli oggetti sono mostrati come ID XML in Livelli, Variabili e Opzioni livello. + The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl. Il passo per dimensione del testo e interlinea: Cmd/Ctrl+Maiusc+. e Cmd/Ctrl+Maiusc+, cambiano la dimensione di un passo, o di cinque aggiungendo Alt; nel testo orizzontale, Alt con la freccia su o giù cambia l’interlinea di un passo, o di cinque con Cmd/Ctrl. + The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl. Il passo per tracking e crenatura, in millesimi di em: nel testo orizzontale, Alt con la freccia sinistra o destra cambia la crenatura al cursore o il tracking del testo selezionato di un passo, o di cinque con Cmd/Ctrl. + The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. Il passo per lo spostamento della linea di base: nel testo orizzontale, Alt e Maiusc con la freccia su o giù spostano la linea di base di un passo, o di cinque con Cmd/Ctrl. + Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. Mostra le opzioni per il testo giapponese e di altre lingue dell’Asia orientale nei pannelli Carattere, Paragrafo, OpenType e Glifi, e il comando Font compositi. + Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. Mostra le opzioni per il testo arabo, ebraico e indiano nei pannelli Carattere e Paragrafo, come la direzione del paragrafo, le kashida e le cifre. + The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. Gli strumenti di selezione selezionano il testo solo sulla sua linea di base, sulla cornice del testo in area o sul suo tracciato, non in qualunque punto del suo riquadro. + Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. I menu dei font elencano ogni font con il suo nome inglese; se disattivato, un font che ha anche un nome nella propria lingua mostra quel nome. + New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. Il nuovo testo in area parte con la dimensione automatica attiva, quindi una cornice rettangolare di testo orizzontale cresce o si riduce in altezza per contenere il testo. + Font lists and the Type › Font menu show a sample of each font beside its name. Gli elenchi dei font e il menu Font mostrano un campione di ogni font accanto al suo nome. + Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on. I campioni dei font sono disegnati in testo scuro su bianco, qualunque sia la luminosità dell’interfaccia; vale solo finché le anteprime dei font nei menu sono attive. + How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is. L’altezza di ogni riga negli elenchi dei campi font, come quello del pannello Carattere, e quindi la grandezza di ogni campione. + How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first. Quanti degli ultimi font usati, da 1 a 15, mostrano Font recenti e gli elenchi dei font, dal più recente. + When you change the font or font style of text, characters the new font has no glyph for keep the font they had. Quando cambi il font o lo stile del font di un testo, i caratteri per cui il nuovo font non ha un glifo mantengono il font che avevano. + A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export. Un’evidenziazione rosa sulla tavola segna i glifi sostituiti da funzioni OpenType, come le legature; non viene stampata né esportata. + With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from. Con lo strumento Testo, selezionando un solo carattere appare accanto a esso sulla tavola una fila dei suoi glifi alternativi tra cui scegliere. + A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export. Un’evidenziazione rosa sulla tavola segna il testo disegnato con un font sostitutivo perché il suo font manca; non viene stampata né esportata. + New type made with a Type tool starts with placeholder text, selected, so typing replaces it. Il nuovo testo creato con uno strumento Testo inizia con un testo segnaposto selezionato, che la digitazione sostituisce. + Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list. Digitare un indicatore di elenco come 1. o * e poi uno spazio all’inizio di un paragrafo trasforma il paragrafo in un elenco. + Fonts in this folder show in the font menus and can be used without being installed. I font in questa cartella compaiono nei menu dei font e si possono usare senza installarli. + Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows. Applicare uno stile grafico a un testo toglie ai caratteri il proprio riempimento o traccia dove lo stile ne ha uno, così si vede il colore dello stile. + Align and Distribute measure point type by the ink of its glyphs instead of its em box. Allinea e Distribuisci misurano il testo con punto in base all’inchiostro dei suoi glifi invece che al suo riquadro em. + Align and Distribute measure area type by the ink of its glyphs instead of its frame. Allinea e Distribuisci misurano il testo in area in base all’inchiostro dei suoi glifi invece che alla sua cornice. + The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box. Il riquadro di selezione e il pannello Trasforma misurano il testo con punto in base all’inchiostro dei suoi glifi invece che al suo riquadro em. Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply. Aggancia il disegno, lo spostamento e il ridimensionamento alle suddivisioni della griglia, anche quando la griglia è nascosta; finché è attivo, Aggancia ai pixel non si applica. The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead. Il colore delle guide non selezionate; una tavola da disegno con un'Etichetta delle guide disegna le proprie guide nel colore dell'etichetta. Draws guides as solid lines or as dots, including the guides already in the document. Disegna le guide come linee continue o come punti, comprese le guide già presenti nel documento. @@ -3259,6 +3345,7 @@ digits Malayalam Malayalam Rounded Rectangle Tool Strumento Rettangolo arrotondato Rounded Rectangle… Rettangolo arrotondato… Row Size: Dimensione riga: + Rows Righe Rows: Righe: Rule: Regola: Rulers Righelli @@ -3435,6 +3522,11 @@ digits Malayalam Malayalam Search commands, tools, panels and effects… Cerca comandi, strumenti, pannelli ed effetti… No commands match Nessun comando corrisponde {pos} of {total}: {name} {pos} di {total}: {name} + No menu item Nessuna voce di menu + Toolbar Barra degli strumenti + {toolbar}, in the {tool} group {toolbar}, nel gruppo {tool} + Tool Strumento + Command Comando @plural {n} result|{n} results {n} risultato|{n} risultati @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} di {n} risultato. Continua a digitare per restringerli.|{shown} di {n} risultati. Continua a digitare per restringerli. Recent Commands Comandi recenti @@ -3515,6 +3607,7 @@ digits Malayalam Malayalam Set Slice Rectangle Imposta rettangolo sezione Set Tab Stops Imposta tabulazioni Set Text Imposta testo + Set the current fill or stroke to the selected color Imposta il riempimento o la traccia corrente sul colore selezionato Set the selected color to the current color Imposta il colore selezionato sul colore corrente Set Zoom Imposta zoom Settings… Impostazioni… @@ -3638,7 +3731,7 @@ digits Malayalam Malayalam Show Vivid/Muted Mostra vivaci/tenui Show Warm/Cool Mostra caldi/freddi Show {kind} Brushes Mostra pennelli di tipo {kind} - Show/hide plate (Alt-click: only this plate) Mostra/nascondi lastra (Alt+clic: solo questa lastra) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Mostra/nascondi lastra (Alt+clic: solo questa lastra; di nuovo Alt+clic: tutte le lastre) Show: Mostra: Shown with the optimised preview. Mostrato con l'anteprima ottimizzata. Side 1: Lato 1: @@ -3948,7 +4041,7 @@ digits Malayalam Malayalam Composite Fonts Font compositi Export Composite Fonts Esporta font compositi Import Composite Fonts Importa font compositi -@msg each font must be {name, parts} ogni font deve essere {name, parts} +@msg each font must be {{name, parts}} ogni font deve essere {{name, parts}} @msg unknown key `{k}`; a font takes name and parts chiave sconosciuta `{k}`; un font accetta name e parts @msg each font needs a name ogni font deve avere un nome @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` non può essere il nome di un font composito (da 1 a {COMPOSITE_NAME_MAX} caratteri, senza caratteri di controllo) @@ -3961,7 +4054,7 @@ digits Malayalam Malayalam @msg two composite fonts are named `{_1}` due font compositi si chiamano `{_1}` @msg `{_1}` is the name of an installed font `{_1}` è il nome di un font installato @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2} usa `{font}`, un font composito -@msg give fonts: [{name, parts}…] indica fonts: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] indica fonts: [{{name, parts}}…] @msg path is empty path è vuoto @msg fonts must be a list of composite fonts fonts deve essere un elenco di font compositi @msg names must be strings names deve contenere stringhe @@ -4044,6 +4137,13 @@ digits Malayalam Malayalam Thumbnail View Vista miniature Thumbnails: Miniature: Tile Affianca + Tile All Vertically Affianca tutto verticalmente + Tile All Horizontally Affianca tutto orizzontalmente + 2-Up Layout Layout a 2 + 3-Up Layout Layout a 3 + 4-Up Layout Layout a 4 + 6-Up Layout Layout a 6 + Arrange Documents Disponi documenti Tile Edge Color Colore bordo tassello Tile Edge Color… Colore bordo tassello… Tile Full Pages Affianca pagine intere @@ -4239,6 +4339,8 @@ digits Malayalam Malayalam V Spacing: Spaziatura verticale: V: V: Variable Width Profile Profilo larghezza variabile + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Il pennello della traccia mantiene la propria dimensione, quindi un profilo di larghezza non la modifica. Rimuovi il pennello per usare un profilo. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Il pennello della traccia mantiene la propria dimensione, quindi un profilo di larghezza non la modifica. Rimuovi il pennello per usare un profilo. Variables Variabili New Variable Nuova variabile Delete Variable Elimina variabile @@ -4303,7 +4405,7 @@ digits Malayalam Malayalam Vertical: Verticale: Very High Molto alta View Visualizza - View Artboard Only Visualizza solo tavola da disegno + View Artboard Contents Only Visualizza solo il contenuto della tavola da disegno View Opacity Mask Visualizza maschera di opacità View PDF after saving Visualizza PDF dopo il salvataggio View {n} Vista {n} @@ -4522,6 +4624,7 @@ imageTrace Outline Contorno Bevel Smussato Offset Spostamento Axis Asse + Axis Angle Angolo dell'asse axis Horizontal Orizzontale axis Vertical Verticale axis Both Entrambi @@ -4598,6 +4701,13 @@ axis Both Entrambi Show External Script Warning Mostra avviso per gli script esterni A Script Is Running È in esecuzione uno script Script Alert Avviso dello script + Script File Access Accesso dello script ai file + The script asks to read a file you choose. Lo script chiede di leggere un file che scegli. + The script asks to read and write a file you choose. Lo script chiede di leggere e scrivere un file che scegli. + The script asks to read and write a folder you choose, with everything in it. Lo script chiede di leggere e scrivere una cartella che scegli, con tutto il suo contenuto. + Allow Once Consenti una volta + Always Allow This Script Consenti sempre questo script + Deny Nega A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Uno script può modificare i documenti aperti e scrivere file tramite i comandi che esegue. Esegui solo script di cui ti fidi. Do not show this warning again Non mostrare più questo avviso Stop the script and undo what it did? Then quit again. Interrompere lo script e annullare ciò che ha fatto? Poi esci di nuovo. @@ -4614,6 +4724,8 @@ axis Both Entrambi @msg the script is no longer in the Scripts folder lo script non è più nella cartella Scripts Some scripts were not listed Alcuni script non sono stati elencati The Scripts folder cannot be read Impossibile leggere la cartella Scripts + Loading scripts… Caricamento degli script… + The Scripts folder is still being read La cartella Scripts è ancora in lettura @msg the script's run is no longer available l'esecuzione dello script non è più disponibile @msg a failed command changed undo steps that could not be put back, so the script was stopped un comando non riuscito ha modificato passaggi di annullamento che non è stato possibile ripristinare, quindi lo script è stato interrotto @msg a recovery copy could not be written, so the script was not run non è stato possibile scrivere una copia di recupero, quindi lo script non è stato eseguito @@ -4626,8 +4738,6 @@ axis Both Entrambi @msg Script file could not be read Impossibile leggere il file di script @msg Script folder has more than 2,048 entries La cartella di script contiene più di 2.048 voci @msg Script file open mode must be r, w, e or a La modalità di apertura del file di script deve essere r, w, e oppure a -@msg Script file writing is not available La scrittura dei file di script non è disponibile -@msg Script file dialogs are not available Le finestre di dialogo dei file di script non sono disponibili @msg Script files cannot be opened in another application I file di script non possono essere aperti in un'altra applicazione @msg Script file access is unavailable on the web L'accesso ai file di script non è disponibile sul web @msg Script has 256 files open Lo script ha 256 file aperti @@ -4744,6 +4854,27 @@ liquify-list-end {0}, {1} {0} e {1} @msg there is no script engine named {name} non esiste un motore di script chiamato {name} @msg Running a script Esecuzione di uno script @msg Copied the script report Rapporto dello script copiato +@msg Script file access denied: {path} Accesso dello script ai file negato: {path} +@msg Script file access to the app's own folders is not allowed L'accesso dello script alle cartelle dell'app non è consentito +@msg Script file cannot encode the text Il file dello script non può codificare il testo +@msg Script file could not be written Impossibile scrivere il file dello script +@msg Script file dialogs need a person to answer them Le finestre di dialogo dei file dello script richiedono una persona che risponda +@msg Script file is not open for writing Il file dello script non è aperto in scrittura +@msg Script file name is already in use Il nome del file dello script è già in uso +@msg Script file name must be a name without a folder Il nome del file dello script deve essere un nome senza cartella +@msg Script file permission can be kept only for a script run from a file Il permesso sui file può essere mantenuto solo per uno script eseguito da un file +@msg Script file permission could not be saved Impossibile salvare il permesso sui file dello script +@msg Script folder is not empty La cartella dello script non è vuota +@msg Script files cannot make aliases I file dello script non possono creare alias +@msg Script file hidden setting cannot be changed L'impostazione nascosto del file dello script non può essere modificata +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: una finestra di dialogo dei file non può aprirsi in un callback di una funzione integrata, di un getter, di una conversione o di un file eseguito da $.evalFile; chiamala dal codice dello script stesso +@msg the script wrote more file data than one run may write (32 MiB) lo script ha scritto più dati di file di quanti ne possa scrivere un'esecuzione (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` per la finestra di dialogo dei file di uno script deve essere uno tra: once, always, deny, stop +@msg choose a file or folder first, or deny scegli prima un file o una cartella, oppure nega +@msg the script file permissions could not be saved: {e} impossibile salvare i permessi sui file degli script: {e} +@msg this script's file access can be allowed only once l'accesso ai file di questo script può essere consentito solo una volta +@msg Only the person at the keyboard can allow a script's file access Solo la persona alla tastiera può consentire l’accesso ai file di uno script +@msg A script is given at most 2,048 files: the files picked after them were left out Uno script riceve al massimo 2.048 file: i file scelti dopo questi sono stati esclusi @msg Copied the link info Informazioni collegamento copiate @msg Corners edits the corners of a path Angoli modifica gli angoli di un tracciato @msg Couldn't copy to the system clipboard: {e} Impossibile copiare negli appunti di sistema: {e} @@ -4819,6 +4950,7 @@ liquify-list-end {0}, {1} {0} e {1} @msg Saved {path} Salvato {path} @msg Select text or click into text with the Type tool to insert glyphs Seleziona del testo o fai clic nel testo con lo strumento Testo per inserire glifi @msg Shape Builder: no region under the pointer Generatore forme: nessuna regione sotto il puntatore +@msg Shape Builder: select all paths you want to merge Generatore forme: seleziona tutti i tracciati da unire @msg Shape Builder: select paths or compound paths Generatore forme: seleziona tracciati o tracciati composti @msg Show All Hidden Attributes: nothing is hidden Mostra tutti gli attributi nascosti: non c'è nulla di nascosto @msg Split Into Grid: select paths large enough for the grid Dividi in griglia: seleziona tracciati abbastanza grandi per la griglia @@ -4874,6 +5006,8 @@ liquify-list-end {0}, {1} {0} e {1} @msg `{min_key}` is greater than `{max_key}` `{min_key}` è maggiore di `{max_key}` @msg give at least one of `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` indica almeno uno tra `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` deve essere grayscale, rgb, hsb, cmyk o websafe +@msg `view` must be wheel or box `view` deve essere wheel o box +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` deve essere hue, saturation, brightness, red, green o blue @msg `{k}` must be [x, y] `{k}` deve essere [x, y] @msg `{name}` has no options `{name}` non ha opzioni @msg `{name}` is a built-in workspace; choose another name `{name}` è un'area di lavoro integrata; scegli un altro nome @@ -4962,6 +5096,7 @@ liquify-list-end {0}, {1} {0} e {1} @msg bad trailer trailer non valido @msg balance must be between 0 and 100 balance deve essere compreso tra 0 e 100 @msg batch step {_1} (`{id}`) failed: {e} il passaggio {_1} del batch (`{id}`) non è riuscito: {e} +@msg action step {_1} (`{id}`) failed: {reason} il passaggio {_1} dell’azione (`{id}`) non è riuscito: {reason} @msg brightness must be dark|mediumDark|mediumLight|light brightness deve essere dark|mediumDark|mediumLight|light @msg can't encode the document: {0} impossibile codificare il documento: {0} @msg can't parse shortcut `{c}` impossibile interpretare la scelta rapida `{c}` @@ -4981,6 +5116,7 @@ liquify-list-end {0}, {1} {0} e {1} @msg choose a folder to export to scegli una cartella in cui esportare @msg choose a location for the package scegli una posizione per il pacchetto @msg clipboard is empty gli appunti sono vuoti +@msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: almeno un colore deve restare nella tabella colori @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` non è un colore come "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: al massimo {MAX_TABLE} colori @msg command `{0}` is not available right now: {1} il comando `{0}` non è disponibile in questo momento: {1} @@ -5048,9 +5184,15 @@ liquify-list-end {0}, {1} {0} e {1} @msg no PNG encoder nessun codificatore PNG @msg no active document nessun documento attivo @msg no active perspective plane nessun piano prospettico attivo +@msg the perspective grid is hidden la griglia prospettica è nascosta +@msg Automatic Plane Positioning is off: turn on anchorPoint or gridlineIntersection (perspective.widget.options) Il posizionamento automatico del piano è disattivato: attiva anchorPoint o gridlineIntersection (perspective.widget.options) +@msg anchorPoint must be true or false anchorPoint deve essere true o false +@msg gridlineIntersection must be true or false gridlineIntersection deve essere true o false +@msg tolerance must be 0 or more tolerance deve essere 0 o maggiore +@msg give `at` or `clear`, not both indica `at` o `clear`, non entrambi @msg no anchor points selected nessun punto di ancoraggio selezionato -@msg `points` must be three [x, y] pairs of numbers `points` deve essere composto da tre coppie di numeri [x, y] -@msg direct-select three anchor points, or give `points` seleziona con Selezione diretta tre punti di ancoraggio oppure indica `points` +@msg `points` must be two or three [x, y] pairs of numbers `points` deve essere composto da due o tre coppie di numeri [x, y] +@msg direct-select two or three anchor points, or give `points` seleziona con Selezione diretta due o tre punti di ancoraggio oppure indica `points` @msg no circle passes through these points: two are the same or all three lie on one line nessun cerchio passa per questi punti: due coincidono oppure tutti e tre sono allineati @msg no app to open files here nessuna app per aprire file qui @msg no artboard nessuna tavola da disegno @@ -5152,6 +5294,9 @@ liquify-list-end {0}, {1} {0} e {1} @msg no such user library libreria utente inesistente @msg no such view vista inesistente @msg no such width point punto di larghezza inesistente +@msg `single` must be `incoming` or `outgoing` `single` deve essere `incoming` o `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` e `outIndex` devono essere le due metà di un unico punto di larghezza discontinuo +@msg a discontinuous width point keeps its place un punto di larghezza discontinuo mantiene la sua posizione @msg no swatch `{name}` nessun campione `{name}` @msg no swatch library `{l}` (see swatch.library.list) nessuna libreria campioni `{l}` (vedi swatch.library.list) @msg no symbol instances selected nessuna istanza di simbolo selezionata @@ -5411,6 +5556,13 @@ liquify-list-end {0}, {1} {0} e {1} @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} più di {MAX_CSV_ROWS} set di dati: Importa set di dati ne legge al massimo {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} più di {MAX_CSV_COLS} variabili: Importa set di dati ne legge al massimo {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} le variabili che non sono di testo sono state escluse: {kinds} +variable-kind Visibility Visibilità +variable-kind Linked File File collegato +variable-kind Graph Data Dati grafico +variable-kind Unknown Sconosciuto +variable-list-two {0}, {1} {0} e {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} e {1} @msg a new document won't read these variables back with their kind: {names} un nuovo documento non rileggerà queste variabili con il loro tipo: {names} @msg a new document refuses this file because of these variables: {names} un nuovo documento rifiuta questo file a causa di queste variabili: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them l’intestazione `{header}` di `{name}` verrebbe riletta come la variabile `{other}`: rinomina una delle due @@ -5436,6 +5588,8 @@ liquify-list-end {0}, {1} {0} e {1} @msg {label}: lost track of a shape's style {label}: lo stile di una forma è andato perso @msg {label}: select paths {label}: seleziona tracciati @msg {label}: select paths, compound paths, groups or text {label}: seleziona tracciati, tracciati composti, gruppi o testo +@msg a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first una linea o un altro tracciato aperto che non racchiude alcuna area non modifica la forma del risultato; per includerlo, applica prima Oggetto › Tracciato › Contorna traccia +@msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first {label} ha prodotto un risultato vuoto: una linea o un altro tracciato aperto non racchiude alcuna area; per includerlo, applica prima Oggetto › Tracciato › Contorna traccia @msg {label}… {label}… @msg {name}: CRC mismatch {name}: CRC non corrispondente @msg {name}: no local header {name}: nessuna intestazione locale @@ -5462,6 +5616,9 @@ liquify-list-end {0}, {1} {0} e {1} @msgplural Discarded {n} recovered document|Discarded {n} recovered documents Scartato {n} documento recuperato|Scartati {n} documenti recuperati @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them Ripristinato {n} documento recuperato. Salvalo per conservarlo|Ripristinati {n} documenti recuperati. Salvali per conservarli @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} Aperto con {n} nota: {first}|Aperto con {n} note: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Copiato con {n} nota: {first}|Copiato con {n} note: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Tagliato con {n} nota: {first}|Tagliato con {n} note: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Immagine ricalcata con {n} nota: {first}|Immagine ricalcata con {n} note: {first} @msgplural {notice}. Opened with {n} note: {first}|{notice}. Opened with {n} notes: {first} {notice}. Aperto con {n} nota: {first}|{notice}. Aperto con {n} note: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} Salvato {path} con {n} nota: {first}|Salvato {path} con {n} note: {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first Incorporata {n} immagine; mancanti: {missing} (ricollegale prima)|Incorporate {n} immagini; mancanti: {missing} (ricollegale prima) @@ -5488,6 +5645,8 @@ liquify-list-end {0}, {1} {0} e {1} @msg All colors are within the CMYK gamut Tutti i colori rientrano nella gamma CMYK @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} colore è fuori dalla gamma CMYK|{n} colori sono fuori dalla gamma CMYK @msg Unembedded to {_1} Incorporamento rimosso, salvato in {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} Incorporamento rimosso per {n} immagine, salvata in {folder}|Incorporamento rimosso per {n} immagini, salvate in {folder} +@msg every numbered name for {name} is taken in that folder tutti i nomi numerati per {name} sono già usati in quella cartella @msg Reset {_1} Reimpostato {_1} @msg Sent to {_1} Inviato a {_1} @msg {_1} files {_1} file @@ -5503,6 +5662,8 @@ liquify-list-end {0}, {1} {0} e {1} @msg Reload the page to go on (changes not saved yet may be lost). Ricarica la pagina per continuare (le modifiche non ancora salvate potrebbero andare perse). @msg tool (a tool id) is required tool (un id di strumento) è obbligatorio @msg {tool} isn't in a toolbar group of several tools {tool} non fa parte di un gruppo di più strumenti nella barra degli strumenti +@msg Presentation Mode hides the toolbars: change the screen mode to show them la Modalità presentazione nasconde le barre degli strumenti: cambia la modalità schermo per mostrarle +@msg Tab has hidden the toolbars: press Tab to show them Tab ha nascosto le barre degli strumenti: premi Tab per mostrarle @msg onto must name a panel floating in another group onto deve indicare un pannello mobile in un altro gruppo @msg below and above must name a panel floating in another group below e above devono indicare un pannello mobile in un altro gruppo @msg give only one of onto, below and above indica solo uno tra onto, below e above @@ -5617,6 +5778,9 @@ liquify-list-end {0}, {1} {0} e {1} @msg automation path rejected: outside the read root {root}: {path} percorso di automazione rifiutato: fuori dalla cartella radice di lettura {root}: {path} @msg automation path rejected: outside the read roots {roots}: {path} percorso di automazione rifiutato: fuori dalle cartelle radice di lettura {roots}: {path} @msg a linked JavaScript file is outside the read roots un file JavaScript collegato è fuori dalle cartelle radice di lettura +@msg a linked image file is outside the read roots un file immagine collegato è fuori dalle cartelle radice di lettura +@msg a linked file's export folder is outside the read roots la cartella di esportazione di un file collegato è fuori dalle cartelle radice di lettura +@msg a linked file's editing data can't be read to check it against the read roots impossibile leggere i dati di modifica di un file collegato per verificarli rispetto alle cartelle radice di lettura @msg automation path rejected: outside the write root {root}: {path} percorso di automazione rifiutato: fuori dalla cartella radice di scrittura {root}: {path} @msg automation path rejected: outside the write roots {roots}: {path} percorso di automazione rifiutato: fuori dalle cartelle radice di scrittura {roots}: {path} @msg automation path rejected: path is empty percorso di automazione rifiutato: il percorso è vuoto @@ -5846,6 +6010,7 @@ lighting Light Luce @msg missing panel layout Disposizione dei pannelli mancante @msg unsupported native docking operation Operazione nativa di ancoraggio non supportata Linux Display Server Server di visualizzazione Linux + Low-Latency Drawing Disegno a bassa latenza X11 (XWayland) When a Pen Is Attached X11 (XWayland) quando è collegata una penna If a drawing tablet's pen doesn't draw, choose an X11 (XWayland) option. Se la penna di una tavoletta grafica non disegna, scegli un'opzione X11 (XWayland). X11 (XWayland) X11 (XWayland) @@ -5900,6 +6065,7 @@ lighting Light Luce Cove Guscio Depth Profondità Front Fronte + Side Lato Isometric Bottom Isometrica sotto Isometric Left Isometrica sinistra Isometric Right Isometrica destra @@ -5994,7 +6160,7 @@ lighting Light Luce @msg each of `{GRAPHICS}` must be an object ogni voce di `{GRAPHICS}` deve essere un oggetto @msg `{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}` le voci di `{GRAPHICS}` accettano symbol, face, x, y, scale e rotation, non `{k}` @msg each of `{GRAPHICS}` needs `symbol`, the name of a symbol ogni voce di `{GRAPHICS}` richiede `symbol`, il nome di un simbolo -@msg `{GRAPHICS}` face must be front or back face di `{GRAPHICS}` deve essere front o back +@msg `{GRAPHICS}` face must be front, back or side face di `{GRAPHICS}` deve essere front, back o side @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} di `{GRAPHICS}` deve essere un numero da {lo} a {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` deve essere un array @msg Graphics map onto the Plane, Extrude and Revolve object types Le grafiche si applicano ai tipi di oggetto Piano, Estrusione e Rivoluzione @@ -7008,6 +7174,12 @@ anchor Points: Punti: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` deve essere "free", "keepAngles" o "symmetric" @msg `{key}` must be [x, y] `{key}` deve essere [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Convertitore di unità + Unit Converter Panel Pannello Convertitore di unità + Copy with Units Copia con le unità + From Selection Dalla selezione + # Color Effects add-on: Select by Color Kind. Select by Color Kind Seleziona per tipo di colore Objects with Spot Colors Oggetti con colori spot @@ -7233,6 +7405,14 @@ breakText Glyphs Glifi Remove Gaps Rimuovi le distanze @msg that makes too many pieces (at most 100000): make the dashes longer così si ottengono troppi pezzi (al massimo 100000): allunga i trattini @msg select paths, or segments, to divide seleziona tracciati o segmenti da dividere +# Path Precision Tools add-on: Smooth Bridge. + Smooth Bridge… Ponte morbido… + Smooth Bridge Ponte morbido + Keep Originals Mantieni originali +@msg select two circles to bridge seleziona due cerchi da unire +@msg one circle is inside the other un cerchio è dentro l’altro +@msg the circles are too far apart for this radius: raise the radius i cerchi sono troppo distanti per questo raggio: aumenta il raggio +@msg the circles are too far apart for this radius i cerchi sono troppo distanti per questo raggio # Path Precision Tools add-on: Common Tangents. Common Tangents… Tangenti comuni… Common Tangents Tangenti comuni @@ -7602,6 +7782,14 @@ breakText Glyphs Glifi @msg `answers` has more than {MAX_ANSWERS} answers `answers` ha più di {MAX_ANSWERS} risposte @msg `answers` is larger than 1 MiB `answers` supera 1 MiB @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` è solo per un'esecuzione senza nessuno a cui chiedere: nell'app, la persona risponde a ogni finestra di dialogo +@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` deve essere un numero intero da 1 a {_1} +@msg `args{place}` is nested more than 64 levels deep `args{place}` è annidato per più di 64 livelli +@msg `args` must be an object `args` deve essere un oggetto +@msg `args` is larger than 1 MiB `args` supera 1 MiB +@msg `path` is empty `path` è vuoto +@msg `installed` takes a `path`, not a `source` `installed` accetta un `path`, non un `source` +@msg `path` must name a .js or .jsx file `path` deve indicare un file .js o .jsx +@msg give exactly one of `path` and `source` indica esattamente uno tra `path` e `source` @msg `answers` must be a list of answers `answers` deve essere un elenco di risposte @msg `artboard` must be the index of an artboard of the document `artboard` deve essere l'indice di una tavola da disegno del documento @msg `artboardsAt` must be [x, y] `artboardsAt` deve essere [x, y] @@ -7645,7 +7833,7 @@ breakText Glyphs Glifi @msg `rows` must be lists of numbers or nulls, not {r} `rows` deve essere un elenco di liste di numeri o null, non {r} @msg `scale` must be a number from 0.001 to 1000 `scale` deve essere un numero compreso tra 0.001 e 1000 @msg `scope.{key}` must be a non-empty array `scope.{key}` deve essere un array non vuoto -@msg `scope` must be "document", {artboards} or {layers} `scope` deve essere "document", {artboards} o {layers} +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` deve essere "document", {{artboards: [index, …]}} o {{layers: [id, …]}} @msg `side` must be "left", "right", "top" or "bottom" `side` deve essere "left", "right", "top" o "bottom" @msg `side` places the artboard: leave out x, y, width and height `side` posiziona la tavola da disegno: ometti x, y, width e height @msg `source` is the only path in series group `target` `source` è l'unico tracciato nel gruppo in serie `target` @@ -7830,7 +8018,7 @@ breakText Glyphs Glifi @msg not a regular expression non è un'espressione regolare @msg not an action set: the text doesn't start with /version and a number non è un set di azioni: il testo non inizia con /version e un numero @msg nothing to repeat niente da ripetere -@msg numbers out of order in {_1} quantifier numeri non in ordine nel quantificatore {_1} +@msg numbers out of order in {{}} quantifier numeri non in ordine nel quantificatore {{}} @msg object {_1} needs a 3D effect l'oggetto {_1} richiede un effetto 3D @msg object {_1}: a hollow Extrude & Bevel has no caps: turn on Cap to map a graphic oggetto {_1}: un'estrusione e smussatura cava non ha tappi: attiva Tappo per applicare una grafica @msg object {_1}: with a depth of 0 the object has one face: map its graphics onto the front oggetto {_1}: con una profondità di 0 l'oggetto ha una sola faccia: applica le sue grafiche sulla faccia anteriore @@ -7899,7 +8087,7 @@ breakText Glyphs Glifi @msg the library's file is outside the read roots il file della libreria è fuori dalle cartelle di lettura consentite @msg the line is too long, or the paths it passes too many, to check la linea è troppo lunga, o i tracciati che attraversa sono troppi, per poterla verificare @msg the method needs an XML value il metodo richiede un valore XML -@msg the paint is not a freeform gradient (apply one with paint.editGradient {kind}) la pittura non è una sfumatura a forma libera (applicane una con paint.editGradient {kind}) +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) la pittura non è una sfumatura a forma libera (applicane una con paint.editGradient {{kind: "freeform"}}) @msg the parameters or body do not form one function i parametri o il corpo non formano un'unica funzione @msg the pasted SVG filter {name} draws differently from the document's filter of that name, and no free name fits it il filtro SVG incollato {name} disegna in modo diverso dal filtro del documento con quel nome, e non c'è un nome libero adatto @msg the paths are too many or too tangled to find where they cross i tracciati sono troppi o troppo intrecciati per trovare dove si incrociano @@ -8186,6 +8374,8 @@ breakText Glyphs Glifi @msg `{f}` is the copy of a document open now `{f}` è la copia di un documento aperto in questo momento @msg `{id}` is no writable format (see document.formats) `{id}` non è un formato scrivibile (vedi document.formats) @msg `{id}` isn't a loaded library `{id}` non è una libreria caricata +@msg `{file}` has no swatches of its own `{file}` non ha campioni propri +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` ha campioni motivo, che un file .vcswatches non può contenere @msg `{key}` has no colours `{key}` non ha colori @msg `{key}` is a design name `{key}` è il nome di un design @msg `{key}` is a design name or a list of them `{key}` è il nome di un design o un elenco di nomi @@ -8408,7 +8598,13 @@ breakText Glyphs Glifi @msg colorModel must be {own} (the document's mode), grayscale or bitmap colorModel deve essere {own} (il metodo del documento), grayscale o bitmap @msg colour groups can't go into colour groups i gruppi di colori non possono entrare in altri gruppi di colori @msg colour, mode and spot apply to solid-colour swatches only colore, metodo e spot si applicano solo ai campioni di colore pieno -@msg column {column}: `{cell}` is a `%` column of graph data files, which are not read colonna {column}: `{cell}` è una colonna `%` dei file di dati dei grafici, che non vengono letti +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path riga {line}, colonna {column}: il file di dati del grafico `{path}` per `{var}` è un percorso relativo: indica `base` o un percorso assoluto +@msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} riga {line}, colonna {column}: impossibile leggere il file di dati del grafico per `{var}`: {e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` isn't followed: {r} riga {line}, colonna {column}: il file di dati del grafico `{path}` per `{var}` non viene seguito: {r} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes riga {line}, colonna {column}: il file di dati del grafico `{path}` per `{var}` supera i {MAX_GRAPH_DATA_FILE} byte +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes riga {line}, colonna {column}: il file di dati del grafico `{path}` per `{var}` dà un valore di grafico che supera i {MAX_GRAPH_CSV} byte +@msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all riga {line}, colonna {column}: i file di dati dei grafici contengono in tutto più di {MAX_GRAPH_FILES_TOTAL} byte +@msg `base` is empty `base` è vuoto @msg column {column}: `{cell}` names `{name}`, which is a {_1} variable colonna {column}: `{cell}` indica `{name}`, che è una variabile {_1} @msg column {column}: `{cell}` names no variable colonna {column}: `{cell}` non indica alcuna variabile @msg column {column}: the variable name is longer than {MAX_NAME} characters colonna {column}: il nome della variabile supera {MAX_NAME} caratteri @@ -8420,6 +8616,7 @@ breakText Glyphs Glifi @msg compound {_1} must contain exactly one open path to join il composto {_1} deve contenere esattamente un tracciato aperto da unire @msg connect end must be "start" or "end" end di connect deve essere "start" o "end" @msg connect needs a path other than the one extended connect richiede un tracciato diverso da quello esteso +@msg connect needs extend connect richiede extend @msg connect needs id connect richiede id @msg connect path has no open end il tracciato di connect non ha un'estremità aperta @msg copy needs path: the file to copy into the document's folder copy richiede path: il file da copiare nella cartella del documento @@ -9550,3 +9747,13 @@ breakText Glyphs Glifi @msg A panel is not joined to the rest by a crease. Un pannello non è unito al resto da alcuna linea di cordonatura. @msg A fold line is on a non-printing layer. Una linea di piega si trova su un livello non stampabile. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Pannelli: {panels}, cerniere: {hinges}, errori: {errors}, avvisi: {warnings} + Fold Preview Anteprima piegatura + Fold Piegatura + Show Fold Lines Mostra linee di piega + Three-Quarter Tre quarti + Open a document to preview its folded shape. Apri un documento per vederne in anteprima la forma piegata. +@msg Check the fold lines first. Verifica prima le linee di piega. +@msg Panels: {panels}, hinges: {hinges} Pannelli: {panels}, cerniere: {hinges} +@msg Other blanks not shown: {count} Altri fustellati non mostrati: {count} +@msg A joint does not close by {gap} pt. Una giunzione non si chiude di {gap} pt. +@msg Two panels pass through each other. Due pannelli si attraversano. diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index c429f204a1..522dfd3573 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -49,6 +49,9 @@ font-technology Variable バリアブル Cap Height キャップハイト x-Height x ハイト ICF Box 平均字面 + Ascent アセント + x Height x ハイト + Em Box Height 仮想ボディの高さ Show Sample サンプルを表示 Hide Sample サンプルを隠す Max Ascent/Descent 最大アセント/ディセント @@ -217,6 +220,8 @@ digits Malayalam マラヤーラム数字 Shear… シアー… Transform Each… 個別に変形… Reset Bounding Box バウンディングボックスのリセット + Rotate Bounding Box バウンディングボックスの回転 + Rotate Bounding Box… バウンディングボックスの回転… Arrange 重ね順 Bring to Front 最前面へ Bring Forward 前面へ @@ -464,6 +469,8 @@ digits Malayalam マラヤーラム数字 Reset Tracking and Kerning トラッキングとカーニングをリセット Reset Horizontal Scale 水平比率をリセット Highlight Font Name フォント名をハイライト + Highlight Font Size フォントサイズをハイライト + Other… その他… Highlight Kerning カーニングをハイライト Highlight Tracking トラッキングをハイライト Step Type 文字を段階的に調整 @@ -750,6 +757,13 @@ digits Malayalam マラヤーラム数字 Previous Document 前のドキュメント Cascade 重ねて表示 Tile 並べて表示 + Tile All Vertically すべてを左右に並べて表示 + Tile All Horizontally すべてを上下に並べて表示 + 2-Up Layout 2 分割レイアウト + 3-Up Layout 3 分割レイアウト + 4-Up Layout 4 分割レイアウト + 6-Up Layout 6 分割レイアウト + Arrange Documents ドキュメントの配置 Float in Window ウィンドウを分離 Float All in Windows すべてをウィンドウに分離 Consolidate All Windows すべてのウィンドウを統合 @@ -788,6 +802,11 @@ digits Malayalam マラヤーラム数字 Saturation and brightness 彩度と明るさ Color field カラーフィールド {name1} {value1}, {name2} {value2} {name1} {value1}、{name2} {value2} + Wheel View ホイール表示 + Box View ボックス表示 + Box Channel ボックスのチャンネル + Color box カラーボックス + Color Wheel Options カラーホイールオプション CSS Properties CSS プロパティ Document Info ドキュメント情報 Flattener Preview 分割・統合プレビュー @@ -1053,6 +1072,7 @@ digits Malayalam マラヤーラム数字 Add Anchor (Pen) アンカーポイントを追加 (ペン) Add Anchor Point アンカーポイントを追加 Add Anchor Point Tool アンカーポイントの追加ツール + Add Around オブジェクトの周囲に追加 Add Effect 効果を追加 Add Freeform Line フリーフォームラインを追加 Add Freeform Point フリーフォームポイントを追加 @@ -1073,8 +1093,12 @@ digits Malayalam マラヤーラム数字 Add to Selection 選択範囲に追加 Add to Swatches スウォッチに追加 Additional Plug-ins Folder 追加プラグインフォルダー + Plug-in Instruction Budget プラグインの命令予算 Additional Fonts Folder 追加フォントフォルダー Adjust Adjoining Width Points 隣接する幅ポイントを調整 + Incoming 入り側 + Outgoing 出側 + Single Width Only 1 つの幅のみ Adjust Colors カラーを調整 Adjust Options: 調整オプション: Advanced Options 詳細オプション @@ -1114,6 +1138,7 @@ digits Malayalam マラヤーラム数字 Angle: 角度: Angles 角度 Animated Zoom アニメーションズーム + Anti Alias アンチエイリアス Anti-Alias アンチエイリアス Anti-alias アンチエイリアス Anti-alias Rasters ラスターをアンチエイリアス @@ -1215,6 +1240,12 @@ antiAlias Sharp シャープ Brush Affects: ブラシの影響: Brush Definition ブラシの定義 Brush Options… ブラシオプション… + Options of Selected Object… 選択中のオブジェクトのオプション… + Options of Selected Object 選択中のオブジェクトのオプション +@msg no path painted with a brush is selected ブラシで描かれたパスが選択されていません +@msg the selected paths are painted with brushes of different types 選択したパスは種類の異なるブラシで描かれています +@msg give `params` or `reset`, not both `params` と `reset` は同時に指定できません +@msg a bristle brush has no options of its own on a path 剛毛ブラシにはパスごとのオプションがありません Built-in presets are read-only: New… starts an editable copy. 組み込みのプリセットは読み取り専用です。「新規…」で編集可能なコピーを作成できます。 Built-in presets don't change: New makes a copy you can edit. 組み込みのプリセットは変更できません。「新規」で編集可能なコピーを作成します。 Built-in presets don't change: New… starts an editable copy. 組み込みのプリセットは変更できません。「新規…」で編集できる複製を作成します。 @@ -1238,6 +1269,12 @@ antiAlias Sharp シャープ Channel チャンネル Character / Paragraph 文字/段落 Character Rotation 文字回転 + Chinese Big 5 中国語 Big 5 + Cyrillic キリル文字 + Greek ギリシャ語 + Turkish トルコ語 + Baltic バルト言語 + Central European 中央ヨーロッパ言語 Character Set: 文字セット: Character Style Options 文字スタイルオプション Check Links リンクを確認 @@ -1297,6 +1334,8 @@ antiAlias Sharp シャープ Choose a folder フォルダーを選択 Choose… 選択… Circle 円 + Circle Tool 円ツール + Circle too large 円が大きすぎます Clear All Tabs すべてのタブを消去 Above Text テキストの上 Position Panel Above Text テキストの上にパネルを配置 @@ -1338,6 +1377,7 @@ antiAlias Sharp シャープ Color Guide Options… カラーガイドオプション… Color Mode カラーモード Color Mode: カラーモード: + Color Model カラーモデル Color Model: カラーモデル: Color Models カラーモデル Color Picker カラーピッカー @@ -1356,6 +1396,7 @@ antiAlias Sharp シャープ Colors カラー Colors: カラー数: Column Graph Tool 集合縦棒グラフツール + Columns 列数 Columns: 列数: Coming soon — tracked in the parity plan 近日対応予定 Command Click to Select Objects Behind Command+クリックで背面のオブジェクトを選択 @@ -1479,6 +1520,8 @@ antiAlias Sharp シャープ Delete Artboard アートボードを削除 Delete Artboards アートボードを削除 Delete Brush ブラシを削除 + Delete Color カラーを削除 + Restore Generated Table 生成されたテーブルを復元 Delete Character Style 文字スタイルを削除 Delete Empty Artboards 空のアートボードを削除 Delete Freeform Point フリーフォームポイントを削除 @@ -1541,6 +1584,7 @@ antiAlias Sharp シャープ Dimensions 寸法 Direct Selection Tool ダイレクト選択ツール Disable Auto Add/Delete 自動追加/削除機能を使用しない + Interpolate Control Points When Moving Anchors アンカーポイントの移動時に方向線ハンドルを補間 Disable Opacity Mask 不透明マスクを無効にする Discard 破棄 Preserve 保持 @@ -1694,6 +1738,7 @@ antiAlias Sharp シャープ Enable Rubber Band for ラバーバンドを有効にする対象 Enable Touch Gestures タッチジェスチャーを有効にする Switch Selection and Drawing Modes 選択モードと描画モードを切り替え + Select Last Selection Tool 最後に使用した選択ツールに切り替え Enable Touch Workspace タッチワークスペースを有効にする Enable copying of text, images and other content テキスト、イメージ、その他のコンテンツのコピーを許可 Enable in-menu font previews メニュー内でフォントプレビューを有効にする @@ -1829,6 +1874,8 @@ antiAlias Sharp シャープ Files ファイル Files of a PDF standard can't be password-protected. PDF 規格のファイルにはパスワードを設定できません。 Files of this standard tag their colours with ICC profiles. この規格のファイルでは、カラーに ICC プロファイルが付けられます。 + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. この規格のファイルでは、カラーに ICC プロファイルが付けられます。ただし、出力インテントのプロファイルの CMYK カラーは DeviceCMYK として書き出されます。 + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. 「プロファイルを含めない」と CMYK の出力インテントでは、別のプロファイルの CMYK 変換先に変換されない限り、すべての CMYK カラーが DeviceCMYK として書き出されます。 Fill 塗り Fill New Type Objects With Placeholder Text 新規テキストオブジェクトをダミーテキストで埋める Start Lists From Typed Markers 入力した記号からリストを開始 @@ -2333,6 +2380,7 @@ antiAlias Sharp シャープ Load SVG into Clipboard SVG をクリップボードに読み込む Load Text into Clipboard テキストをクリップボードに読み込む Local Libraries ローカルライブラリ + Locate Layer レイヤーを検索 Locate Object オブジェクトを検索 Locate Selected Objects 選択したオブジェクトを検索 Location 場所 @@ -2454,6 +2502,7 @@ antiAlias Sharp シャープ Scatter: 散布: Rotation: 回転: Rotation relative to: 回転の基準: + Hue Jitter: 色相のばらつき: Brush Scale Options ブラシ伸縮オプション Scale Proportionately 縦横比を保持して拡大・縮小 Stretch to Fit Stroke Length ストロークの長さに合わせて伸縮 @@ -2490,6 +2539,7 @@ antiAlias Sharp シャープ Black becomes the stroke color and white stays white. Other colors become tints of the stroke color by their lightness. 黒は線のカラーになり、白は白のままです。その他のカラーは線のカラーの淡彩になり、明るいカラーほど明るい淡彩になります。 Black and white stay as they are. Dark colors become shades of the stroke color and light colors become tints of it. 黒は黒のまま、白は白のままです。その他のカラーは、暗い場合は線のカラーの陰影に、明るい場合は淡彩になります。 The key color becomes the stroke color. The other colors shift their hue by the same amount and keep their saturation and brightness. キーカラーが線のカラーになります。その他のカラーはキーカラーと同じだけカラーホイール上を移動し、彩度と明るさは保たれます。 + Roundness 真円率 Roundness: 真円率: Fixed 固定 Pressure 筆圧 @@ -2726,6 +2776,9 @@ antiAlias Sharp シャープ Overprint Stroke 線をオーバープリント Overprint and Transparency Flattener オーバープリントと透明の分割・統合 Overprint and Transparency Flattener Options オーバープリントと透明の分割・統合オプション + Custom… カスタム… + Custom Transparency Flattener Options カスタムの透明の分割・統合オプション + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS にはアルファ透明がなく、オーバープリントを保持するかどうかは「オーバープリント」で決まります。 Overprint: オーバープリント: Overprints: オーバープリント: Override Character Color 文字カラーを上書き @@ -2763,6 +2816,13 @@ antiAlias Sharp シャープ Pathfinders: パスファインダー: Paths パス Path Length パスの長さ + Grid Size グリッドのサイズ + Grid Colors グリッドのカラー + Flattener Preset 分割・統合プリセット + X X + Y Y + Orange オレンジ + Purple パープル Paths: {paths} Anchors: {anchors} Colors: {colors} パス:{paths} アンカー:{anchors} カラー:{colors} Pattern Editing パターン編集 Pattern options are available in pattern editing mode. パターンオプションはパターン編集モードで使用できます。 @@ -2800,6 +2860,7 @@ diagnostics ui UI Play Current Selection 選択項目を再生 Save Actions… アクションを保存… Load Actions… アクションを読み込み… + Replace Actions… アクションを置き換え… Reset Actions アクションをリセット Replace the current actions with the default set? 現在のアクションを初期設定のセットで置き換えますか? Append adds the default set after the current sets instead. 「追加」を選ぶと、初期設定のセットを現在のセットの後に追加します。 @@ -2812,6 +2873,10 @@ diagnostics ui UI Polar Grid Tool 同心円グリッドツール Polygon 多角形 Polygon Properties: 多角形のプロパティ: + Line Properties: 線のプロパティ: + Line Length: 線の長さ: + Line Angle: 線の角度: + Constrain Pie Angle 扇形の角度を固定 Polygon Tool 多角形ツール Portrait 縦置き Portuguese ポルトガル語 @@ -2913,6 +2978,9 @@ mark-style Japanese 日本式 Real World: 実寸: Real-time Drawing and Editing リアルタイム描画および編集 Use Monitor Profile for Canvas キャンバスにモニタープロファイルを使用 + Refresh Monitor Profile モニタープロファイルを更新 +@msg turn on Use Monitor Profile for Canvas first 先に「キャンバスにモニタープロファイルを使用」をオンにしてください +@msg this build doesn't read display profiles このビルドはディスプレイプロファイルを読み込みません The canvas is drawn in sRGB. キャンバスは sRGB で描画されます。 Canvas display profile: キャンバスのディスプレイプロファイル: The system matches the window to the display's colors. システムがウィンドウをディスプレイのカラーに合わせます。 @@ -3098,6 +3166,7 @@ mark-style Japanese 日本式 Reshape Segment セグメントをシェイプ変形 Reshape Tool リシェイプツール Reshape Type Area テキストエリアの形を変更 + Resolution 解像度 Resolution: 解像度: Responsive レスポンシブ Restore 復元 @@ -3125,6 +3194,7 @@ mark-style Japanese 日本式 The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Cmd/Ctrl キーを押しながらマウスホイールを回すとカンバスを横にスクロールします。 Dragging sideways on a numeric field's label changes the field's value. 数値フィールドのラベルを横にドラッグすると、フィールドの値が変わります。 A two-finger rotate gesture on a trackpad rotates the canvas view. トラックパッドで 2 本指の回転ジェスチャーをすると、カンバスの表示が回転します。 + When you move anchor points, each curve with one moved end keeps its shape relative to its ends. アンカーポイントを移動すると、一方の端が移動した各曲線は、両端に対する形状を保ちます。 Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. ツールのショートカットキーを押している間はそのツールを選び、離すと前のツールに戻ります。 Shows the bounding box while you move the selection or draw a shape. 選択範囲の移動中や図形の描画中にバウンディングボックスを表示します。 Create Trim Marks draws Japanese-style marks instead of Roman ones. トリムマークを作成で、西洋式ではなく日本式のトンボを描きます。 @@ -3155,6 +3225,29 @@ mark-style Japanese 日本式 The unit for East Asian type measurements, which no field uses yet. 東アジア言語の文字の測定に使う単位で、まだどのフィールドも使っていません。 When on, a number typed without a unit into a field in picas is read in points. オンのとき、パイカのフィールドに単位なしで入力した数値はポイントとして読み取られます。 With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options. XML ID を選ぶと、レイヤー、変数、レイヤーオプションでオブジェクト名が XML ID として表示されます。 + The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl. 文字サイズと行送りの増減値です。Cmd/Ctrl+Shift+. と Cmd/Ctrl+Shift+, で文字サイズを 1 段階、Alt も押すと 5 段階変えます。横組みの文字では Alt と上下の矢印キーで行送りを 1 段階、Cmd/Ctrl も押すと 5 段階変えます。 + The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl. トラッキングとカーニングの増減値で、単位は 1/1000 em です。横組みの文字では Alt と左右の矢印キーで、キャレット位置のカーニングまたは選択したテキストのトラッキングを 1 段階、Cmd/Ctrl も押すと 5 段階変えます。 + The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. ベースラインシフトの増減値です。横組みの文字では Alt と Shift と上下の矢印キーでベースラインを 1 段階、Cmd/Ctrl も押すと 5 段階移動します。 + Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. 文字、段落、OpenType、字形の各パネルに日本語などの東アジアの文字のオプションを表示し、合成フォントのコマンドも表示します。 + Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. 文字パネルと段落パネルに、段落の方向、カシーダ、数字など、アラビア語、ヘブライ語、インド系文字のオプションを表示します。 + The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. 選択ツールは文字をベースライン、エリア内文字の枠、またはパス上でのみ選択し、ボックス内の任意の場所では選択しません。 + Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. フォントメニューに各フォントを英語名で表示します。オフにすると、自国語の名前も持つフォントはその名前で表示されます。 + New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. 新しいエリア内文字は自動サイズ調整がオンの状態で作成され、横組みの長方形の枠は文字に合わせて高さが伸び縮みします。 + Font lists and the Type › Font menu show a sample of each font beside its name. フォントリストとフォントメニューに、各フォントの名前の横にそのフォントのサンプルを表示します。 + Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on. フォントのサンプルを、インターフェイスの明るさにかかわらず白地に濃い色の文字で描きます。メニュー内のフォントプレビューがオンのときだけ有効です。 + How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is. 文字パネルなどのフォント欄のリストで各行をどれだけ高くするか、つまり各サンプルの大きさです。 + How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first. 最近使用したフォントとフォントリストに、最後に使ったフォントを新しい順にいくつ表示するかです (1~15)。 + When you change the font or font style of text, characters the new font has no glyph for keep the font they had. 文字のフォントまたはフォントスタイルを変えたとき、新しいフォントに字形がない文字は元のフォントのままになります。 + A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export. OpenType 機能で置き換えられた合字などの字形を、カンバス上でピンクのハイライトで示します。プリントや書き出しには含まれません。 + With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from. 文字ツールで 1 文字を選択すると、カンバス上のその横に、選べる異体字の列が表示されます。 + A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export. フォントが見つからず代替フォントで描かれた文字を、カンバス上でピンクのハイライトで示します。プリントや書き出しには含まれません。 + New type made with a Type tool starts with placeholder text, selected, so typing replaces it. 文字ツールで作成した新しい文字は、選択されたサンプルテキストで始まり、入力するとそれが置き換わります。 + Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list. 段落の先頭で 1. や * などのリスト記号とスペースを入力すると、その段落がリストになります。 + Fonts in this folder show in the font menus and can be used without being installed. このフォルダーのフォントはフォントメニューに表示され、インストールせずに使えます。 + Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows. 文字にグラフィックスタイルを適用すると、スタイルに塗りや線があればその文字自体の塗りや線が取り除かれ、スタイルのペイントが見えるようになります。 + Align and Distribute measure point type by the ink of its glyphs instead of its em box. 整列と分布は、ポイント文字を仮想ボディではなく字形のインクで測ります。 + Align and Distribute measure area type by the ink of its glyphs instead of its frame. 整列と分布は、エリア内文字を枠ではなく字形のインクで測ります。 + The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box. バウンディングボックスと変形パネルは、ポイント文字を仮想ボディではなく字形のインクで測ります。 Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply. グリッドが非表示でも、描画、移動、拡大・縮小をグリッドの分割位置にスナップします。オンの間は「ピクセルにスナップ」は働きません。 The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead. 選択されていないガイドの色です。ガイドのラベルを設定したアートボードは、自身のガイドをラベルの色で描きます。 Draws guides as solid lines or as dots, including the guides already in the document. ドキュメントにすでにあるガイドも含め、ガイドを実線または点線で描きます。 @@ -3217,6 +3310,7 @@ mark-style Japanese 日本式 Rounded Rectangle 角丸長方形 Rounded Rectangle Tool 角丸長方形ツール Row Size: 行のサイズ: + Rows 行数 Rows: 行数: Rule: ルール: Rulers & Grids 定規とグリッド @@ -3313,6 +3407,9 @@ mark-style Japanese 日本式 Search commands, tools, panels and effects… コマンド、ツール、パネル、効果を検索… No commands match 一致するコマンドはありません {pos} of {total}: {name} {total} 件中 {pos} 件目: {name} + No menu item メニュー項目なし + Toolbar ツールバー + {toolbar}, in the {tool} group {toolbar}、{tool} のグループ内 @plural {n} result|{n} results {n} 件 @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {n} 件中 {shown} 件。続けて入力すると絞り込めます。 Recent Commands 最近使ったコマンド @@ -3370,6 +3467,7 @@ mark-style Japanese 日本式 Set Text テキストを設定 Set Zoom ズーム率を設定 Set base color to the current color 基本カラーを現在のカラーに設定 + Set the current fill or stroke to the selected color 現在の塗りまたは線を選択したカラーに設定 Set the selected color to the current color 選択したカラーを現在のカラーに設定 Setup… 設定… Shape Builder シェイプ形成ツール @@ -3428,7 +3526,7 @@ mark-style Japanese 日本式 Show all plates すべての版を表示 Show handles when multiple anchors are selected 複数のアンカーを選択したときにハンドルを表示 Show {kind} Brushes {kind}ブラシを表示 - Show/hide plate (Alt-click: only this plate) 版の表示/非表示 (Alt+クリック: この版のみ) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) 版の表示/非表示 (Alt+クリック: この版のみ、もう一度 Alt+クリック: すべての版) Show: 表示: Shown with the optimised preview. 最適化プレビューで表示されます。 Side 1: 辺 1: @@ -3783,6 +3881,8 @@ mark-style Japanese 日本式 User Swatch Library 9 ユーザースウォッチライブラリ 9 V Spacing: 垂直方向の間隔: Variable Width Profile 可変幅プロファイル + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. 線のブラシは独自のサイズを保つため、幅プロファイルでは変わりません。プロファイルを使うにはブラシを削除してください。 +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. 線のブラシは独自のサイズを保つため、幅プロファイルでは変わりません。プロファイルを使うにはブラシを削除してください。 Variation: バリエーション: Vector Halftone ベクトルハーフトーン Vector illustration — fast, open, scriptable. ベクターイラスト — 高速・オープン・スクリプト対応 @@ -3796,7 +3896,7 @@ mark-style Japanese 日本式 Vertical Type Tool 縦書き文字ツール Vertical Type on a Path Tool 縦書きパス上文字ツール Vertical: 垂直方向: - View Artboard Only アートボードのみ表示 + View Artboard Contents Only アートボードの内容のみ表示 View Opacity Mask 不透明マスクを表示 View PDF after saving 保存後に PDF を表示 Viewing Angle: 視角: @@ -4277,7 +4377,7 @@ file-filter Templates テンプレート Composite Fonts 合成フォント Export Composite Fonts 合成フォントを書き出し Import Composite Fonts 合成フォントを読み込み -@msg each font must be {name, parts} 各フォントは {name, parts} の形にしてください +@msg each font must be {{name, parts}} 各フォントは {{name, parts}} の形にしてください @msg unknown key `{k}`; a font takes name and parts `{k}` は不明なキーです。フォントに使えるのは name と parts です @msg each font needs a name 各フォントには名前が必要です @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` は合成フォントの名前にできません (1~{COMPOSITE_NAME_MAX} 文字、制御文字なし) @@ -4290,7 +4390,7 @@ file-filter Templates テンプレート @msg two composite fonts are named `{_1}` `{_1}` という名前の合成フォントが 2 つあります @msg `{_1}` is the name of an installed font `{_1}` はインストール済みのフォントの名前です @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2} に合成フォントの `{font}` が設定されています -@msg give fonts: [{name, parts}…] fonts を指定してください: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] fonts を指定してください: [{{name, parts}}…] @msg path is empty path が空です @msg fonts must be a list of composite fonts fonts は合成フォントのリストにしてください @msg names must be strings names は文字列にしてください @@ -4463,6 +4563,7 @@ imageTrace Outline アウトライン Bevel ベベル Offset オフセット Axis 軸 + Axis Angle 軸の角度 axis Horizontal 水平方向 axis Vertical 垂直方向 axis Both 両方 @@ -4516,7 +4617,7 @@ theme Appearance 外観 Free Transform 自由変形 Perspective Distort 遠近変形 -# Photoshop-style raster effects (Effect menu, their dialogs). +# Raster effects (Effect menu, their dialogs). Radial Blur… ぼかし (放射状)… Blur Center ぼかしの中心 Smart Blur… ぼかし (詳細)… @@ -4680,6 +4781,7 @@ swatch Bright Violet ビビッドバイオレット @msg Live Paint: select paths or compound paths ライブペイント: パスまたは複合パスを選択してください @msg Live Paint: these paths are too degenerate to paint ライブペイント: これらのパスは形状がつぶれすぎていてペイントできません @msg Shape Builder: no region under the pointer シェイプ形成ツール: ポインターの下に領域がありません +@msg Shape Builder: select all paths you want to merge シェイプ形成ツール: 結合するパスをすべて選択してください @msg Shape Builder: select paths or compound paths シェイプ形成ツール: パスまたは複合パスを選択してください @msg image data `{_1}` is missing 画像データ `{_1}` が見つかりません @msg no Live Paint edge near that point その位置の近くにライブペイントのエッジがありません @@ -4715,6 +4817,13 @@ swatch Bright Violet ビビッドバイオレット @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} データセットが {MAX_CSV_ROWS} 個を超えています: 「データセットを読み込み」が読み込めるのは {MAX_CSV_ROWS} 個までです @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} 変数が {MAX_CSV_COLS} 個を超えています: 「データセットを読み込み」が読み込めるのは {MAX_CSV_COLS} 個までです @msg variables that aren't text were left out: {kinds} テキスト以外の変数は除外されました: {kinds} +variable-kind Visibility 表示状態 +variable-kind Linked File リンクファイル +variable-kind Graph Data グラフデータ +variable-kind Unknown 不明 +variable-list-two {0}, {1} {0}、{1} +variable-list-middle {0}, {1} {0}、{1} +variable-list-end {0}, {1} {0}、{1} @msg a new document won't read these variables back with their kind: {names} 新しいドキュメントでは、これらの変数は元の種類で読み込まれません: {names} @msg a new document refuses this file because of these variables: {names} 新しいドキュメントは、これらの変数のためにこのファイルを拒否します: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them `{name}` の見出し `{header}` は変数 `{other}` として読み込まれます: どちらかの名前を変更してください @@ -4747,6 +4856,7 @@ swatch Bright Violet ビビッドバイオレット @msg Expand: no gradient fills 拡張: グラデーションの塗りがありません @msg Expand: nothing to expand 拡張: 拡張するものがありません @msg batch step {_1} (`{id}`) failed: {e} バッチのステップ {_1} (`{id}`) が失敗しました: {e} +@msg action step {_1} (`{id}`) failed: {reason} アクションのステップ {_1} (`{id}`) が失敗しました: {reason} @msg BMP files are RGB or grayscale: colorModel rgb or gray BMP ファイルが対応するのは RGB とグレースケールのみです: colorModel には rgb または gray を指定してください @msg Targa files are RGB: colorModel rgb Targa ファイルが対応するのは RGB のみです: colorModel には rgb を指定してください @msg antiAlias `{id}`: none, art or type antiAlias に `{id}` は指定できません: none、art、type のいずれかを指定してください @@ -4843,8 +4953,8 @@ swatch Bright Violet ビビッドバイオレット @msg image would be too large; lower the resolution 画像が大きくなりすぎるため、解像度を下げてください @msg clipboard is empty クリップボードが空です @msg no anchor points selected アンカーポイントが選択されていません -@msg `points` must be three [x, y] pairs of numbers `points` は 3 組の数値 [x, y] にしてください -@msg direct-select three anchor points, or give `points` アンカーポイントを 3 つダイレクト選択するか、`points` を指定してください +@msg `points` must be two or three [x, y] pairs of numbers `points` は 2 組または 3 組の数値 [x, y] にしてください +@msg direct-select two or three anchor points, or give `points` アンカーポイントを 2 つまたは 3 つダイレクト選択するか、`points` を指定してください @msg no circle passes through these points: two are the same or all three lie on one line これらの点を通る円はありません: 2 つの点が同じか、3 点すべてが一直線上にあります @msg select at least two objects オブジェクトを 2 つ以上選択してください @msg exit isolation mode first 先に分離モードを終了してください @@ -4886,6 +4996,8 @@ swatch Bright Violet ビビッドバイオレット @msg {label}: lost track of a shape's style {label}: シェイプのスタイル情報が失われました @msg {label}: select paths {label}: パスを選択してください @msg {label}: select paths, compound paths, groups or text {label}: パス、複合パス、グループ、テキストのいずれかを選択してください +@msg a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first 領域を囲まない直線などのオープンパスは、結果の形を変えません。含めるには、先にそのパスに「オブジェクト › パス › パスのアウトライン」を適用してください +@msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first {label} の結果が空になりました。領域を囲まない直線などのオープンパスがあります。含めるには、先にそのパスに「オブジェクト › パス › パスのアウトライン」を適用してください @msg already editing a pattern すでにパターンを編集中です @msg no pattern `{name}` パターン `{name}` が見つかりません @msg not in pattern editing mode パターン編集モードではありません @@ -4967,6 +5079,7 @@ swatch Bright Violet ビビッドバイオレット @msg Create Outlines: select text objects アウトラインを作成: テキストオブジェクトを選択してください @msg paste unavailable 貼り付けを使用できません @msg Save for Web: the image is empty Web 用に保存: 画像が空です +@msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: カラーテーブルには少なくとも 1 つのカラーを残す必要があります @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` は「#ff8800」のような形式のカラーではありません @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: 指定できるカラーは {MAX_TABLE} 色までです @msg no artboard {i} (0-based; the document has {_1}) アートボード {i} はありません (番号は 0 始まり、このドキュメントには {_1} 個あります) @@ -5214,6 +5327,12 @@ swatch Bright Violet ビビッドバイオレット @msg no preset editor プリセットの編集ダイアログが開いていません @msg no perspective grid preset named `{name}` `{name}` という名前の遠近グリッドプリセットが見つかりません @msg no active perspective plane アクティブな遠近面がありません +@msg the perspective grid is hidden 遠近グリッドが非表示になっています +@msg Automatic Plane Positioning is off: turn on anchorPoint or gridlineIntersection (perspective.widget.options) 遠近面の自動配置がオフになっています: anchorPoint または gridlineIntersection をオンにしてください (perspective.widget.options) +@msg anchorPoint must be true or false anchorPoint には true または false を指定してください +@msg gridlineIntersection must be true or false gridlineIntersection には true または false を指定してください +@msg tolerance must be 0 or more tolerance には 0 以上の値を指定してください +@msg give `at` or `clear`, not both `at` または `clear` のどちらか一方を指定してください @msg plane must be left, right or ground plane には left、right、ground のいずれかを指定してください @msg missing `id` (see plugin.list) `id` が指定されていません (plugin.list を参照) @msg no plug-in {id} is installed プラグイン {id} はインストールされていません @@ -5264,6 +5383,9 @@ swatch Bright Violet ビビッドバイオレット @msg `{color}` is not a colour (#rrggbb or a preset name) `{color}` はカラーではありません (#rrggbb またはプリセット名で指定してください) @msg give the path `id` and the width point `index` パスの `id` と幅ポイントの `index` を指定してください @msg no such width point 指定された幅ポイントが見つかりません +@msg `single` must be `incoming` or `outgoing` `single` は `incoming` または `outgoing` にしてください +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` と `outIndex` は 1 つの不連続な幅ポイントの 2 つの半分である必要があります +@msg a discontinuous width point keeps its place 不連続な幅ポイントの位置は変わりません @msg onto must name a panel floating in another group onto には、別のグループでフローティングしているパネルを指定してください @msg below and above must name a panel floating in another group below と above には別のグループでフローティングしているパネルを指定してください @msg give only one of onto, below and above onto、below、above のうち 1 つだけを指定してください @@ -5293,6 +5415,8 @@ swatch Bright Violet ビビッドバイオレット @msg No saved views (View → New View…) 保存した表示はありません (表示 → 新規表示…) @msg `command` must be a command whose menu item opens a dialog (see ui.menuDialog) `command` には、メニュー項目がダイアログを開くコマンドを指定してください (ui.menuDialog を参照) @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` には grayscale、rgb、hsb、cmyk、websafe のいずれかを指定してください +@msg `view` must be wheel or box `view` には wheel、box のいずれかを指定してください +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` には hue、saturation、brightness、red、green、blue のいずれかを指定してください @msg `{key}` must be true or false `{key}` には true または false を指定してください @msg `top` and `below` can't both be true `top` と `below` を同時に true にすることはできません @msg `select` must be true or false `select` には true または false を指定してください @@ -5374,6 +5498,13 @@ swatch Bright Violet ビビッドバイオレット Show External Script Warning 外部スクリプトの警告を表示 A Script Is Running スクリプトの実行中 Script Alert スクリプトの通知 + Script File Access スクリプトのファイルアクセス + The script asks to read a file you choose. スクリプトが、選択したファイルの読み取りを求めています。 + The script asks to read and write a file you choose. スクリプトが、選択したファイルの読み書きを求めています。 + The script asks to read and write a folder you choose, with everything in it. スクリプトが、選択したフォルダーとその中身すべての読み書きを求めています。 + Allow Once 今回のみ許可 + Always Allow This Script このスクリプトを常に許可 + Deny 拒否 A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. スクリプトは開いているドキュメントを変更でき、実行するコマンドを通じてファイルを書き込むこともできます。信頼できるスクリプトだけを実行してください。 Do not show this warning again 今後この警告を表示しない Stop the script and undo what it did? Then quit again. スクリプトを停止して変更を取り消しますか?その後、もう一度終了してください。 @@ -5390,6 +5521,8 @@ swatch Bright Violet ビビッドバイオレット @msg the script is no longer in the Scripts folder スクリプトは Scripts フォルダーにもうありません Some scripts were not listed 一部のスクリプトは一覧に表示されていません The Scripts folder cannot be read Scripts フォルダーを読み込めません + Loading scripts… スクリプトを読み込み中… + The Scripts folder is still being read Scripts フォルダーをまだ読み込んでいます @msg the script's run is no longer available スクリプトの実行は利用できなくなりました @msg a failed command changed undo steps that could not be put back, so the script was stopped 失敗したコマンドが元に戻せない取り消し手順を変更したため、スクリプトを停止しました @msg a recovery copy could not be written, so the script was not run 復元用のコピーを書き込めなかったため、スクリプトは実行されませんでした @@ -5402,8 +5535,6 @@ swatch Bright Violet ビビッドバイオレット @msg Script file could not be read スクリプトファイルを読み込めませんでした @msg Script folder has more than 2,048 entries スクリプトフォルダーの項目が 2,048 を超えています @msg Script file open mode must be r, w, e or a スクリプトファイルを開くモードは r、w、e、a のいずれかにしてください -@msg Script file writing is not available スクリプトファイルの書き込みは利用できません -@msg Script file dialogs are not available スクリプトファイルのダイアログは利用できません @msg Script files cannot be opened in another application スクリプトファイルを別のアプリケーションで開くことはできません @msg Script file access is unavailable on the web Web ではスクリプトファイルにアクセスできません @msg Script has 256 files open スクリプトが 256 個のファイルを開いています @@ -5519,8 +5650,37 @@ liquify-list-end {0}, {1} {0}、{1} @msg the main script engine is new for each run and is never kept, so it cannot be dropped メインのスクリプトエンジンは実行ごとに新しく作られ、保持されないため、破棄できません @msg there is no script engine named {name} {name} という名前のスクリプトエンジンはありません @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` は尋ねる相手がいない実行専用です。アプリでは、各ダイアログに本人が回答します +@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` には 1 から {_1} までの整数を指定してください +@msg `args{place}` is nested more than 64 levels deep `args{place}` の入れ子が 64 階層を超えています +@msg `args` must be an object `args` はオブジェクトである必要があります +@msg `args` is larger than 1 MiB `args` が 1 MiB を超えています +@msg `path` is empty `path` が空です +@msg `installed` takes a `path`, not a `source` `installed` には `source` ではなく `path` を指定してください +@msg `path` must name a .js or .jsx file `path` には .js または .jsx ファイルを指定してください +@msg give exactly one of `path` and `source` `path` と `source` のうち 1 つだけを指定してください @msg Running a script スクリプトを実行中 @msg Copied the script report スクリプトのレポートをコピーしました +@msg Script file access denied: {path} スクリプトのファイルアクセスが拒否されました: {path} +@msg Script file access to the app's own folders is not allowed スクリプトからアプリ自身のフォルダーへのアクセスは許可されていません +@msg Script file cannot encode the text スクリプトのファイルでテキストをエンコードできません +@msg Script file could not be written スクリプトのファイルを書き込めませんでした +@msg Script file dialogs need a person to answer them スクリプトのファイルダイアログには応答する人が必要です +@msg Script file is not open for writing スクリプトのファイルが書き込み用に開かれていません +@msg Script file name is already in use スクリプトのファイル名はすでに使用されています +@msg Script file name must be a name without a folder スクリプトのファイル名はフォルダーを含まない名前にしてください +@msg Script file permission can be kept only for a script run from a file ファイルの許可を保持できるのは、ファイルから実行したスクリプトだけです +@msg Script file permission could not be saved スクリプトのファイルの許可を保存できませんでした +@msg Script folder is not empty スクリプトのフォルダーが空ではありません +@msg Script files cannot make aliases スクリプトのファイルではエイリアスを作成できません +@msg Script file hidden setting cannot be changed スクリプトのファイルの非表示設定は変更できません +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: 組み込み関数、ゲッター、変換、または $.evalFile が実行するファイルのコールバック内ではファイルダイアログを開けません。スクリプト自身のコードから呼び出してください +@msg the script wrote more file data than one run may write (32 MiB) スクリプトが 1 回の実行で書き込める量を超えるファイルデータを書き込みました (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop スクリプトのファイルダイアログの `answer` は once、always、deny、stop のいずれかにしてください +@msg choose a file or folder first, or deny 先にファイルまたはフォルダーを選択するか、拒否してください +@msg the script file permissions could not be saved: {e} スクリプトのファイル許可を保存できませんでした: {e} +@msg this script's file access can be allowed only once このスクリプトのファイルアクセスは 1 回だけ許可できます +@msg Only the person at the keyboard can allow a script's file access スクリプトのファイルアクセスを許可できるのはキーボードの前にいる人だけです +@msg A script is given at most 2,048 files: the files picked after them were left out スクリプトに渡せるファイルは 2,048 個までのため、それ以降に選んだファイルは除外されました @msg Copied the link info リンク情報をコピーしました @msg Exported {path} {path} を書き出しました @msg no CSS to copy: select objects with CSS of their own コピーする CSS がありません: 独自の CSS を持つオブジェクトを選択してください @@ -5557,6 +5717,8 @@ liquify-list-end {0}, {1} {0}、{1} @msg All colors are within the CMYK gamut すべてのカラーが CMYK の色域内です @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} 個のカラーが CMYK の色域外です @msg Unembedded to {_1} 埋め込みを解除して {_1} に保存しました +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} {n} 枚の画像の埋め込みを解除して {folder} に保存しました +@msg every numbered name for {name} is taken in that folder そのフォルダーでは、{name} の番号付きの名前がすべて使われています @msg no swatch library `{l}` (see swatch.library.list) スウォッチライブラリ `{l}` が見つかりません (swatch.library.list を参照) @msg no user library folder here この環境にはユーザーライブラリフォルダーがありません @msg Couldn't place {name}: the document it was dropped on was closed {name} を配置できませんでした: ドロップ先のドキュメントは閉じられています @@ -5582,6 +5744,9 @@ liquify-list-end {0}, {1} {0}、{1} @msgplural Discarded {n} recovered document|Discarded {n} recovered documents 復帰用データのドキュメントを {n} 件破棄しました @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them 復帰用データからドキュメントを {n} 件復元しました: 残すには保存してください @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} ドキュメントを開きました (注意 {n} 件): {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} コピーしましたが、注意事項が {n} 件あります: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} 切り取りましたが、注意事項が {n} 件あります: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} 画像をトレースしましたが、注意事項が {n} 件あります: {first} @msgplural {notice}. Opened with {n} note: {first}|{notice}. Opened with {n} notes: {first} {notice}。ドキュメントを開きました (注意 {n} 件): {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} {path} を保存しましたが、注意事項が {n} 件あります: {first} @msg Saving recovery data for {_1} {_1} の復帰用データを保存中 @@ -5610,6 +5775,8 @@ liquify-list-end {0}, {1} {0}、{1} @msg the {tool} tool has no options {tool} ツールにはオプションがありません @msg unknown tool `{tool}` `{tool}` は不明なツールです @msg {tool} isn't in a toolbar group of several tools {tool} は複数のツールからなるツールグループに含まれていません +@msg Presentation Mode hides the toolbars: change the screen mode to show them プレゼンテーションモードではツールバーが表示されません: 表示するにはスクリーンモードを変更してください +@msg Tab has hidden the toolbars: press Tab to show them Tab でツールバーが非表示になっています: 表示するには Tab キーを押してください @msg no such document 指定されたドキュメントが見つかりません @msg {_1}: not saved, so not closed {_1}: 保存されていないため、閉じませんでした @msg `{name}` is a built-in workspace; choose another name `{name}` は組み込みのワークスペースなので、別の名前を指定してください @@ -5659,6 +5826,9 @@ liquify-list-end {0}, {1} {0}、{1} @msg automation path rejected: outside the read root {root}: {path} 自動化のパスを拒否しました: 読み込みルート {root} の外です: {path} @msg automation path rejected: outside the read roots {roots}: {path} 自動化のパスを拒否しました: 読み込みルート {roots} のいずれの中でもありません: {path} @msg a linked JavaScript file is outside the read roots リンクされた JavaScript ファイルが読み込みルートの外にあります +@msg a linked image file is outside the read roots リンクされた画像ファイルが読み込みルートの外にあります +@msg a linked file's export folder is outside the read roots リンクされたファイルの書き出しフォルダーが読み込みルートの外にあります +@msg a linked file's editing data can't be read to check it against the read roots リンクされたファイルの編集データを読み込めないため、読み込みルートと照合できません @msg automation path rejected: outside the write root {root}: {path} 自動化のパスを拒否しました: 書き込みルート {root} の外です: {path} @msg automation path rejected: outside the write roots {roots}: {path} 自動化のパスを拒否しました: 書き込みルート {roots} のいずれの中でもありません: {path} @msg automation path rejected: path is empty 自動化のパスを拒否しました: パスが空です @@ -5889,6 +6059,7 @@ lighting Light ライト @msg missing panel layout パネル配置がありません @msg unsupported native docking operation ネイティブドッキング操作は未対応です Linux Display Server Linux ディスプレイサーバー + Low-Latency Drawing 低遅延描画 X11 (XWayland) When a Pen Is Attached ペン接続時は X11 (XWayland) If a drawing tablet's pen doesn't draw, choose an X11 (XWayland) option. ペンタブレットのペンで描画できない場合は、X11 (XWayland) のいずれかを選択してください。 X11 (XWayland) X11 (XWayland) @@ -5943,6 +6114,7 @@ lighting Light ライト Cove 凹面 Depth 奥行き Front 正面 + Side 側面 Isometric Bottom 等角図(底面) Isometric Left 等角図(左) Isometric Right 等角図(右) @@ -6037,7 +6209,7 @@ lighting Light ライト @msg each of `{GRAPHICS}` must be an object `{GRAPHICS}` の各項目はオブジェクトにしてください @msg `{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}` `{GRAPHICS}` の項目に指定できるのは symbol、face、x、y、scale、rotation で、`{k}` は指定できません @msg each of `{GRAPHICS}` needs `symbol`, the name of a symbol `{GRAPHICS}` の各項目にはシンボルの名前 `symbol` が必要です -@msg `{GRAPHICS}` face must be front or back `{GRAPHICS}` の face には front または back を指定してください +@msg `{GRAPHICS}` face must be front, back or side `{GRAPHICS}` の face には front、back、side のいずれかを指定してください @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} `{GRAPHICS}` の {key} は {lo} から {hi} までの数値にしてください @msg `{GRAPHICS}` must be an array `{GRAPHICS}` は配列にしてください @msg Graphics map onto the Plane, Extrude and Revolve object types グラフィックはオブジェクトの種類が平面、押し出し、回転体のときにマッピングされます @@ -6799,7 +6971,7 @@ axis Y Axis Y 軸 @msg `rows` must be lists of numbers or nulls, not {r} `rows` には数値または null のリストを指定してください ({r} は指定できません) @msg `scale` must be a number from 0.001 to 1000 `scale` には 0.001 から 1000 までの数値を指定してください @msg `scope.{key}` must be a non-empty array `scope.{key}` には空でない配列を指定してください -@msg `scope` must be "document", {artboards} or {layers} `scope` には "document"、{artboards}、{layers} のいずれかを指定してください +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` には "document"、{{artboards: [index, …]}}、{{layers: [id, …]}} のいずれかを指定してください @msg `side` must be "left", "right", "top" or "bottom" `side` には "left"、"right"、"top"、"bottom" のいずれかを指定してください @msg `side` places the artboard: leave out x, y, width and height `side` でアートボードを配置します: x、y、width、height は省略してください @msg `source` is the only path in series group `target` `source` は系列グループ `target` の唯一のパスです @@ -6984,7 +7156,7 @@ axis Y Axis Y 軸 @msg not a regular expression 正規表現ではありません @msg not an action set: the text doesn't start with /version and a number アクションセットではありません: テキストが /version と数値で始まっていません @msg nothing to repeat 繰り返す対象がありません -@msg numbers out of order in {_1} quantifier {_1} 量指定子の数値の順序が正しくありません +@msg numbers out of order in {{}} quantifier {{}} 量指定子の数値の順序が正しくありません @msg object {_1} needs a 3D effect オブジェクト {_1} には 3D 効果が必要です @msg object {_1}: a hollow Extrude & Bevel has no caps: turn on Cap to map a graphic オブジェクト {_1}: 中空の「押し出しとベベル」にはキャップがありません: グラフィックをマッピングするには「キャップ」をオンにしてください @msg object {_1}: with a depth of 0 the object has one face: map its graphics onto the front オブジェクト {_1}: 奥行きが 0 のオブジェクトは面が 1 つです: グラフィックは前面にマッピングしてください @@ -7053,7 +7225,7 @@ axis Y Axis Y 軸 @msg the library's file is outside the read roots ライブラリのファイルが読み取りルートの外にあります @msg the line is too long, or the paths it passes too many, to check 線が長すぎるか、通過するパスが多すぎるため、確認できません @msg the method needs an XML value このメソッドには XML の値が必要です -@msg the paint is not a freeform gradient (apply one with paint.editGradient {kind}) ペイントがフリーフォームグラデーションではありません (paint.editGradient {kind} で適用してください) +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) ペイントがフリーフォームグラデーションではありません (paint.editGradient {{kind: "freeform"}} で適用してください) @msg the parameters or body do not form one function パラメーターまたは本体が 1 つの関数になっていません @msg the pasted SVG filter {name} draws differently from the document's filter of that name, and no free name fits it ペーストした SVG フィルター {name} は、ドキュメントにある同名のフィルターと描画結果が異なり、使用できる空き名もありません @msg the paths are too many or too tangled to find where they cross パスが多すぎるか複雑に絡み合っているため、交差する位置を見つけられません @@ -7340,6 +7512,8 @@ axis Y Axis Y 軸 @msg `{f}` is the copy of a document open now `{f}` は現在開いているドキュメントのコピーです @msg `{id}` is no writable format (see document.formats) `{id}` は書き出せる形式ではありません (document.formats を参照) @msg `{id}` isn't a loaded library `{id}` は読み込まれているライブラリではありません +@msg `{file}` has no swatches of its own `{file}` には独自のスウォッチがありません +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` にはパターンスウォッチがあり、.vcswatches ファイルには保存できません @msg `{key}` has no colours `{key}` にカラーがありません @msg `{key}` is a design name `{key}` にはデザイン名を指定してください @msg `{key}` is a design name or a list of them `{key}` にはデザイン名またはそのリストを指定してください @@ -7562,7 +7736,13 @@ axis Y Axis Y 軸 @msg colorModel must be {own} (the document's mode), grayscale or bitmap colorModel には {own} (ドキュメントのモード)、grayscale、bitmap のいずれかを指定してください @msg colour groups can't go into colour groups カラーグループをカラーグループに入れることはできません @msg colour, mode and spot apply to solid-colour swatches only colour、mode、spot を適用できるのは単色のスウォッチだけです -@msg column {column}: `{cell}` is a `%` column of graph data files, which are not read 列 {column}: `{cell}` はグラフデータファイルの `%` 列で、読み込まれません +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path {line} 行目、列 {column}: `{var}` のグラフデータファイル `{path}` は相対パスです: `base` か絶対パスを指定してください +@msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} {line} 行目、列 {column}: `{var}` のグラフデータファイルを読み込めません: {e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` isn't followed: {r} {line} 行目、列 {column}: `{var}` のグラフデータファイル `{path}` は参照しません: {r} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes {line} 行目、列 {column}: `{var}` のグラフデータファイル `{path}` が {MAX_GRAPH_DATA_FILE} バイトを超えています +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes {line} 行目、列 {column}: `{var}` のグラフデータファイル `{path}` から得られるグラフの値が {MAX_GRAPH_CSV} バイトを超えています +@msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all {line} 行目、列 {column}: グラフデータファイルが合計で {MAX_GRAPH_FILES_TOTAL} バイトを超えています +@msg `base` is empty `base` が空です @msg column {column}: `{cell}` names `{name}`, which is a {_1} variable 列 {column}: `{cell}` が指定している `{name}` は {_1} 変数です @msg column {column}: `{cell}` names no variable 列 {column}: `{cell}` に該当する変数はありません @msg column {column}: the variable name is longer than {MAX_NAME} characters 列 {column}: 変数名が {MAX_NAME} 文字を超えています @@ -7574,6 +7754,7 @@ axis Y Axis Y 軸 @msg compound {_1} must contain exactly one open path to join 連結するには、複合パス {_1} にオープンパスがちょうど 1 つ含まれている必要があります @msg connect end must be "start" or "end" connect の end には "start" または "end" を指定してください @msg connect needs a path other than the one extended connect には、延長したパスとは別のパスが必要です +@msg connect needs extend connect には extend が必要です @msg connect needs id connect には id が必要です @msg connect path has no open end connect のパスに開いた端点がありません @msg copy needs path: the file to copy into the document's folder copy には path が必要です: ドキュメントのフォルダーにコピーするファイルを指定してください @@ -8883,6 +9064,12 @@ anchor Points: ポイント: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` には "free"、"keepAngles" または "symmetric" を指定してください @msg `{key}` must be [x, y] `{key}` には [x, y] を指定してください +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter 単位換算 + Unit Converter Panel 単位換算パネル + Copy with Units 単位付きでコピー + From Selection 選択範囲から + # Color Effects add-on: Select by Color Kind. Select by Color Kind カラーの種類で選択 Objects with Spot Colors 特色を使用したオブジェクト @@ -9108,6 +9295,14 @@ breakText Glyphs 字形 Remove Gaps 間隔を削除 @msg that makes too many pieces (at most 100000): make the dashes longer 分割数が多すぎます(最大 100000):ダッシュを長くしてください @msg select paths, or segments, to divide 分割するパスまたはセグメントを選択してください +# Path Precision Tools add-on: Smooth Bridge. + Smooth Bridge… スムーズブリッジ… + Smooth Bridge スムーズブリッジ + Keep Originals オリジナルを保持 +@msg select two circles to bridge ブリッジでつなぐ円を 2 つ選択してください +@msg one circle is inside the other 一方の円がもう一方の円の内側にあります +@msg the circles are too far apart for this radius: raise the radius この半径では円が離れすぎています:半径を大きくしてください +@msg the circles are too far apart for this radius この半径では円が離れすぎています # Path Precision Tools add-on: Common Tangents. Common Tangents… 共通接線… Common Tangents 共通接線 @@ -9617,3 +9812,13 @@ breakText Glyphs 字形 @msg A panel is not joined to the rest by a crease. パネルがどの筋入れ線でも他とつながっていません。 @msg A fold line is on a non-printing layer. 折り線が印刷しないレイヤーにあります。 @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} パネル: {panels}、ヒンジ: {hinges}、エラー: {errors}、警告: {warnings} + Fold Preview 折りプレビュー + Fold 折り + Show Fold Lines 折り線を表示 + Three-Quarter 斜め + Open a document to preview its folded shape. ドキュメントを開くと折った形をプレビューできます。 +@msg Check the fold lines first. 先に折り線をチェックしてください。 +@msg Panels: {panels}, hinges: {hinges} パネル: {panels}、ヒンジ: {hinges} +@msg Other blanks not shown: {count} 表示されていない他の展開図: {count} +@msg A joint does not close by {gap} pt. 継ぎ目が {gap} pt 閉じていません。 +@msg Two panels pass through each other. 2 つのパネルが互いを貫通しています。 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 414f45171c..b84d5aa71b 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -409,6 +409,8 @@ @msg `{f}` is the copy of a document open now `{f}` ახლა გახსნილი დოკუმენტის ასლია @msg `{id}` is no writable format (see document.formats) `{id}` ჩაწერადი ფორმატი არ არის (იხ. document.formats) @msg `{id}` isn't a loaded library `{id}` ჩატვირთული ბიბლიოთეკა არ არის +@msg `{file}` has no swatches of its own `{file}`-ს საკუთარი ფერის ნიმუშები არ აქვს +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}`-ს აქვს პატერნის ნიმუშები, რომლებსაც .vcswatches ფაილი ვერ შეინახავს @msg `{key}` has no colours `{key}`: ფერები არ არის @msg `{key}` holds more than {MAX_EDIT_WORDS} words `{key}` {MAX_EDIT_WORDS}-ზე მეტ სიტყვას შეიცავს @msg `{key}` is a design name `{key}` არის დიზაინის სახელი @@ -731,6 +733,7 @@ @msg compound {_1} must contain exactly one open path to join შედგენილი {_1} შესაერთებლად ზუსტად ერთ ღია ტრაექტორიას უნდა შეიცავდეს @msg connect end must be "start" or "end" connect-ის end უნდა იყოს "start" ან "end" @msg connect needs a path other than the one extended connect-ს სჭირდება ტრაექტორია, რომელიც გაგრძელებულისგან განსხვავდება +@msg connect needs extend connect-ს სჭირდება extend @msg connect needs id connect-ს სჭირდება id @msg connect path has no open end connect-ის ტრაექტორიას ღია ბოლო არ აქვს @msg continuation must be an array of path chunks continuation უნდა იყოს ტრაექტორიის ნაწილების მასივი @@ -1977,7 +1980,7 @@ @msg each font must be {{name, parts}} თითოეული შრიფტი უნდა იყოს {{name, parts}} @msg feTurbulence's numOctaves is at most {MAX_OCTAVES} feTurbulence-ის numOctaves მაქსიმუმ {MAX_OCTAVES}-ია @msg give fonts: [{{name, parts}}…] მიუთითეთ fonts: [{{name, parts}}…] -@msg knockout groups with too many overlapping translucent elements are written as PDF knockout groups: their translucent elements knock out what they cover fully ჩაკვეთილი ჯგუფები, რომლებშიც ზედმეტად ბევრი ნახევრად გამჭვირვალე ელემენტი ერთმანეთს ფარავს, PDF-ის ჩაკვეთილ ჯგუფებად იწერება: მათი ნახევრად გამჭვირვალე ელემენტები სრულად ჩაკვეთს იმას, რასაც ფარავს +@msg knockout groups with too many overlapping translucent elements are written as PDF knockout groups: their translucent elements knock out what they cover fully ჩაკვეთილი ჯგუფები, რომლებშიც ზედმეტად ბევრი ნახევრად გამჭვირვალე ელემენტი ერთმანეთს ფარავს, PDF-ის ჩაკვეთილ ჯგუფებად იწერება: მათი ნახევრად გამჭვირვალე ელემენტები სრულად ჩაკვეთს იმას, რასაც ფარავს @msg no pattern `{pat}` პატერნი `{pat}` არ არის @msg numbers out of order in {{}} quantifier {{}} კვანტიფიკატორში რიცხვები არასწორი რიგითაა @msg plugin.remove: {_1}: {e}: nothing was removed plugin.remove: {_1}: {e}: არაფერი წაშლილა @@ -2062,6 +2065,8 @@ @msg {var_key} must be 0 or more {var_key} უნდა იყოს 0 ან მეტი @msg {var_key} must be at most {most} {var_key} უნდა იყოს მაქსიმუმ {most} @msg a linked image file is outside the read roots დაკავშირებული გამოსახულების ფაილი წაკითხვის ძირეული საქაღალდეების გარეთაა +@msg a linked file's export folder is outside the read roots დაკავშირებული ფაილის ექსპორტის საქაღალდე წაკითხვის ძირეული საქაღალდეების გარეთაა +@msg a linked file's editing data can't be read to check it against the read roots დაკავშირებული ფაილის რედაქტირების მონაცემების წაკითხვა ვერ ხერხდება წაკითხვის ძირეულ საქაღალდეებთან შესამოწმებლად Neon & Glow ნეონი და ნათება Show Hidden Panels at Edge დამალული პანელების ჩვენება კიდესთან @msg `anchor` must be a [subpath, anchor] pair `anchor` უნდა იყოს წყვილი [subpath, anchor] @@ -2331,6 +2336,8 @@ Shear… დახრა… Transform Each… თითოეულის გარდაქმნა… Reset Bounding Box შემომსაზღვრელი ჩარჩოს ჩამოყრა + Rotate Bounding Box შემომსაზღვრელი ჩარჩოს შემობრუნება + Rotate Bounding Box… შემომსაზღვრელი ჩარჩოს შემობრუნება… Arrange დალაგება Bring to Front წინა პლანზე გადმოტანა Bring Forward წინ გადმოტანა @@ -2837,6 +2844,13 @@ Previous Document წინა დოკუმენტი Cascade კასკადად Tile ფილებად + Tile All Vertically ყველა ფილებად ვერტიკალურად + Tile All Horizontally ყველა ფილებად ჰორიზონტალურად + 2-Up Layout 2-იანი განლაგება + 3-Up Layout 3-იანი განლაგება + 4-Up Layout 4-იანი განლაგება + 6-Up Layout 6-იანი განლაგება + Arrange Documents დოკუმენტების დალაგება Float in Window ცალკე ფანჯარაში გამოტანა Float All in Windows ყველას ცალკე ფანჯრებში გამოტანა Consolidate All Windows ყველა ფანჯრის გაერთიანება @@ -2874,6 +2888,11 @@ Saturation and brightness გაჯერება და სიკაშკაშე Color field ფერის ველი {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View წრის ხედი + Box View კვადრატის ხედი + Box Channel კვადრატის არხი + Color box ფერის კვადრატი + Color Wheel Options ფერთა წრის პარამეტრები CSS Properties CSS თვისებები Document Info დოკუმენტის ინფორმაცია Flattener Preview გაბრტყელების წინასწარი ნახვა @@ -3583,6 +3602,7 @@ lighting Light სინათლე Play Current Selection მიმდინარე მონიშნულის შესრულება Save Actions… მოქმედებების შენახვა… Load Actions… მოქმედებების ჩატვირთვა… + Replace Actions… მოქმედებების ჩანაცვლება… Reset Actions მოქმედებების ჩამოყრა Replace the current actions with the default set? ჩანაცვლდეს მიმდინარე მოქმედებები ნაგულისხმევი ნაკრებით? Append adds the default set after the current sets instead. „დამატება“ ამის ნაცვლად ნაგულისხმევ ნაკრებს მიმდინარე ნაკრებების შემდეგ ამატებს. @@ -3742,7 +3762,6 @@ digits Malayalam მალაიალამური Composite Fonts კომპოზიტური შრიფტები Export Composite Fonts კომპოზიტური შრიფტების ექსპორტი Import Composite Fonts კომპოზიტური შრიფტების იმპორტი -@msg each font must be {name, parts} თითოეული შრიფტი უნდა იყოს {name, parts} @msg unknown key `{k}`; a font takes name and parts უცნობი გასაღები `{k}`; შრიფტი იღებს name-სა და parts-ს @msg each font needs a name თითოეულ შრიფტს სახელი სჭირდება @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` ვერ იქნება კომპოზიტური შრიფტის სახელი (1-დან {COMPOSITE_NAME_MAX} სიმბოლომდე, მმართველი სიმბოლოების გარეშე) @@ -3755,7 +3774,6 @@ digits Malayalam მალაიალამური @msg two composite fonts are named `{_1}` ორ კომპოზიტურ შრიფტს ჰქვია `{_1}` @msg `{_1}` is the name of an installed font `{_1}` დაინსტალირებული შრიფტის სახელია @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2} იყენებს `{font}`-ს, რომელიც კომპოზიტური შრიფტია -@msg give fonts: [{name, parts}…] მიუთითეთ fonts: [{name, parts}…] @msg path is empty path ცარიელია @msg fonts must be a list of composite fonts fonts უნდა იყოს კომპოზიტური შრიფტების სია @msg names must be strings names უნდა იყოს სტრიქონები @@ -3798,6 +3816,7 @@ digits Malayalam მალაიალამური Underline ხაზგასმული Vertical Scale % ვერტიკალური მასშტაბი % Axis ღერძი + Axis Angle ღერძის კუთხე ICF Top/Right ICF ზედა/მარჯვენა ICF Bottom/Left ICF ქვედა/მარცხენა Show Font Height Options შრიფტის სიმაღლის პარამეტრების ჩვენება @@ -3840,6 +3859,7 @@ digits Malayalam მალაიალამური Rule: წესი: Save changes to {name} ცვლილებების შენახვა: {name} Save theme to My Themes თემის შენახვა „ჩემ თემებში“ + Set the current fill or stroke to the selected color მიმდინარე შევსების ან კონტურის მონიშნულ ფერად დაყენება Set the selected color to the current color მონიშნული ფერის მიმდინარე ფერად დაყენება Copy All Styles ყველა სტილის კოპირება Exported {path} ექსპორტირებულია: {path} @@ -4048,7 +4068,7 @@ digits Malayalam მალაიალამური Stroke: click for swatches, Shift-click for the color mixer კონტური: დაწკაპეთ ფერის ნიმუშებისთვის, Shift-დაწკაპუნებით — ფერის შემრევისთვის This panel is on the roadmap (see the parity plan). ეს პანელი სამომავლო გეგმაშია (იხ. პარიტეტის გეგმა). Open a document to navigate it. გახსენით დოკუმენტი მასში სანავიგაციოდ. - View Artboard Only მხოლოდ სამუშაო დაფის ჩვენება + View Artboard Contents Only მხოლოდ სამუშაო დაფის შიგთავსის ჩვენება Contextual Alternates კონტექსტური ალტერნატივები Default Figure ნაგულისხმევი ციფრები Discretionary Ligatures დამატებითი ლიგატურები @@ -4189,7 +4209,7 @@ digits Malayalam მალაიალამური Overprint Preview (separations) ზედდაბეჭდვის წინასწარი ნახვა (სეპარაციები) Show All Plates ყველა ფირფიტის ჩვენება Show all plates ყველა ფირფიტის ჩვენება - Show/hide plate (Alt-click: only this plate) ფირფიტის ჩვენება/დამალვა (Alt-დაწკაპუნებით: მხოლოდ ეს ფირფიტა) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) ფირფიტის ჩვენება/დამალვა (Alt-დაწკაპუნებით: მხოლოდ ეს ფირფიტა; ხელახლა Alt-დაწკაპუნებით: ყველა ფირფიტა) Simulate Paper ქაღალდის იმიტაცია Use Black Point Compensation შავი წერტილის კომპენსაციის გამოყენება Working CMYK (don't tag) სამუშაო CMYK (ტეგის გარეშე) @@ -4229,6 +4249,8 @@ digits Malayalam მალაიალამური Tip extends past the end point წვერი ბოლო წერტილს სცდება Tip on the end point წვერი ბოლო წერტილზე Variable Width Profile ცვლადი სიგანის პროფილი + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. კონტურის ფუნჯი საკუთარ ზომას ინარჩუნებს, ამიტომ სიგანის პროფილი მას არ ცვლის. პროფილის გამოსაყენებლად მოხსენით ფუნჯი. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. კონტურის ფუნჯი საკუთარ ზომას ინარჩუნებს, ამიტომ სიგანის პროფილი მას არ ცვლის. პროფილის გამოსაყენებლად მოხსენით ფუნჯი. Weight: სისქე: Art using a deleted global swatch keeps its colour. წაშლილი გლობალური ფერის ნიმუშის მქონე ნახატი თავის ფერს ინარჩუნებს. Color Group: {name} ფერთა ჯგუფი: {name} @@ -4337,6 +4359,10 @@ digits Malayalam მალაიალამური Flip Horizontal ჰორიზონტალურად არეკვლა Flip Vertical ვერტიკალურად არეკვლა Polygon Properties: მრავალკუთხედის თვისებები: + Line Properties: ხაზის თვისებები: + Line Length: ხაზის სიგრძე: + Line Angle: ხაზის კუთხე: + Constrain Pie Angle სექტორის კუთხის შენარჩუნება Rectangle Properties: მართკუთხედის თვისებები: Shape Properties: ფიგურის თვისებები: Shape Properties ფიგურის თვისებები @@ -4377,6 +4403,7 @@ digits Malayalam მალაიალამური Scatter: გაფანტვა: Rotation: შემობრუნება: Rotation relative to: შემობრუნების ათვლა: + Hue Jitter: ელფერის ვარიაცია: Brush Scale Options ფუნჯის მასშტაბირების პარამეტრები Scale Proportionately პროპორციული მასშტაბირება Stretch to Fit Stroke Length კონტურის სიგრძეზე გაწელვა @@ -4415,6 +4442,7 @@ digits Malayalam მალაიალამური Size: ზომა: Calligraphic Brush Options კალიგრაფიული ფუნჯის პარამეტრები Bristle Brush Options ჯაგრის ფუნჯის პარამეტრები + Roundness სიმრგვალე Roundness: სიმრგვალე: Shape: ფორმა: Bristle Length: ჯაგრის სიგრძე: @@ -4728,6 +4756,7 @@ digits Malayalam მალაიალამური BLANK DOCUMENT PRESETS ცარიელი დოკუმენტის პრესეტები Bleed ჭრისპირა არე Change to Right-to-Left Layout მარჯვნიდან მარცხნივ განლაგებაზე გადასვლა + Columns სვეტები Columns: სვეტები: Documents you create appear here. თქვენ მიერ შექმნილი დოკუმენტები აქ გამოჩნდება. More Settings მეტი პარამეტრი @@ -4860,6 +4889,9 @@ digits Malayalam მალაიალამური Open a document to preview its pages გახსენით დოკუმენტი მისი გვერდების წინასწარ სანახავად Output › Mode გამოტანა › რეჟიმი Overprint and Transparency Flattener Options ზედდაბეჭდვისა და გამჭვირვალობის გაბრტყელების პარამეტრები + Custom… მორგებული… + Custom Transparency Flattener Options გამჭვირვალობის გაბრტყელების მორგებული პარამეტრები + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS-ს არ აქვს ალფა-გამჭვირვალობა, ხოლო ზედდაბეჭდვები განსაზღვრავს, შენარჩუნდება თუ არა ზედდაბეჭდვები. Place the pages with the placement again გვერდების ხელახლა განთავსება განთავსების მიხედვით Placement: განთავსება: Preserve CMYK Numbers CMYK მნიშვნელობების შენარჩუნება @@ -4906,14 +4938,19 @@ digits Malayalam მალაიალამური Around Object ობიექტის ირგვლივ Background: ფონი: Changing these settings changes how raster effects look when exported, flattened or expanded. ამ პარამეტრების შეცვლა ცვლის, თუ როგორ გამოიყურება რასტრული ეფექტები ექსპორტის, გაბრტყელების ან გაშლის შემდეგ. + Add Around ობიექტის ირგვლივ დამატება + Anti Alias ანტიალიასინგი + Color Model ფერის მოდელი Color Model: ფერის მოდელი: Create Clipping Mask მომჭრელი ნიღბის შექმნა Preserve Spot Colors სპოტ-ფერების შენარჩუნება + Resolution გარჩევადობა Resolution: გარჩევადობა: Transparent გამჭვირვალე Layout Order: განლაგების რიგი: Change to Left-to-Right Layout მარცხნიდან მარჯვნივ განლაგებაზე გადასვლა Artboards: {n} სამუშაო დაფა: {n} + Rows სტრიქონები Rows: სტრიქონები: Assign მინიჭება Color Group: ფერთა ჯგუფი: @@ -5040,6 +5077,8 @@ antiAlias Sharp მკვეთრი Every option matches {base}. ყველა პარამეტრი ემთხვევა {base}-ს. Files of a PDF standard can't be password-protected. PDF სტანდარტის ფაილების პაროლით დაცვა შეუძლებელია. Files of this standard tag their colours with ICC profiles. ამ სტანდარტის ფაილები ფერებს ICC პროფილებით აღნიშნავს. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. ამ სტანდარტის ფაილები ფერებს ICC პროფილებით აღნიშნავს, გარდა გამოტანის მიზნის პროფილის CMYK ფერებისა, რომლებიც DeviceCMYK-ად იწერება. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. „პროფილების გარეშე“ და CMYK გამოტანის მიზნით ყველა CMYK ფერი DeviceCMYK-ად იწერება, თუ ის სხვა პროფილის CMYK დანიშნულებაში არ გარდაიქმნება. Flattener preset: გაბრტყელების პრესეტი: General › Thumbnails ზოგადი › ესკიზები Grayscale images ნაცრისფერი გამოსახულებები @@ -5164,6 +5203,11 @@ antiAlias Sharp მკვეთრი Encoding: კოდირება: Line Endings: სტრიქონის დაბოლოებები: Text Export Options ტექსტის ექსპორტის პარამეტრები + Chinese Big 5 ჩინური Big 5 + Cyrillic კირილიცა + Greek ბერძნული + Baltic ბალტიური + Central European ცენტრალურევროპული Character Set: სიმბოლოთა ნაკრები: Join the lines of each paragraph თითოეული აბზაცის სტრიქონების შეერთება Line Breaks სტრიქონის წყვეტები @@ -5193,6 +5237,9 @@ antiAlias Sharp მკვეთრი Variable Options ცვლადის პარამეტრები Define a variable first ჯერ განსაზღვრეთ ცვლადი Adjust Adjoining Width Points მეზობელი სიგანის წერტილების მორგება + Incoming შემავალი + Outgoing გამავალი + Single Width Only მხოლოდ ერთი სიგანე Keep both sides the same width ორივე მხარის ერთნაირი სიგანე Side 1: მხარე 1: Side 2: მხარე 2: @@ -5298,9 +5345,17 @@ theme Appearance იერსახე Break Link to Symbol სიმბოლოსთან კავშირის გაწყვეტა Brush Definition ფუნჯის განსაზღვრება Brush Options… ფუნჯის პარამეტრები… + Options of Selected Object… მონიშნული ობიექტის პარამეტრები… + Options of Selected Object მონიშნული ობიექტის პარამეტრები +@msg no path painted with a brush is selected ფუნჯით დახატული კონტური მონიშნული არ არის +@msg the selected paths are painted with brushes of different types მონიშნული კონტურები სხვადასხვა ტიპის ფუნჯებითაა დახატული +@msg give `params` or `reset`, not both მიუთითეთ `params` ან `reset`, არა ორივე +@msg a bristle brush has no options of its own on a path ჯაგრის ფუნჯს კონტურზე საკუთარი პარამეტრები არ აქვს Current Brush მიმდინარე ფუნჯი Current Symbol მიმდინარე სიმბოლო Delete Brush ფუნჯის წაშლა + Delete Color ფერის წაშლა + Restore Generated Table გენერირებული ცხრილის აღდგენა Delete Symbol სიმბოლოს წაშლა Delete the selected symbol? წაიშალოს მონიშნული სიმბოლო? Delete the selected symbols? წაიშალოს მონიშნული სიმბოლოები? @@ -5580,6 +5635,7 @@ theme Appearance იერსახე Select Art ნახატის მონიშვნა Set Current Layer მიმდინარე შრედ დაყენება Flatten Artwork ნახატის გაბრტყელება + Locate Layer შრის მოძებნა Locate Object ობიექტის მოძებნა Lock Others დანარჩენების ჩაკეტვა Merge Selected მონიშნულების შერწყმა @@ -5754,6 +5810,7 @@ theme Appearance იერსახე 90° & 45° Angles 90° და 45° კუთხეები 90° Angles 90° კუთხეები Additional Plug-ins Folder დამატებითი პლაგინები + Plug-in Instruction Budget პლაგინების ინსტრუქციების ბიუჯეტი Additional Fonts Folder შრიფტების დამატებითი საქაღალდე Alignment Guides გასწორების დამხმარე ხაზები Anchor Points, Handle, and Bounding Box Display საყრდენი წერტილების, სახელურებისა და შემომსაზღვრელი ჩარჩოს ჩვენება @@ -5780,6 +5837,7 @@ theme Appearance იერსახე Data Recovery მონაცემების აღდგენა Default Language ნაგულისხმევი ენა Disable Auto Add/Delete ავტომატური დამატება/წაშლის გამორთვა + Interpolate Control Points When Moving Anchors სახელურების ინტერპოლაცია საყრდენი წერტილების გადაადგილებისას Display All Blacks Accurately ყველა შავის ზუსტად ჩვენება Display All Blacks as Rich Black ყველა შავის მდიდარ შავად ჩვენება Display Bitmaps as Anti-aliased Images in Pixel Preview პიქსელურ ნახვაში ბიტმაპების ანტიალიასინგიან გამოსახულებებად ჩვენება @@ -5796,6 +5854,7 @@ theme Appearance იერსახე Enable Rubber Band for რეზინის ზოლის ჩართვა: Enable Touch Gestures შეხების ჟესტების ჩართვა Switch Selection and Drawing Modes მონიშვნისა და ხატვის რეჟიმების გადართვა + Select Last Selection Tool ბოლოს გამოყენებული მონიშვნის ხელსაწყოს არჩევა Enable Touch Workspace სენსორული სამუშაო სივრცის ჩართვა English: UK ინგლისური: ბრიტანეთი Every (minutes) ყოველ (წუთში) @@ -5867,6 +5926,9 @@ theme Appearance იერსახე Printing / Exporting ბეჭდვა / ექსპორტირება Real-time Drawing and Editing რეალურ დროში ხატვა და რედაქტირება Use Monitor Profile for Canvas მონიტორის პროფილის გამოყენება ტილოსთვის + Refresh Monitor Profile მონიტორის პროფილის განახლება +@msg turn on Use Monitor Profile for Canvas first ჯერ ჩართეთ „მონიტორის პროფილის გამოყენება ტილოსთვის“ +@msg this build doesn't read display profiles ეს ვერსია ეკრანის პროფილებს არ კითხულობს The canvas is drawn in sRGB. ტილო sRGB-ში იხატება. Canvas display profile: ტილოს ეკრანის პროფილი: The system matches the window to the display's colors. სისტემა ფანჯარას ეკრანის ფერებს უსადაგებს. @@ -5929,6 +5991,7 @@ theme Appearance იერსახე Scroll Sideways with Cmd/Ctrl + Wheel ჰორიზონტალური გადაადგილება Cmd/Ctrl + ბორბლით Scrub Numeric Fields by Dragging რიცხვითი ველების შეცვლა გადათრევით Linux Display Server Linux-ის ეკრანის სერვერი + Low-Latency Drawing დაბალი დაყოვნების ხატვა Print Preview ნახვა ამობეჭდვამდე Print Setup ბეჭდვის მომართვა Bitmap ბიტმაპი @@ -6236,6 +6299,9 @@ font-technology Variable ცვლადი Search commands, tools, panels and effects… ბრძანებების, ხელსაწყოების, პანელებისა და ეფექტების ძიება… No commands match შესაბამისი ბრძანება არ არის {pos} of {total}: {name} {pos} / {total}: {name} + No menu item მენიუს ელემენტი არ არის + Toolbar ხელსაწყოთა ზოლი + {toolbar}, in the {tool} group {toolbar}, ჯგუფში {tool} @plural {n} result|{n} results {n} შედეგი @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {n} შედეგიდან {shown}. გააგრძელეთ აკრეფა მათ შესამცირებლად. Recent Commands ბოლოდროინდელი ბრძანებები @@ -6273,6 +6339,7 @@ font-technology Variable ცვლადი The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. დაჭერილი Cmd/Ctrl-ით მაუსის ბორბალი ტილოს გვერდულად გადაახვევს. Dragging sideways on a numeric field's label changes the field's value. რიცხვითი ველის წარწერაზე გვერდულად გადათრევა ველის მნიშვნელობას ცვლის. A two-finger rotate gesture on a trackpad rotates the canvas view. ტრეკპადზე ორი თითით მობრუნების ჟესტი ტილოს ხედს აბრუნებს. + When you move anchor points, each curve with one moved end keeps its shape relative to its ends. როცა ღუზის წერტილებს გადაადგილებთ, ყოველი მრუდი, რომლის ერთი ბოლოც გადაადგილდა, ინარჩუნებს ფორმას თავის ბოლოებთან მიმართებით. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. ხელსაწყოს მალსახმობი კლავიშის დაჭერით ხელსაწყო არჩეულია მის აშვებამდე, შემდეგ კი ისევ წინა ხელსაწყო აირჩევა. Shows the bounding box while you move the selection or draw a shape. აჩვენებს შემომსაზღვრელ ჩარჩოს, სანამ მონიშნულს გადაადგილებთ ან ფიგურას ხატავთ. Create Trim Marks draws Japanese-style marks instead of Roman ones. ჭრის ნიშნების შექმნა რომაულის ნაცვლად იაპონური სტილის ნიშნებს ხატავს. @@ -6303,6 +6370,29 @@ font-technology Variable ცვლადი The unit for East Asian type measurements, which no field uses yet. აღმოსავლეთაზიური ტექსტის ზომების ერთეული, რომელსაც ჯერჯერობით არცერთი ველი არ იყენებს. When on, a number typed without a unit into a field in picas is read in points. ჩართვისას პიკებში მოცემულ ველში ერთეულის გარეშე აკრეფილი რიცხვი პუნქტებში იკითხება. With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options. XML ID-ის არჩევისას ობიექტების სახელები შრეების პანელში, ცვლადების პანელსა და შრის პარამეტრებში XML ID-ებად ჩანს. + The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl. ტექსტის ზომისა და სტრიქონთაშორისის ბიჯი: Cmd/Ctrl+Shift+. და Cmd/Ctrl+Shift+, ზომას ერთი ბიჯით ცვლის (Alt-ით ხუთით); ჰორიზონტალურ ტექსტში Alt და ზემოთ ან ქვემოთ ისარი სტრიქონთაშორისს ერთი ბიჯით ცვლის (Cmd/Ctrl-ით ხუთით). + The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl. ტრეკინგისა და კერნინგის ბიჯი em-ის მეათასედებში: ჰორიზონტალურ ტექსტში Alt მარცხენა ან მარჯვენა ისართან ერთად კურსორთან კერნინგს ან მონიშნული ტექსტის ტრეკინგს ერთი ბიჯით ცვლის, Cmd/Ctrl-თან ერთად კი ხუთით. + The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. საბაზისო ხაზის წანაცვლების ბიჯი: ჰორიზონტალურ ტექსტში Alt და Shift ზემოთ ან ქვემოთ ისართან ერთად საბაზისო ხაზს ერთი ბიჯით ანაცვლებს, Cmd/Ctrl-თან ერთად კი ხუთით. + Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. აჩვენებს იაპონური და სხვა აღმოსავლეთაზიური ტექსტის პარამეტრებს პანელებში სიმბოლო, აბზაცი, OpenType და გლიფები, ასევე ბრძანებას კომპოზიტური შრიფტები. + Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. აჩვენებს არაბული, ებრაული და ინდური ტექსტის პარამეტრებს პანელებში სიმბოლო და აბზაცი, მაგალითად აბზაცის მიმართულებას, ქაშიდებს და ციფრებს. + The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. მონიშვნის ხელსაწყოები ტექსტს მხოლოდ მის საბაზისო ხაზზე, არის ტექსტის ჩარჩოზე ან მის კონტურზე მონიშნავენ და არა მისი ყუთის შიგნით ნებისმიერ ადგილას. + Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. შრიფტების მენიუები ყოველ შრიფტს ინგლისური სახელით აჩვენებს; გამორთვისას შრიფტი, რომელსაც საკუთარ ენაზეც აქვს სახელი, იმ სახელს აჩვენებს. + New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. ახალი არის ტექსტი ჩართული ავტომატური ზომით იწყება, ამიტომ ჰორიზონტალური ტექსტის მართკუთხა ჩარჩო სიმაღლეში იზრდება ან მცირდება, რომ ტექსტი დაეტიოს. + Font lists and the Type › Font menu show a sample of each font beside its name. შრიფტების სიები და მენიუ შრიფტი თითოეული შრიფტის ნიმუშს მისი სახელის გვერდით აჩვენებს. + Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on. შრიფტის ნიმუშები მუქი ტექსტით თეთრზე იხატება ინტერფეისის სიკაშკაშის მიუხედავად; ეს მოქმედებს მხოლოდ მაშინ, როცა მენიუში შრიფტების გადახედვა ჩართულია. + How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is. რამდენად მაღალია თითოეული სტრიქონი შრიფტის ველების სიებში, მაგალითად სიმბოლოს პანელში, და შესაბამისად რამდენად დიდია თითოეული ნიმუში. + How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first. ბოლოს გამოყენებული რამდენი შრიფტი, 1-დან 15-მდე, ჩანს ბოლოდროინდელ შრიფტებსა და შრიფტების სიებში, უახლესი პირველი. + When you change the font or font style of text, characters the new font has no glyph for keep the font they had. ტექსტის შრიფტის ან შრიფტის სტილის შეცვლისას სიმბოლოები, რომელთათვისაც ახალ შრიფტს გლიფი არ აქვს, წინა შრიფტს ინარჩუნებენ. + A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export. ტილოზე ვარდისფერი მონიშვნა აღნიშნავს OpenType-ის ფუნქციების მიერ ჩანაცვლებულ გლიფებს, მაგალითად ლიგატურებს; ის არ იბეჭდება და არ ექსპორტდება. + With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from. ტექსტის ხელსაწყოთი ერთი სიმბოლოს მონიშვნისას ტილოზე მის გვერდით ჩანს მისი ალტერნატიული გლიფების რიგი ასარჩევად. + A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export. ტილოზე ვარდისფერი მონიშვნა აღნიშნავს ტექსტს, რომელიც შემცვლელი შრიფტით იხატება, რადგან მისი შრიფტი აკლია; ის არ იბეჭდება და არ ექსპორტდება. + New type made with a Type tool starts with placeholder text, selected, so typing replaces it. ტექსტის ხელსაწყოთი შექმნილი ახალი ტექსტი მონიშნული ჩანაცვლების ტექსტით იწყება, რომელსაც აკრეფილი ტექსტი ცვლის. + Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list. აბზაცის დასაწყისში სიის ნიშნის, მაგალითად 1. ან *, და შემდეგ ჰარის აკრეფა აბზაცს სიად აქცევს. + Fonts in this folder show in the font menus and can be used without being installed. ამ საქაღალდის შრიფტები შრიფტების მენიუებში ჩანს და მათი გამოყენება დაყენების გარეშეა შესაძლებელი. + Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows. ტექსტზე გრაფიკული სტილის გამოყენება სიმბოლოებს საკუთარ შევსებას ან კონტურს აშორებს იქ, სადაც სტილს ისინი აქვს, რათა სტილის საღებავი გამოჩნდეს. + Align and Distribute measure point type by the ink of its glyphs instead of its em box. სწორება და განაწილება წერტილის ტექსტს მისი გლიფების მელნით ზომავს და არა მისი em-ყუთით. + Align and Distribute measure area type by the ink of its glyphs instead of its frame. სწორება და განაწილება არის ტექსტს მისი გლიფების მელნით ზომავს და არა მისი ჩარჩოთი. + The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box. შემომსაზღვრელი ჩარჩო და გარდაქმნის პანელი წერტილის ტექსტს მისი გლიფების მელნით ზომავს და არა მისი em-ყუთით. Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply. ხატვას, გადაადგილებასა და მასშტაბირებას ბადის დაყოფებზე მიაბამს, მაშინაც კი, როცა ბადე დამალულია; სანამ ჩართულია, პიქსელზე მიბმა არ მოქმედებს. The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead. არჩეული არ მყოფი დამხმარე ხაზების ფერი; იარლიყიანი სამუშაო დაფა საკუთარ დამხმარე ხაზებს იარლიყის ფერით ხატავს. Draws guides as solid lines or as dots, including the guides already in the document. დამხმარე ხაზებს უწყვეტი ხაზებით ან წერტილებით ხატავს, დოკუმენტში უკვე არსებულების ჩათვლით. @@ -6346,6 +6436,8 @@ font-technology Variable ცვლადი Couldn't paste from the clipboard: {e} გაცვლის ბუფერიდან ჩასმა ვერ მოხერხდა: {e} Channel არხი Circle წრე + Circle Tool წრის ხელსაწყო + Circle too large წრე ზედმეტად დიდია Clip to Art ნახატზე მოჭრა Colorize გაფერადება Gamma გამა @@ -6619,6 +6711,7 @@ font-technology Variable ცვლადი @msg Saved {path} შენახულია: {path} @msg Select text or click into text with the Type tool to insert glyphs გლიფების ჩასასმელად მონიშნეთ ტექსტი ან ტექსტის ხელსაწყოთი დაწკაპეთ ტექსტში @msg Shape Builder: no region under the pointer ფიგურების კონსტრუქტორი: მაჩვენებლის ქვეშ არე არ არის +@msg Shape Builder: select all paths you want to merge ფიგურების კონსტრუქტორი: მონიშნეთ ყველა ტრაექტორია, რომლის გაერთიანებაც გსურთ @msg Shape Builder: select paths or compound paths ფიგურების კონსტრუქტორი: მონიშნეთ ტრაექტორიები ან შედგენილი ტრაექტორიები @msg Show All Hidden Attributes: nothing is hidden ყველა დამალული ატრიბუტის ჩვენება: დამალული არაფერია @msg Split Into Grid: select paths large enough for the grid ბადედ გაყოფა: მონიშნეთ ბადისთვის საკმარისად დიდი ტრაექტორიები @@ -6764,6 +6857,7 @@ font-technology Variable ცვლადი @msg choose a folder to export to აირჩიეთ ექსპორტის საქაღალდე @msg choose a location for the package აირჩიეთ შეფუთვის მდებარეობა @msg clipboard is empty გაცვლის ბუფერი ცარიელია +@msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: ფერების ცხრილში ერთი ფერი მაინც უნდა დარჩეს @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` ფერი არ არის, მაგალითად "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: არაუმეტეს {MAX_TABLE} ფერი @msg command `{0}` is not available right now: {1} ბრძანება `{0}` ახლა ხელმისაწვდომი არ არის: {1} @@ -6828,8 +6922,8 @@ font-technology Variable ცვლადი @msg no active document აქტიური დოკუმენტი არ არის @msg no active perspective plane აქტიური პერსპექტივის სიბრტყე არ არის @msg no anchor points selected საყრდენი წერტილები მონიშნული არ არის -@msg `points` must be three [x, y] pairs of numbers `points` უნდა იყოს რიცხვების სამი [x, y] წყვილი -@msg direct-select three anchor points, or give `points` პირდაპირი მონიშვნით მონიშნეთ სამი საყრდენი წერტილი ან მიუთითეთ `points` +@msg `points` must be two or three [x, y] pairs of numbers `points` უნდა იყოს რიცხვების ორი ან სამი [x, y] წყვილი +@msg direct-select two or three anchor points, or give `points` პირდაპირი მონიშვნით მონიშნეთ ორი ან სამი საყრდენი წერტილი ან მიუთითეთ `points` @msg no circle passes through these points: two are the same or all three lie on one line ამ წერტილებზე წრეწირი არ გადის: ორი ერთნაირია ან სამივე ერთ წრფეზე მდებარეობს @msg no app to open files here აქ ფაილების გასახსნელი აპი არ არის @msg no artboard სამუშაო დაფა არ არის @@ -6926,6 +7020,9 @@ font-technology Variable ცვლადი @msg no such user library მომხმარებლის ასეთი ბიბლიოთეკა არ არის @msg no such view ასეთი ხედი არ არის @msg no such width point ასეთი სიგანის წერტილი არ არის +@msg `single` must be `incoming` or `outgoing` `single` უნდა იყოს `incoming` ან `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` და `outIndex` უნდა იყოს ერთი წყვეტილი სიგანის წერტილის ორი ნახევარი +@msg a discontinuous width point keeps its place წყვეტილი სიგანის წერტილი თავის ადგილს ინარჩუნებს @msg no swatch `{name}` ფერის ნიმუში `{name}` არ არის @msg no swatch library `{l}` (see swatch.library.list) ფერის ნიმუშების ბიბლიოთეკა `{l}` არ არის (იხ. swatch.library.list) @msg no symbol instances selected სიმბოლოს ეგზემპლარები მონიშნული არ არის @@ -7183,6 +7280,8 @@ font-technology Variable ცვლადი @msg {label}: lost track of a shape's style {label}: ფიგურის სტილი დაიკარგა @msg {label}: select paths {label}: მონიშნეთ ტრაექტორიები @msg {label}: select paths, compound paths, groups or text {label}: მონიშნეთ ტრაექტორიები, შედგენილი ტრაექტორიები, ჯგუფები ან ტექსტი +@msg a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first ხაზი ან სხვა ღია ტრაექტორია, რომელიც ფართობს არ შემოსაზღვრავს, შედეგის ფორმას არ ცვლის; მის ჩასართავად ჯერ გამოიყენეთ ობიექტი › ტრაექტორია › კონტურის ფიგურად გარდაქმნა +@msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first {label}-მა ცარიელი შედეგი მოგვცა: ხაზი ან სხვა ღია ტრაექტორია ფართობს არ შემოსაზღვრავს; მის ჩასართავად ჯერ გამოიყენეთ ობიექტი › ტრაექტორია › კონტურის ფიგურად გარდაქმნა @msg {label}… {label}… @msg {name}: CRC mismatch {name}: CRC არ ემთხვევა @msg {name}: no local header {name}: ლოკალური სათაური არ არის @@ -7208,6 +7307,9 @@ font-technology Variable ცვლადი @msgplural Discarded {n} recovered document|Discarded {n} recovered documents უარყოფილია აღდგენილი დოკუმენტები: {n} @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them აღდგენილია დოკუმენტები: {n}: შესანარჩუნებლად შეინახეთ ისინი @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} გაიხსნა, შენიშვნები: {n}: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} კოპირებულია, შენიშვნები: {n}: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} ამოჭრილია, შენიშვნები: {n}: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} გამოსახულება ვექტორიზებულია, შენიშვნები: {n}: {first} @msgplural {notice}. Opened with {n} note: {first}|{notice}. Opened with {n} notes: {first} {notice}. გაიხსნა, შენიშვნები: {n}: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} შენახულია {path}, შენიშვნები: {n}: {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first ჩაშენებულია გამოსახულებები: {n}; აკლია {missing}: ჯერ ხელახლა დააკავშირეთ @@ -7234,6 +7336,8 @@ font-technology Variable ცვლადი @msg All colors are within the CMYK gamut ყველა ფერი CMYK-ის გამის ფარგლებშია @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut CMYK-ის გამის ფარგლებს გარეთაა ფერი ({n}) @msg Unembedded to {_1} ჩაშენება მოხსნილია: {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} ჩაშენება მოხსნილია, გამოსახულებები: {n}, საქაღალდე: {folder} +@msg every numbered name for {name} is taken in that folder იმ საქაღალდეში {name}-ის ყველა დანომრილი სახელი დაკავებულია @msg Reset {_1} ჩამოყრილია: {_1} @msg Sent to {_1} გაგზავნილია: {_1} @msg {_1} files ფაილები: {_1} @@ -7247,6 +7351,8 @@ font-technology Variable ცვლადი @msg Reload the page to go on (changes not saved yet may be lost). გასაგრძელებლად გადატვირთეთ გვერდი (ჯერ შეუნახავი ცვლილებები შეიძლება დაიკარგოს). @msg tool (a tool id) is required tool (ხელსაწყოს id) აუცილებელია @msg {tool} isn't in a toolbar group of several tools {tool} რამდენიმე ხელსაწყოს მქონე ხელსაწყოთა ჯგუფში არ არის +@msg Presentation Mode hides the toolbars: change the screen mode to show them პრეზენტაციის რეჟიმი მალავს ხელსაწყოთა ზოლებს: მათ საჩვენებლად შეცვალეთ ეკრანის რეჟიმი +@msg Tab has hidden the toolbars: press Tab to show them Tab-მა დამალა ხელსაწყოთა ზოლები: მათ საჩვენებლად დააჭირეთ Tab-ს @msg onto must name a panel floating in another group onto უნდა ასახელებდეს სხვა ჯგუფში მცურავ პანელს @msg below and above must name a panel floating in another group below და above უნდა ასახელებდეს სხვა ჯგუფში მცურავ პანელს @msg give only one of onto, below and above მიუთითეთ მხოლოდ ერთი: onto, below ან above @@ -7589,6 +7695,7 @@ font-technology Variable ცვლადი Ascent ზედა გამონაშვერი Cap Height მთავრული ასოს სიმაღლე x Height x-სიმაღლე + Em Box Height Em-ბლოკის სიმაღლე Justify ორმხრივი სწორება First Baseline პირველი საბაზისო ხაზი Vertical Align ვერტიკალური სწორება @@ -7710,6 +7817,7 @@ font-technology Variable ცვლადი Cove ღარი Depth სიღრმე Front წინიდან + Side გვერდიდან Isometric Bottom იზომეტრია ქვემოდან Isometric Left იზომეტრია მარცხნიდან Isometric Right იზომეტრია მარჯვნიდან @@ -7789,7 +7897,7 @@ font-technology Variable ცვლადი @msg each of `{GRAPHICS}` must be an object `{GRAPHICS}`-ის თითოეული ჩანაწერი უნდა იყოს ობიექტი @msg `{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}` `{GRAPHICS}`-ის ჩანაწერები იღებს symbol, face, x, y, scale და rotation მნიშვნელობებს და არა `{k}`-ს @msg each of `{GRAPHICS}` needs `symbol`, the name of a symbol `{GRAPHICS}`-ის თითოეულ ჩანაწერს სჭირდება `symbol`, სიმბოლოს სახელი -@msg `{GRAPHICS}` face must be front or back `{GRAPHICS}`-ის face უნდა იყოს front ან back +@msg `{GRAPHICS}` face must be front, back or side `{GRAPHICS}`-ის face უნდა იყოს front, back ან side @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} `{GRAPHICS}`-ის {key} უნდა იყოს რიცხვი {lo}-დან {hi}-მდე @msg `{GRAPHICS}` must be an array `{GRAPHICS}` უნდა იყოს მასივი @msg Graphics map onto the Plane, Extrude and Revolve object types გრაფიკა თავსდება ობიექტის ტიპებზე „სიბრტყე“, „ამოწევა“ და „ბრუნვა“ @@ -7999,6 +8107,13 @@ imageTrace Outline კონტური Show External Script Warning გარე სკრიპტის გაფრთხილების ჩვენება A Script Is Running სკრიპტი მუშაობს Script Alert სკრიპტის შეტყობინება + Script File Access სკრიპტის წვდომა ფაილებზე + The script asks to read a file you choose. სკრიპტი ითხოვს თქვენ მიერ არჩეული ფაილის წაკითხვას. + The script asks to read and write a file you choose. სკრიპტი ითხოვს თქვენ მიერ არჩეული ფაილის წაკითხვასა და ჩაწერას. + The script asks to read and write a folder you choose, with everything in it. სკრიპტი ითხოვს თქვენ მიერ არჩეული საქაღალდისა და მთელი მისი შიგთავსის წაკითხვასა და ჩაწერას. + Allow Once ერთხელ დაშვება + Always Allow This Script ამ სკრიპტის ყოველთვის დაშვება + Deny უარყოფა A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. სკრიპტს შეუძლია ღია დოკუმენტების შეცვლა და მის მიერ გაშვებული ბრძანებებით ფაილების ჩაწერა. გაუშვით მხოლოდ სანდო სკრიპტები. Do not show this warning again აღარ აჩვენო ეს გაფრთხილება Stop the script and undo what it did? Then quit again. შეჩერდეს სკრიპტი და გაუქმდეს მისი ცვლილებები? შემდეგ ხელახლა გამოდით. @@ -8015,6 +8130,8 @@ imageTrace Outline კონტური @msg the script is no longer in the Scripts folder სკრიპტი აღარ არის Scripts საქაღალდეში Some scripts were not listed ზოგიერთი სკრიპტი არ არის ჩამოთვლილი The Scripts folder cannot be read Scripts საქაღალდის წაკითხვა შეუძლებელია + Loading scripts… სკრიპტების ჩატვირთვა… + The Scripts folder is still being read Scripts საქაღალდე ჯერ კიდევ იკითხება @msg the script's run is no longer available სკრიპტის გაშვება აღარ არის ხელმისაწვდომი @msg a failed command changed undo steps that could not be put back, so the script was stopped წარუმატებელმა ბრძანებამ დაბრუნების ნაბიჯები შეცვალა და მათი პირვანდელ მდგომარეობაში მოყვანა ვერ მოხერხდა, ამიტომ სკრიპტი შეჩერდა @msg a recovery copy could not be written, so the script was not run აღდგენის ასლის ჩაწერა ვერ მოხერხდა, ამიტომ სკრიპტი არ გაეშვა @@ -8027,8 +8144,6 @@ imageTrace Outline კონტური @msg Script file could not be read სკრიპტის ფაილის წაკითხვა ვერ მოხერხდა @msg Script folder has more than 2,048 entries სკრიპტის საქაღალდეში 2048-ზე მეტი ჩანაწერია @msg Script file open mode must be r, w, e or a სკრიპტის ფაილის გახსნის რეჟიმი უნდა იყოს r, w, e ან a -@msg Script file writing is not available სკრიპტის ფაილების ჩაწერა მიუწვდომელია -@msg Script file dialogs are not available სკრიპტის ფაილის დიალოგები მიუწვდომელია @msg Script files cannot be opened in another application სკრიპტის ფაილების სხვა აპლიკაციაში გახსნა შეუძლებელია @msg Script file access is unavailable on the web ვებში სკრიპტის ფაილებზე წვდომა მიუწვდომელია @msg Script has 256 files open სკრიპტს 256 ფაილი აქვს გახსნილი @@ -8146,6 +8261,27 @@ liquify-list-end {0}, {1} {0} და {1} @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` მხოლოდ ისეთი გაშვებისთვისაა, სადაც შესაკითხი არავინაა: აპში თითოეულ დიალოგს ადამიანი პასუხობს @msg Running a script სკრიპტი მუშაობს @msg Copied the script report კოპირებულია სკრიპტის ანგარიში +@msg Script file access denied: {path} სკრიპტის წვდომა ფაილებზე უარყოფილია: {path} +@msg Script file access to the app's own folders is not allowed სკრიპტს არ აქვს აპის საკუთარ საქაღალდეებზე წვდომის უფლება +@msg Script file cannot encode the text სკრიპტის ფაილი ვერ აკოდირებს ტექსტს +@msg Script file could not be written სკრიპტის ფაილის ჩაწერა ვერ მოხერხდა +@msg Script file dialogs need a person to answer them სკრიპტის ფაილის დიალოგებს სჭირდება ადამიანი, რომელიც უპასუხებს +@msg Script file is not open for writing სკრიპტის ფაილი ჩასაწერად გახსნილი არ არის +@msg Script file name is already in use სკრიპტის ფაილის სახელი უკვე გამოიყენება +@msg Script file name must be a name without a folder სკრიპტის ფაილის სახელი უნდა იყოს სახელი საქაღალდის გარეშე +@msg Script file permission can be kept only for a script run from a file ფაილების ნებართვის შენახვა შესაძლებელია მხოლოდ ფაილიდან გაშვებული სკრიპტისთვის +@msg Script file permission could not be saved სკრიპტის ფაილების ნებართვის შენახვა ვერ მოხერხდა +@msg Script folder is not empty სკრიპტის საქაღალდე ცარიელი არ არის +@msg Script files cannot make aliases სკრიპტის ფაილებს არ შეუძლიათ ფსევდონიმების შექმნა +@msg Script file hidden setting cannot be changed სკრიპტის ფაილის დამალვის პარამეტრის შეცვლა შეუძლებელია +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: ფაილის დიალოგი ვერ გაიხსნება ჩაშენებული ფუნქციის, getter-ის, გარდაქმნის ან $.evalFile-ის მიერ გაშვებული ფაილის callback-ში; გამოიძახეთ ის სკრიპტის საკუთარი კოდიდან +@msg the script wrote more file data than one run may write (32 MiB) სკრიპტმა ჩაწერა იმაზე მეტი ფაილის მონაცემი, ვიდრე ერთ გაშვებას შეუძლია ჩაწეროს (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop სკრიპტის ფაილის დიალოგისთვის `answer` უნდა იყოს ერთ-ერთი: once, always, deny, stop +@msg choose a file or folder first, or deny ჯერ აირჩიეთ ფაილი ან საქაღალდე, ან უარყავით +@msg the script file permissions could not be saved: {e} სკრიპტების ფაილების ნებართვების შენახვა ვერ მოხერხდა: {e} +@msg this script's file access can be allowed only once ამ სკრიპტის წვდომა ფაილებზე მხოლოდ ერთხელ შეიძლება დაიშვას +@msg Only the person at the keyboard can allow a script's file access სკრიპტის წვდომას ფაილებზე მხოლოდ კლავიატურასთან მყოფი ადამიანი უშვებს +@msg A script is given at most 2,048 files: the files picked after them were left out სკრიპტი იღებს მაქსიმუმ 2 048 ფაილს: მათ შემდეგ არჩეული ფაილები გამოტოვებულია @msg Copied the link info კოპირებულია ბმულის ინფორმაცია @msg Offset Path: the offset leaves nothing of the selected paths (an inset larger than the shapes) ტრაექტორიის წანაცვლება: წანაცვლების შემდეგ მონიშნული ტრაექტორიებიდან არაფერი რჩება (შიგნით წანაცვლება ფიგურებზე დიდია) @msg {path}: not a file {path}: ფაილი არ არის @@ -8244,6 +8380,8 @@ liquify-list-end {0}, {1} {0} და {1} Keep selected მონიშნულად დატოვება Reset Tracking and Kerning ტრეკინგისა და კერნინგის ჩამოყრა Highlight Font Name შრიფტის სახელის გამოკვეთა + Highlight Font Size შრიფტის ზომის გამოკვეთა + Other… სხვა… Highlight Kerning კერნინგის გამოკვეთა Highlight Tracking ტრეკინგის გამოკვეთა Legacy (version 7) ძველი (ვერსია 7) @@ -8330,6 +8468,11 @@ liquify-list-end {0}, {1} {0} და {1} Hide Template შაბლონის დამალვა Show Template შაბლონის ჩვენება Path Length ტრაექტორიის სიგრძე + Grid Size ბადის ზომა + Grid Colors ბადის ფერები + Flattener Preset გაბრტყელების პრესეტი + X X + Y Y Filter ფილტრი Clear All ყველას გასუფთავება By Object ობიექტის მიხედვით @@ -8343,6 +8486,8 @@ liquify-list-end {0}, {1} {0} და {1} Color Panel Options ფერის პანელის პარამეტრები @msg `{key}` must be an array of these names: {_1} `{key}` უნდა იყოს ამ სახელების მასივი: {_1} @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` უნდა იყოს grayscale, rgb, hsb, cmyk ან websafe +@msg `view` must be wheel or box `view` უნდა იყოს wheel ან box +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` უნდა იყოს hue, saturation, brightness, red, green ან blue @msg this is a PostScript file (an .ai saved in an older format or without PDF compatibility, or an EPS file), not a PDF: File › Open and File › Place read it as EPS ეს PostScript ფაილია (ძველ ფორმატში ან PDF-თან თავსებადობის გარეშე შენახული .ai, ან EPS ფაილი) და არა PDF: ფაილი › გახსნა და ფაილი › განთავსება მას EPS-ად კითხულობს # Upstream sync 2026-10-16 (3): Intertwine, symbol registration, gradient span, data sets, Batch. Intertwine გადახლართვა @@ -8734,6 +8879,13 @@ liquify-list-end {0}, {1} {0} და {1} @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} {MAX_CSV_ROWS}-ზე მეტი მონაცემთა ნაკრები: მონაცემთა ნაკრებების იმპორტი კითხულობს მაქსიმუმ {MAX_CSV_ROWS}-ს @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} {MAX_CSV_COLS}-ზე მეტი ცვლადი: მონაცემთა ნაკრებების იმპორტი კითხულობს მაქსიმუმ {MAX_CSV_COLS}-ს @msg variables that aren't text were left out: {kinds} ცვლადები, რომლებიც ტექსტი არ არის, გამოტოვებულია: {kinds} +variable-kind Visibility ხილვადობა +variable-kind Linked File დაკავშირებული ფაილი +variable-kind Graph Data დიაგრამის მონაცემები +variable-kind Unknown უცნობი +variable-list-two {0}, {1} {0} და {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} და {1} @msg a new document won't read these variables back with their kind: {names} ახალი დოკუმენტი ამ ცვლადებს მათი ტიპით ვერ წაიკითხავს: {names} @msg a new document refuses this file because of these variables: {names} ახალი დოკუმენტი ამ ფაილს ამ ცვლადების გამო უარყოფს: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them `{name}`-ის სათაური `{header}` წაიკითხება როგორც ცვლადი `{other}`: გადაარქვით სახელი ერთ-ერთს @@ -9594,6 +9746,12 @@ anchor Points: წერტილები: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` უნდა იყოს "free", "keepAngles" ან "symmetric" @msg `{key}` must be [x, y] `{key}` უნდა იყოს [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter ერთეულების გადამყვანი + Unit Converter Panel ერთეულების გადამყვანის პანელი + Copy with Units ერთეულებით კოპირება + From Selection მონიშნულიდან + # Color Effects add-on: Select by Color Kind. Select by Color Kind ფერის სახეობით არჩევა Objects with Spot Colors ობიექტები სპოტ-ფერებით @@ -9818,6 +9976,14 @@ breakText Glyphs გლიფები Remove Gaps ღრეჩოების მოცილება @msg that makes too many pieces (at most 100000): make the dashes longer ეს ძალიან ბევრ ნაწილს იძლევა (მაქსიმუმ 100000): გაზარდეთ ტირეების სიგრძე @msg select paths, or segments, to divide აირჩიეთ დასაყოფი ტრაექტორიები ან სეგმენტები +# Path Precision Tools add-on: Smooth Bridge. + Smooth Bridge… გლუვი ხიდი… + Smooth Bridge გლუვი ხიდი + Keep Originals ორიგინალების შენარჩუნება +@msg select two circles to bridge აირჩიეთ ორი წრე დასაკავშირებლად +@msg one circle is inside the other ერთი წრე მეორის შიგნითაა +@msg the circles are too far apart for this radius: raise the radius ამ რადიუსისთვის წრეები ერთმანეთისგან ძალიან შორსაა: გაზარდეთ რადიუსი +@msg the circles are too far apart for this radius ამ რადიუსისთვის წრეები ერთმანეთისგან ძალიან შორსაა # Path Precision Tools add-on: Common Tangents. Common Tangents… საერთო მხებები… Common Tangents საერთო მხებები @@ -10284,4 +10450,14 @@ font-script Japanese იაპონური @msg A panel is not joined to the rest by a crease. პანელი დანარჩენს არცერთი ბიგის ხაზით არ უერთდება. @msg A fold line is on a non-printing layer. მოკეცვის ხაზი არაბეჭდვად შრეზეა. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} პანელები: {panels}, ანჯამები: {hinges}, შეცდომები: {errors}, გაფრთხილებები: {warnings} + Fold Preview მოკეცვის გადახედვა + Fold მოკეცვა + Show Fold Lines მოკეცვის ხაზების ჩვენება + Three-Quarter სამი მეოთხედი + Open a document to preview its folded shape. გახსენით დოკუმენტი მისი მოკეცილი ფორმის სანახავად. +@msg Check the fold lines first. ჯერ შეამოწმეთ მოკეცვის ხაზები. +@msg Panels: {panels}, hinges: {hinges} პანელები: {panels}, ანჯამები: {hinges} +@msg Other blanks not shown: {count} სხვა ნამზადები არ ჩანს: {count} +@msg A joint does not close by {gap} pt. შეერთება არ იხურება {gap} pt-ით. +@msg Two panels pass through each other. ორი პანელი ერთმანეთში გადის. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer უნდა იყოს "singleLine", "everyLine", "standardSingleLine" ან "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index dbda53243f..61bda0cfa7 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -43,6 +43,9 @@ font-technology Variable 가변 Cap Height 대문자 높이 x-Height x 높이 ICF Box ICF 박스 + Ascent 어센트 + x Height x 높이 + Em Box Height 엠 박스 높이 Show Sample 샘플 표시 Hide Sample 샘플 숨기기 Max Ascent/Descent 최대 어센트/디센트 @@ -210,6 +213,8 @@ digits Malayalam 말라얄람어 Shear… 기울이기… Transform Each… 각각 변형… Reset Bounding Box 경계 상자 재설정 + Rotate Bounding Box 경계 상자 회전 + Rotate Bounding Box… 경계 상자 회전… Arrange 정렬 순서 Bring to Front 맨 앞으로 가져오기 Bring Forward 앞으로 가져오기 @@ -457,6 +462,8 @@ digits Malayalam 말라얄람어 Reset Tracking and Kerning 자간 및 커닝 재설정 Reset Horizontal Scale 가로 비율 재설정 Highlight Font Name 글꼴 이름 강조 표시 + Highlight Font Size 글꼴 크기 강조 표시 + Other… 기타… Highlight Kerning 커닝 강조 표시 Highlight Tracking 자간 강조 표시 Step Type 단계별 문자 @@ -743,6 +750,13 @@ digits Malayalam 말라얄람어 Previous Document 이전 문서 Cascade 계단식 배열 Tile 바둑판식 배열 + Tile All Vertically 모두 세로로 바둑판식 배열 + Tile All Horizontally 모두 가로로 바둑판식 배열 + 2-Up Layout 2분할 레이아웃 + 3-Up Layout 3분할 레이아웃 + 4-Up Layout 4분할 레이아웃 + 6-Up Layout 6분할 레이아웃 + Arrange Documents 문서 정렬 Float in Window 창에 플로팅 Float All in Windows 모두 창에 플로팅 Consolidate All Windows 모든 창 통합 @@ -781,6 +795,11 @@ digits Malayalam 말라얄람어 Saturation and brightness 채도 및 밝기 Color field 색상 필드 {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View 휠 보기 + Box View 상자 보기 + Box Channel 상자 채널 + Color box 색상 상자 + Color Wheel Options 색상환 옵션 CSS Properties CSS 속성 Document Info 문서 정보 Flattener Preview 병합 미리 보기 @@ -1043,6 +1062,7 @@ digits Malayalam 말라얄람어 Add Anchor (Pen) 앵커 추가(펜) Add Anchor Point 앵커 포인트 추가 Add Anchor Point Tool 앵커 포인트 추가 도구 + Add Around 개체 주위에 추가 Add Effect 효과 추가 Add Freeform Line 자유형 선 추가 Add Freeform Point 자유형 점 추가 @@ -1063,8 +1083,12 @@ digits Malayalam 말라얄람어 Add to Selection 선택 영역에 추가 Add to Swatches 견본에 추가 Additional Plug-ins Folder 추가 플러그인 폴더 + Plug-in Instruction Budget 플러그인 명령어 예산 Additional Fonts Folder 추가 글꼴 폴더 Adjust Adjoining Width Points 인접한 너비 점 조정 + Incoming 들어오는 쪽 + Outgoing 나가는 쪽 + Single Width Only 한 너비만 Adjust Colors 색상 조정 Adjust Options: 조정 옵션: Advanced Options 고급 옵션 @@ -1104,6 +1128,7 @@ digits Malayalam 말라얄람어 Angle: 각도: Angles 각도 Animated Zoom 애니메이션 확대/축소 + Anti Alias 안티 앨리어싱 Anti-Alias 안티 앨리어싱 Anti-alias 안티 앨리어싱 Anti-alias Rasters 래스터 안티 앨리어싱 @@ -1205,6 +1230,12 @@ antiAlias Sharp 날카롭게 Brush Affects: 브러시 적용 대상: Brush Definition 브러시 정의 Brush Options… 브러시 옵션… + Options of Selected Object… 선택한 오브젝트 옵션… + Options of Selected Object 선택한 오브젝트 옵션 +@msg no path painted with a brush is selected 브러시로 칠한 패스가 선택되지 않았습니다 +@msg the selected paths are painted with brushes of different types 선택한 패스가 서로 다른 유형의 브러시로 칠해져 있습니다 +@msg give `params` or `reset`, not both `params`와 `reset` 중 하나만 지정하세요 +@msg a bristle brush has no options of its own on a path 강모 브러시는 패스별 옵션이 없습니다 Built-in presets are read-only: New… starts an editable copy. 기본 제공 프리셋은 읽기 전용입니다. 새로 만들기…를 누르면 편집 가능한 복사본이 만들어집니다. Built-in presets don't change: New makes a copy you can edit. 기본 제공 프리셋은 변경되지 않습니다. 새로 만들기를 누르면 편집 가능한 복사본이 만들어집니다. Built-in presets don't change: New… starts an editable copy. 기본 제공 프리셋은 변경되지 않습니다. 새로 만들기…를 누르면 편집 가능한 복사본이 만들어집니다. @@ -1228,6 +1259,12 @@ antiAlias Sharp 날카롭게 Channel 채널 Character / Paragraph 문자 / 단락 Character Rotation 문자 회전 + Chinese Big 5 중국어 Big 5 + Cyrillic 키릴 자모 + Greek 그리스어 + Turkish 터키어 + Baltic 발트어 + Central European 중앙 유럽어 Character Set: 문자 집합: Character Style Options 문자 스타일 옵션 Check Links 링크 확인 @@ -1287,6 +1324,8 @@ antiAlias Sharp 날카롭게 Choose a folder 폴더 선택 Choose… 선택… Circle 원 + Circle Tool 점 기준 원 도구 + Circle too large 원이 너무 큽니다 Clear All Tabs 모든 탭 지우기 Above Text 문자 위 Position Panel Above Text 패널을 문자 위에 배치 @@ -1328,6 +1367,7 @@ antiAlias Sharp 날카롭게 Color Guide Options… 색상 가이드 옵션… Color Mode 색상 모드 Color Mode: 색상 모드: + Color Model 색상 모델 Color Model: 색상 모델: Color Models 색상 모델 Color Picker 색상 피커 @@ -1346,6 +1386,7 @@ antiAlias Sharp 날카롭게 Colors 색상 Colors: 색상: Column Graph Tool 세로 막대 그래프 도구 + Columns 열 Columns: 열: Coming soon — tracked in the parity plan 곧 제공 예정 — 기능 동등성 계획에서 관리 중 Command Click to Select Objects Behind Command-클릭으로 뒤쪽 개체 선택 @@ -1469,6 +1510,8 @@ antiAlias Sharp 날카롭게 Delete Artboard 아트보드 삭제 Delete Artboards 아트보드 삭제 Delete Brush 브러시 삭제 + Delete Color 색상 삭제 + Restore Generated Table 생성된 표 복원 Delete Character Style 문자 스타일 삭제 Delete Empty Artboards 빈 아트보드 삭제 Delete Freeform Point 자유 형태 포인트 삭제 @@ -1531,6 +1574,7 @@ antiAlias Sharp 날카롭게 Dimensions 치수 Direct Selection Tool 직접 선택 도구 Disable Auto Add/Delete 자동 추가/삭제 사용 안 함 + Interpolate Control Points When Moving Anchors 앵커 포인트 이동 시 방향 핸들 보간 Disable Opacity Mask 불투명 마스크 사용 안 함 Discard 삭제 Preserve 보존 @@ -1684,6 +1728,7 @@ antiAlias Sharp 날카롭게 Enable Rubber Band for 러버 밴드 사용 대상 Enable Touch Gestures 터치 제스처 사용 Switch Selection and Drawing Modes 선택 모드와 그리기 모드 전환 + Select Last Selection Tool 마지막으로 사용한 선택 도구로 전환 Enable Touch Workspace 터치 작업 영역 사용 Enable copying of text, images and other content 텍스트, 이미지 및 기타 콘텐츠 복사 허용 Enable in-menu font previews 메뉴에서 글꼴 미리 보기 사용 @@ -1819,6 +1864,8 @@ antiAlias Sharp 날카롭게 Files 파일 Files of a PDF standard can't be password-protected. PDF 표준 파일은 암호로 보호할 수 없습니다. Files of this standard tag their colours with ICC profiles. 이 표준의 파일은 ICC 프로파일로 색상을 태그합니다. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. 이 표준의 파일은 ICC 프로파일로 색상을 태그합니다. 단, 출력 의도 프로파일의 CMYK 색상은 DeviceCMYK로 기록됩니다. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. '프로파일 포함 안 함'과 CMYK 출력 의도를 사용하면, 다른 프로파일의 CMYK 대상으로 변환되지 않는 한 모든 CMYK 색상이 DeviceCMYK로 기록됩니다. Fill 칠 Fill New Type Objects With Placeholder Text 새 문자 개체를 대체 텍스트로 채우기 Start Lists From Typed Markers 입력한 기호로 목록 시작 @@ -2323,6 +2370,7 @@ antiAlias Sharp 날카롭게 Load SVG into Clipboard SVG를 클립보드로 불러오기 Load Text into Clipboard 텍스트를 클립보드로 불러오기 Local Libraries 로컬 라이브러리 + Locate Layer 레이어 찾기 Locate Object 개체 찾기 Locate Selected Objects 선택한 개체 찾기 Location 위치 @@ -2444,6 +2492,7 @@ antiAlias Sharp 날카롭게 Scatter: 흩뿌림: Rotation: 회전: Rotation relative to: 회전 기준: + Hue Jitter: 색조 변화: Brush Scale Options 브러시 크기 조절 옵션 Scale Proportionately 비율에 맞게 크기 조절 Stretch to Fit Stroke Length 선 길이에 맞게 늘이기 @@ -2480,6 +2529,7 @@ antiAlias Sharp 날카롭게 Black becomes the stroke color and white stays white. Other colors become tints of the stroke color by their lightness. 검정은 선 색상이 되고 흰색은 흰색으로 남습니다. 다른 색상은 선 색상의 틴트가 되며, 색상이 밝을수록 틴트도 밝아집니다. Black and white stay as they are. Dark colors become shades of the stroke color and light colors become tints of it. 검정은 검정으로 남고 흰색은 흰색으로 남습니다. 다른 색상은 어두우면 선 색상의 셰이드가 되고 밝으면 틴트가 됩니다. The key color becomes the stroke color. The other colors shift their hue by the same amount and keep their saturation and brightness. 키 색상은 선 색상이 됩니다. 다른 색상은 키 색상과 같은 만큼 색상환에서 이동하며 채도와 밝기를 유지합니다. + Roundness 원형률 Roundness: 원형률: Fixed 고정 Pressure 필압 @@ -2716,6 +2766,9 @@ antiAlias Sharp 날카롭게 Overprint Stroke 선 오버프린트 Overprint and Transparency Flattener 오버프린트 및 투명도 병합 Overprint and Transparency Flattener Options 오버프린트 및 투명도 병합 옵션 + Custom… 사용자 지정… + Custom Transparency Flattener Options 사용자 지정 투명도 병합 옵션 + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS에는 알파 투명도가 없으며, 오버프린트 설정에 따라 오버프린트 유지 여부가 결정됩니다. Overprint: 오버프린트: Overprints: 오버프린트: Override Character Color 문자 색상 덮어쓰기 @@ -2753,6 +2806,13 @@ antiAlias Sharp 날카롭게 Pathfinders: 패스파인더: Paths 패스 Path Length 패스 길이 + Grid Size 격자 크기 + Grid Colors 격자 색상 + Flattener Preset 병합 프리셋 + X X + Y Y + Orange 주황 + Purple 보라 Paths: {paths} Anchors: {anchors} Colors: {colors} 패스: {paths} 앵커: {anchors} 색상: {colors} Pattern Editing 패턴 편집 Pattern options are available in pattern editing mode. 패턴 옵션은 패턴 편집 모드에서 사용할 수 있습니다. @@ -2790,6 +2850,7 @@ diagnostics ui UI Play Current Selection 현재 선택 항목 재생 Save Actions… 액션 저장… Load Actions… 액션 불러오기… + Replace Actions… 액션 바꾸기… Reset Actions 액션 재설정 Replace the current actions with the default set? 현재 액션을 기본 세트로 바꾸시겠습니까? Append adds the default set after the current sets instead. 추가를 누르면 대신 기본 세트를 현재 세트 뒤에 추가합니다. @@ -2802,6 +2863,10 @@ diagnostics ui UI Polar Grid Tool 극좌표 격자 도구 Polygon 다각형 Polygon Properties: 다각형 속성: + Line Properties: 선 속성: + Line Length: 선 길이: + Line Angle: 선 각도: + Constrain Pie Angle 파이 각도 고정 Polygon Tool 다각형 도구 Portrait 세로 Portuguese Português @@ -2903,6 +2968,9 @@ mark-style Japanese 일본식 Real World: 실제 크기: Real-time Drawing and Editing 실시간 그리기 및 편집 Use Monitor Profile for Canvas 캔버스에 모니터 프로필 사용 + Refresh Monitor Profile 모니터 프로필 새로 고침 +@msg turn on Use Monitor Profile for Canvas first 먼저 "캔버스에 모니터 프로필 사용"을 켜세요 +@msg this build doesn't read display profiles 이 빌드는 디스플레이 프로필을 읽지 않습니다 The canvas is drawn in sRGB. 캔버스는 sRGB로 그려집니다. Canvas display profile: 캔버스 디스플레이 프로필: The system matches the window to the display's colors. 시스템이 창을 디스플레이 색상에 맞춥니다. @@ -3087,6 +3155,7 @@ mark-style Japanese 일본식 Reshape Segment 세그먼트 모양 다듬기 Reshape Tool 모양 다듬기 도구 Reshape Type Area 문자 영역 모양 다듬기 + Resolution 해상도 Resolution: 해상도: Responsive 반응형 Restore 복원 @@ -3114,6 +3183,7 @@ mark-style Japanese 일본식 The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Cmd/Ctrl 키를 누른 채 마우스 휠을 돌리면 캔버스가 가로로 스크롤됩니다. Dragging sideways on a numeric field's label changes the field's value. 숫자 필드의 레이블을 옆으로 드래그하면 필드 값이 바뀝니다. A two-finger rotate gesture on a trackpad rotates the canvas view. 트랙패드에서 두 손가락으로 회전하는 동작을 하면 캔버스 보기가 회전합니다. + When you move anchor points, each curve with one moved end keeps its shape relative to its ends. 고정점을 이동하면 한쪽 끝이 이동한 각 곡선은 양 끝을 기준으로 모양을 유지합니다. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. 도구의 바로 가기 키를 누르고 있는 동안 그 도구가 선택되고, 키를 놓으면 이전 도구가 다시 선택됩니다. Shows the bounding box while you move the selection or draw a shape. 선택 영역을 이동하거나 모양을 그리는 동안 테두리 상자를 표시합니다. Create Trim Marks draws Japanese-style marks instead of Roman ones. 트림 마크 만들기에서 서양식 대신 일본식 표시를 그립니다. @@ -3144,6 +3214,29 @@ mark-style Japanese 일본식 The unit for East Asian type measurements, which no field uses yet. 동아시아 문자 측정에 쓰는 단위로, 아직 이 단위를 쓰는 필드는 없습니다. When on, a number typed without a unit into a field in picas is read in points. 켜면 파이카 필드에 단위 없이 입력한 숫자를 포인트로 읽습니다. With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options. XML ID를 고르면 레이어, 변수, 레이어 옵션에서 개체 이름이 XML ID로 표시됩니다. + The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl. 문자 크기와 행간의 단계입니다. Cmd/Ctrl+Shift+. 와 Cmd/Ctrl+Shift+, 는 크기를 한 단계, Alt도 누르면 다섯 단계 바꿉니다. 가로 문자에서 Alt와 위쪽 또는 아래쪽 화살표는 행간을 한 단계, Cmd/Ctrl도 누르면 다섯 단계 바꿉니다. + The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl. 자간과 커닝의 단계로, 단위는 1/1000 em입니다. 가로 문자에서 Alt와 왼쪽 또는 오른쪽 화살표는 캐럿 위치의 커닝이나 선택한 텍스트의 자간을 한 단계, Cmd/Ctrl도 누르면 다섯 단계 바꿉니다. + The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. 기준선 이동의 단계입니다. 가로 문자에서 Alt, Shift와 위쪽 또는 아래쪽 화살표는 기준선을 한 단계, Cmd/Ctrl도 누르면 다섯 단계 옮깁니다. + Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. 문자, 단락, OpenType, 글리프 패널에 일본어 등 동아시아 문자의 옵션을 표시하고 합성 글꼴 명령도 표시합니다. + Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. 문자 패널과 단락 패널에 단락 방향, 카시다, 숫자 등 아랍어, 히브리어, 인도계 문자의 옵션을 표시합니다. + The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. 선택 도구는 문자를 기준선, 영역 문자의 프레임 또는 패스에서만 선택하며 상자 안의 아무 곳에서나 선택하지 않습니다. + Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. 글꼴 메뉴에 각 글꼴을 영어 이름으로 표시합니다. 끄면 자국어 이름도 있는 글꼴은 그 이름으로 표시됩니다. + New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. 새 영역 문자는 자동 크기가 켜진 상태로 시작하므로 가로 문자의 직사각형 프레임이 텍스트에 맞게 높이가 늘거나 줄어듭니다. + Font lists and the Type › Font menu show a sample of each font beside its name. 글꼴 목록과 글꼴 메뉴에 각 글꼴 이름 옆에 그 글꼴의 견본을 표시합니다. + Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on. 글꼴 견본을 인터페이스 밝기와 관계없이 흰 바탕에 어두운 글자로 그립니다. 메뉴의 글꼴 미리 보기가 켜져 있을 때만 적용됩니다. + How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is. 문자 패널 같은 글꼴 필드의 목록에서 각 행의 높이이며, 따라서 각 견본의 크기입니다. + How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first. 최근 글꼴과 글꼴 목록에 마지막으로 사용한 글꼴을 최신순으로 몇 개 표시할지입니다(1~15). + When you change the font or font style of text, characters the new font has no glyph for keep the font they had. 텍스트의 글꼴이나 글꼴 스타일을 바꿀 때 새 글꼴에 글리프가 없는 문자는 원래 글꼴을 유지합니다. + A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export. OpenType 기능이 대체한 합자 등의 글리프를 캔버스에서 분홍색 강조로 표시합니다. 인쇄나 내보내기에는 포함되지 않습니다. + With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from. 문자 도구로 한 글자를 선택하면 캔버스에서 그 옆에 고를 수 있는 대체 글리프 줄이 표시됩니다. + A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export. 글꼴이 없어 대체 글꼴로 그려진 텍스트를 캔버스에서 분홍색 강조로 표시합니다. 인쇄나 내보내기에는 포함되지 않습니다. + New type made with a Type tool starts with placeholder text, selected, so typing replaces it. 문자 도구로 만든 새 문자는 선택된 자리 표시자 텍스트로 시작하며, 입력하면 그 텍스트가 바뀝니다. + Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list. 단락 시작에서 1. 또는 * 같은 목록 기호와 공백을 입력하면 그 단락이 목록이 됩니다. + Fonts in this folder show in the font menus and can be used without being installed. 이 폴더의 글꼴은 글꼴 메뉴에 표시되며 설치하지 않고 사용할 수 있습니다. + Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows. 문자에 그래픽 스타일을 적용하면 스타일에 칠이나 선이 있는 곳에서 문자 자체의 칠이나 선이 제거되어 스타일의 페인트가 보입니다. + Align and Distribute measure point type by the ink of its glyphs instead of its em box. 정렬과 분포는 포인트 문자를 em 상자 대신 글리프의 잉크로 측정합니다. + Align and Distribute measure area type by the ink of its glyphs instead of its frame. 정렬과 분포는 영역 문자를 프레임 대신 글리프의 잉크로 측정합니다. + The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box. 테두리 상자와 변형 패널은 포인트 문자를 em 상자 대신 글리프의 잉크로 측정합니다. Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply. 격자가 숨겨져 있어도 그리기, 이동, 크기 조절을 격자의 세분 위치에 스냅합니다. 켜져 있는 동안에는 픽셀에 스냅이 적용되지 않습니다. The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead. 선택되지 않은 안내선의 색상입니다. 안내선 레이블이 있는 아트보드는 자신의 안내선을 레이블 색상으로 그립니다. Draws guides as solid lines or as dots, including the guides already in the document. 문서에 이미 있는 안내선을 포함해 안내선을 실선 또는 점으로 그립니다. @@ -3206,6 +3299,7 @@ mark-style Japanese 일본식 Rounded Rectangle 둥근 사각형 Rounded Rectangle Tool 둥근 사각형 도구 Row Size: 행 크기: + Rows 행 Rows: 행: Rule: 규칙: Rulers & Grids 눈금자 및 격자 @@ -3302,6 +3396,11 @@ mark-style Japanese 일본식 Search commands, tools, panels and effects… 명령, 도구, 패널 및 효과 검색… No commands match 일치하는 명령이 없습니다 {pos} of {total}: {name} {total}개 중 {pos}번째: {name} + No menu item 메뉴 항목 없음 + Toolbar 도구 모음 + {toolbar}, in the {tool} group {toolbar}, {tool} 그룹 + Tool 도구 + Command 명령 @plural {n} result|{n} results 결과 {n}개 @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. 결과 {n}개 중 {shown}개. 계속 입력하여 범위를 좁히세요. Recent Commands 최근 명령 @@ -3359,6 +3458,7 @@ mark-style Japanese 일본식 Set Text 문자 설정 Set Zoom 확대/축소 설정 Set base color to the current color 기준 색상을 현재 색상으로 설정 + Set the current fill or stroke to the selected color 현재 칠 또는 선을 선택한 색상으로 설정 Set the selected color to the current color 선택한 색상을 현재 색상으로 설정 Setup… 설정… Shape Builder 모양 빌더 @@ -3417,7 +3517,7 @@ mark-style Japanese 일본식 Show all plates 모든 분판 표시 Show handles when multiple anchors are selected 여러 앵커 선택 시 핸들 표시 Show {kind} Brushes {kind} 브러시 표시 - Show/hide plate (Alt-click: only this plate) 분판 표시/숨기기(Alt 클릭: 이 분판만) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) 분판 표시/숨기기(Alt 클릭: 이 분판만, 다시 Alt 클릭: 모든 분판) Show: 표시: Shown with the optimised preview. 최적화된 미리 보기와 함께 표시됩니다. Side 1: 면 1: @@ -3772,6 +3872,8 @@ mark-style Japanese 일본식 User Swatch Library 9 사용자 견본 라이브러리 9 V Spacing: 세로 간격: Variable Width Profile 가변 너비 프로파일 + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. 선의 브러시는 고유한 크기를 유지하므로 너비 프로파일로 바뀌지 않습니다. 프로파일을 사용하려면 브러시를 제거하세요. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. 선의 브러시는 고유한 크기를 유지하므로 너비 프로파일로 바뀌지 않습니다. 프로파일을 사용하려면 브러시를 제거하세요. Variation: 변형: Vector Halftone 벡터 하프톤 Vector illustration — fast, open, scriptable. 벡터 일러스트레이션 — 빠르고 개방적이며 스크립트 지원. @@ -3785,7 +3887,7 @@ mark-style Japanese 일본식 Vertical Type Tool 세로 문자 도구 Vertical Type on a Path Tool 패스 상의 세로 문자 도구 Vertical: 세로: - View Artboard Only 아트보드만 보기 + View Artboard Contents Only 아트보드 내용만 보기 View Opacity Mask 불투명 마스크 보기 View PDF after saving 저장 후 PDF 보기 Viewing Angle: 시야각: @@ -4265,7 +4367,7 @@ file-filter Templates 템플릿 Composite Fonts 합성 글꼴 Export Composite Fonts 합성 글꼴 내보내기 Import Composite Fonts 합성 글꼴 가져오기 -@msg each font must be {name, parts} 각 글꼴은 {name, parts} 형식이어야 합니다 +@msg each font must be {{name, parts}} 각 글꼴은 {{name, parts}} 형식이어야 합니다 @msg unknown key `{k}`; a font takes name and parts 알 수 없는 키 `{k}`: 글꼴에는 name과 parts만 쓸 수 있습니다 @msg each font needs a name 각 글꼴에는 이름이 필요합니다 @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}`은(는) 합성 글꼴 이름으로 쓸 수 없습니다(1~{COMPOSITE_NAME_MAX}자, 제어 문자 없음) @@ -4278,7 +4380,7 @@ file-filter Templates 템플릿 @msg two composite fonts are named `{_1}` 이름이 `{_1}`인 합성 글꼴이 두 개 있습니다 @msg `{_1}` is the name of an installed font `{_1}`은(는) 설치된 글꼴의 이름입니다 @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2}이(가) 합성 글꼴인 `{font}`(으)로 설정되어 있습니다 -@msg give fonts: [{name, parts}…] fonts를 지정하세요: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] fonts를 지정하세요: [{{name, parts}}…] @msg path is empty path가 비어 있습니다 @msg fonts must be a list of composite fonts fonts는 합성 글꼴 목록이어야 합니다 @msg names must be strings names는 문자열이어야 합니다 @@ -4447,6 +4549,7 @@ imageTrace Outline 윤곽선 Bevel 베벨 Offset 오프셋 Axis 축 + Axis Angle 축 각도 axis Horizontal 가로 axis Vertical 세로 axis Both 양쪽 @@ -4607,6 +4710,7 @@ theme Appearance 외관 @msg Live Paint: select paths or compound paths 라이브 페인트: 패스 또는 컴파운드 패스를 선택하세요 @msg Live Paint: these paths are too degenerate to paint 라이브 페인트: 이 패스는 퇴화되어 칠할 수 없습니다 @msg Shape Builder: no region under the pointer 모양 빌더: 포인터 아래에 영역이 없습니다 +@msg Shape Builder: select all paths you want to merge 모양 빌더: 병합할 패스를 모두 선택하세요 @msg Shape Builder: select paths or compound paths 모양 빌더: 패스 또는 컴파운드 패스를 선택하세요 @msg image data `{_1}` is missing 이미지 데이터 `{_1}`이(가) 없습니다 @msg no Live Paint edge near that point 그 지점 근처에 라이브 페인트 가장자리가 없습니다 @@ -4642,6 +4746,13 @@ theme Appearance 외관 @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} 데이터 세트가 {MAX_CSV_ROWS}개보다 많습니다: 데이터 세트 가져오기는 최대 {MAX_CSV_ROWS}개를 읽습니다 @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} 변수가 {MAX_CSV_COLS}개보다 많습니다: 데이터 세트 가져오기는 최대 {MAX_CSV_COLS}개를 읽습니다 @msg variables that aren't text were left out: {kinds} 텍스트가 아닌 변수는 제외되었습니다: {kinds} +variable-kind Visibility 가시성 +variable-kind Linked File 연결된 파일 +variable-kind Graph Data 그래프 데이터 +variable-kind Unknown 알 수 없음 +variable-list-two {0}, {1} {0} 및 {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} 및 {1} @msg a new document won't read these variables back with their kind: {names} 새 문서는 이 변수들을 원래 종류로 다시 읽지 않습니다: {names} @msg a new document refuses this file because of these variables: {names} 새 문서는 이 변수들 때문에 이 파일을 거부합니다: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them `{name}`의 머리글 `{header}`은(는) 변수 `{other}`(으)로 다시 읽힙니다: 둘 중 하나의 이름을 바꾸십시오 @@ -4674,6 +4785,7 @@ theme Appearance 외관 @msg Expand: no gradient fills 확장: 그레이디언트 칠이 없습니다 @msg Expand: nothing to expand 확장: 확장할 항목이 없습니다 @msg batch step {_1} (`{id}`) failed: {e} 일괄 처리 단계 {_1}(`{id}`) 실패: {e} +@msg action step {_1} (`{id}`) failed: {reason} 액션 단계 {_1}(`{id}`) 실패: {reason} @msg BMP files are RGB or grayscale: colorModel rgb or gray BMP 파일은 RGB 또는 그레이스케일입니다: colorModel rgb 또는 gray @msg Targa files are RGB: colorModel rgb Targa 파일은 RGB입니다: colorModel rgb @msg antiAlias `{id}`: none, art or type antiAlias `{id}`: none, art 또는 type이어야 합니다 @@ -4770,8 +4882,8 @@ theme Appearance 외관 @msg image would be too large; lower the resolution 이미지가 너무 커집니다. 해상도를 낮추세요 @msg clipboard is empty 클립보드가 비어 있습니다 @msg no anchor points selected 선택한 앵커 포인트가 없습니다 -@msg `points` must be three [x, y] pairs of numbers `points`는 숫자 쌍 [x, y] 세 개여야 합니다 -@msg direct-select three anchor points, or give `points` 앵커 포인트 세 개를 직접 선택하거나 `points`를 지정하세요 +@msg `points` must be two or three [x, y] pairs of numbers `points`는 숫자 쌍 [x, y] 두 개 또는 세 개여야 합니다 +@msg direct-select two or three anchor points, or give `points` 앵커 포인트 두 개 또는 세 개를 직접 선택하거나 `points`를 지정하세요 @msg no circle passes through these points: two are the same or all three lie on one line 이 점들을 지나는 원이 없습니다: 두 점이 같거나 세 점이 모두 한 직선 위에 있습니다 @msg select at least two objects 개체를 두 개 이상 선택하세요 @msg exit isolation mode first 먼저 격리 모드를 종료하세요 @@ -4813,6 +4925,8 @@ theme Appearance 외관 @msg {label}: lost track of a shape's style {label}: 모양의 스타일을 잃었습니다 @msg {label}: select paths {label}: 패스를 선택하세요 @msg {label}: select paths, compound paths, groups or text {label}: 패스, 컴파운드 패스, 그룹 또는 텍스트를 선택하세요 +@msg a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first 영역을 둘러싸지 않는 선이나 기타 열린 패스는 결과의 모양을 바꾸지 않습니다. 포함하려면 먼저 개체 › 패스 › 선 윤곽선화를 적용하세요 +@msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first {label}의 결과가 비어 있습니다. 선이나 기타 열린 패스가 영역을 둘러싸지 않습니다. 포함하려면 먼저 개체 › 패스 › 선 윤곽선화를 적용하세요 @msg already editing a pattern 이미 패턴을 편집 중입니다 @msg no pattern `{name}` `{name}` 패턴이 없습니다 @msg not in pattern editing mode 패턴 편집 모드가 아닙니다 @@ -4894,6 +5008,7 @@ theme Appearance 외관 @msg Create Outlines: select text objects 윤곽선 만들기: 텍스트 개체를 선택하세요 @msg paste unavailable 붙여넣을 수 없습니다 @msg Save for Web: the image is empty 웹용으로 저장: 이미지가 비어 있습니다 +@msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: 색상 표에 색상이 하나 이상 남아 있어야 합니다 @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}`은(는) "#ff8800" 같은 색상이 아닙니다 @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: 색상은 최대 {MAX_TABLE}개입니다 @msg no artboard {i} (0-based; the document has {_1}) 아트보드 {i}이(가) 없습니다(0부터 시작, 문서의 아트보드 수: {_1}) @@ -5141,6 +5256,12 @@ theme Appearance 외관 @msg no preset editor 프리셋 편집기가 없습니다 @msg no perspective grid preset named `{name}` `{name}`이라는 원근 격자 프리셋이 없습니다 @msg no active perspective plane 활성 원근 평면이 없습니다 +@msg the perspective grid is hidden 원근 격자가 숨겨져 있습니다 +@msg Automatic Plane Positioning is off: turn on anchorPoint or gridlineIntersection (perspective.widget.options) 자동 평면 배치가 꺼져 있습니다: anchorPoint 또는 gridlineIntersection을 켜세요 (perspective.widget.options) +@msg anchorPoint must be true or false anchorPoint는 true 또는 false여야 합니다 +@msg gridlineIntersection must be true or false gridlineIntersection은 true 또는 false여야 합니다 +@msg tolerance must be 0 or more tolerance는 0 이상이어야 합니다 +@msg give `at` or `clear`, not both `at`과 `clear` 중 하나만 지정하세요 @msg plane must be left, right or ground plane은 left, right 또는 ground여야 합니다 @msg missing `id` (see plugin.list) `id`가 없습니다(plugin.list 참조) @msg no plug-in {id} is installed 플러그인 {id}이(가) 설치되어 있지 않습니다 @@ -5191,6 +5312,9 @@ theme Appearance 외관 @msg `{color}` is not a colour (#rrggbb or a preset name) `{color}`은(는) 색상이 아닙니다(#rrggbb 또는 프리셋 이름) @msg give the path `id` and the width point `index` 패스 `id`와 너비 점 `index`를 지정하세요 @msg no such width point 해당 너비 점이 없습니다 +@msg `single` must be `incoming` or `outgoing` `single`은 `incoming` 또는 `outgoing`이어야 합니다 +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index`와 `outIndex`는 하나의 불연속 너비 점의 두 절반이어야 합니다 +@msg a discontinuous width point keeps its place 불연속 너비 점은 위치를 유지합니다 @msg onto must name a panel floating in another group onto는 다른 그룹에 떠 있는 패널을 지정해야 합니다 @msg below and above must name a panel floating in another group below와 above는 다른 그룹에 떠 있는 패널을 지정해야 합니다 @msg give only one of onto, below and above onto, below, above 중 하나만 지정하세요 @@ -5220,6 +5344,8 @@ theme Appearance 외관 @msg No saved views (View → New View…) 저장된 보기가 없습니다(보기 → 새 보기…) @msg `command` must be a command whose menu item opens a dialog (see ui.menuDialog) `command`는 메뉴 항목이 대화상자를 여는 명령이어야 합니다(ui.menuDialog 참조) @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode`은(는) grayscale, rgb, hsb, cmyk, websafe 중 하나여야 합니다 +@msg `view` must be wheel or box `view`은(는) wheel, box 중 하나여야 합니다 +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel`은(는) hue, saturation, brightness, red, green, blue 중 하나여야 합니다 @msg `{key}` must be true or false `{key}`은(는) true 또는 false여야 합니다 @msg `top` and `below` can't both be true `top`과 `below`를 동시에 true로 지정할 수 없습니다 @msg `select` must be true or false `select`은(는) true 또는 false여야 합니다 @@ -5301,6 +5427,13 @@ theme Appearance 외관 Show External Script Warning 외부 스크립트 경고 표시 A Script Is Running 스크립트 실행 중 Script Alert 스크립트 알림 + Script File Access 스크립트 파일 접근 + The script asks to read a file you choose. 스크립트가 선택한 파일을 읽도록 요청합니다. + The script asks to read and write a file you choose. 스크립트가 선택한 파일을 읽고 쓰도록 요청합니다. + The script asks to read and write a folder you choose, with everything in it. 스크립트가 선택한 폴더와 그 안의 모든 항목을 읽고 쓰도록 요청합니다. + Allow Once 한 번 허용 + Always Allow This Script 이 스크립트 항상 허용 + Deny 거부 A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. 스크립트는 열려 있는 문서를 변경하고 실행하는 명령을 통해 파일을 쓸 수 있습니다. 신뢰할 수 있는 스크립트만 실행하세요. Do not show this warning again 이 경고를 다시 표시하지 않음 Stop the script and undo what it did? Then quit again. 스크립트를 중지하고 변경 내용을 취소할까요? 그런 다음 다시 종료하세요. @@ -5317,6 +5450,8 @@ theme Appearance 외관 @msg the script is no longer in the Scripts folder 스크립트가 더 이상 Scripts 폴더에 없습니다 Some scripts were not listed 일부 스크립트가 나열되지 않았습니다 The Scripts folder cannot be read Scripts 폴더를 읽을 수 없습니다 + Loading scripts… 스크립트 불러오는 중… + The Scripts folder is still being read Scripts 폴더를 아직 읽는 중입니다 @msg the script's run is no longer available 스크립트 실행을 더 이상 사용할 수 없습니다 @msg a failed command changed undo steps that could not be put back, so the script was stopped 실패한 명령이 되돌릴 수 없는 실행 취소 단계를 변경하여 스크립트를 중지했습니다 @msg a recovery copy could not be written, so the script was not run 복구 사본을 쓸 수 없어 스크립트를 실행하지 않았습니다 @@ -5329,8 +5464,6 @@ theme Appearance 외관 @msg Script file could not be read 스크립트 파일을 읽을 수 없습니다 @msg Script folder has more than 2,048 entries 스크립트 폴더의 항목이 2,048개를 초과합니다 @msg Script file open mode must be r, w, e or a 스크립트 파일 열기 모드는 r, w, e 또는 a여야 합니다 -@msg Script file writing is not available 스크립트 파일 쓰기를 사용할 수 없습니다 -@msg Script file dialogs are not available 스크립트 파일 대화 상자를 사용할 수 없습니다 @msg Script files cannot be opened in another application 스크립트 파일을 다른 응용 프로그램에서 열 수 없습니다 @msg Script file access is unavailable on the web 웹에서는 스크립트 파일에 접근할 수 없습니다 @msg Script has 256 files open 스크립트가 파일 256개를 열고 있습니다 @@ -5446,8 +5579,37 @@ liquify-list-end {0}, {1} {0} 및 {1} @msg the main script engine is new for each run and is never kept, so it cannot be dropped 기본 스크립트 엔진은 실행마다 새로 만들어지고 유지되지 않으므로 삭제할 수 없습니다 @msg there is no script engine named {name} 이름이 {name}인 스크립트 엔진이 없습니다 @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers`는 물어볼 사람이 없는 실행에만 쓰입니다. 앱에서는 사람이 각 대화 상자에 답합니다 +@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel`은(는) 1에서 {_1} 사이의 정수여야 합니다 +@msg `args{place}` is nested more than 64 levels deep `args{place}`이(가) 64단계보다 깊게 중첩되어 있습니다 +@msg `args` must be an object `args`은(는) 개체여야 합니다 +@msg `args` is larger than 1 MiB `args`이(가) 1 MiB보다 큽니다 +@msg `path` is empty `path`이(가) 비어 있습니다 +@msg `installed` takes a `path`, not a `source` `installed`에는 `source`가 아니라 `path`를 지정하세요 +@msg `path` must name a .js or .jsx file `path`은(는) .js 또는 .jsx 파일을 가리켜야 합니다 +@msg give exactly one of `path` and `source` `path`, `source` 중 정확히 하나를 지정하세요 @msg Running a script 스크립트 실행 중 @msg Copied the script report 스크립트 보고서를 복사했습니다 +@msg Script file access denied: {path} 스크립트 파일 접근이 거부되었습니다: {path} +@msg Script file access to the app's own folders is not allowed 스크립트는 앱 자체 폴더에 접근할 수 없습니다 +@msg Script file cannot encode the text 스크립트 파일이 텍스트를 인코딩할 수 없습니다 +@msg Script file could not be written 스크립트 파일을 쓸 수 없습니다 +@msg Script file dialogs need a person to answer them 스크립트 파일 대화 상자에는 응답할 사람이 필요합니다 +@msg Script file is not open for writing 스크립트 파일이 쓰기용으로 열려 있지 않습니다 +@msg Script file name is already in use 스크립트 파일 이름이 이미 사용 중입니다 +@msg Script file name must be a name without a folder 스크립트 파일 이름은 폴더 없는 이름이어야 합니다 +@msg Script file permission can be kept only for a script run from a file 파일 권한은 파일에서 실행한 스크립트에만 유지할 수 있습니다 +@msg Script file permission could not be saved 스크립트 파일 권한을 저장할 수 없습니다 +@msg Script folder is not empty 스크립트 폴더가 비어 있지 않습니다 +@msg Script files cannot make aliases 스크립트 파일은 별칭을 만들 수 없습니다 +@msg Script file hidden setting cannot be changed 스크립트 파일의 숨김 설정을 변경할 수 없습니다 +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: 기본 제공 함수, getter, 변환 또는 $.evalFile이 실행하는 파일의 콜백 안에서는 파일 대화 상자를 열 수 없습니다. 스크립트 자체 코드에서 호출하세요 +@msg the script wrote more file data than one run may write (32 MiB) 스크립트가 한 번의 실행에서 쓸 수 있는 것보다 많은 파일 데이터를 썼습니다(32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop 스크립트 파일 대화 상자의 `answer`는 once, always, deny, stop 중 하나여야 합니다 +@msg choose a file or folder first, or deny 먼저 파일이나 폴더를 선택하거나 거부하세요 +@msg the script file permissions could not be saved: {e} 스크립트 파일 권한을 저장할 수 없습니다: {e} +@msg this script's file access can be allowed only once 이 스크립트의 파일 접근은 한 번만 허용할 수 있습니다 +@msg Only the person at the keyboard can allow a script's file access 스크립트의 파일 접근은 키보드 앞에 있는 사람만 허용할 수 있습니다 +@msg A script is given at most 2,048 files: the files picked after them were left out 스크립트에는 파일이 최대 2,048개까지 전달됩니다: 그 뒤에 고른 파일은 제외되었습니다 @msg Copied the link info 링크 정보를 복사했습니다 @msg Exported {path} {path}을(를) 내보냈습니다 @msg no CSS to copy: select objects with CSS of their own 복사할 CSS가 없습니다: 자체 CSS가 있는 개체를 선택하세요 @@ -5484,6 +5646,8 @@ liquify-list-end {0}, {1} {0} 및 {1} @msg All colors are within the CMYK gamut 모든 색상이 CMYK 색상 범위 안에 있습니다 @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut 색상 {n}개가 CMYK 색상 범위를 벗어났습니다 @msg Unembedded to {_1} {_1}에 포함 해제했습니다 +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} 이미지 {n}개를 {folder}에 포함 해제했습니다 +@msg every numbered name for {name} is taken in that folder 해당 폴더에서 {name}을(를) 위한 번호 이름이 모두 사용 중입니다 @msg no swatch library `{l}` (see swatch.library.list) 견본 라이브러리 `{l}`이(가) 없습니다(swatch.library.list 참조) @msg no user library folder here 여기에는 사용자 라이브러리 폴더가 없습니다 @msg Couldn't place {name}: the document it was dropped on was closed {name}을(를) 가져올 수 없습니다: 놓은 문서가 닫혔습니다 @@ -5509,6 +5673,9 @@ liquify-list-end {0}, {1} {0} 및 {1} @msgplural Discarded {n} recovered document|Discarded {n} recovered documents 복구된 문서 {n}개를 삭제했습니다 @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them 복구된 문서 {n}개를 복원했습니다: 보관하려면 저장하세요 @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} 참고 {n}건과 함께 열었습니다: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} 참고 {n}건과 함께 복사했습니다: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} 참고 {n}건과 함께 잘라냈습니다: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} 참고 {n}건과 함께 이미지를 추적했습니다: {first} @msgplural {notice}. Opened with {n} note: {first}|{notice}. Opened with {n} notes: {first} {notice}. 참고 {n}건과 함께 열었습니다: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} 참고 {n}건과 함께 {path}을(를) 저장했습니다: {first} @msg Saving recovery data for {_1} {_1}의 복구 데이터를 저장하는 중 @@ -5537,6 +5704,8 @@ liquify-list-end {0}, {1} {0} 및 {1} @msg the {tool} tool has no options {tool} 도구에는 옵션이 없습니다 @msg unknown tool `{tool}` 알 수 없는 도구 `{tool}` @msg {tool} isn't in a toolbar group of several tools {tool}은(는) 여러 도구가 있는 도구 모음 그룹에 속하지 않습니다 +@msg Presentation Mode hides the toolbars: change the screen mode to show them 프레젠테이션 모드에서는 도구 모음이 숨겨집니다: 표시하려면 화면 모드를 변경하세요 +@msg Tab has hidden the toolbars: press Tab to show them Tab으로 도구 모음이 숨겨졌습니다: 표시하려면 Tab을 누르세요 @msg no such document 해당 문서가 없습니다 @msg {_1}: not saved, so not closed {_1}: 저장되지 않아 닫지 않았습니다 @msg `{name}` is a built-in workspace; choose another name `{name}`은(는) 기본 제공 작업 영역입니다: 다른 이름을 선택하세요 @@ -5586,6 +5755,9 @@ liquify-list-end {0}, {1} {0} 및 {1} @msg automation path rejected: outside the read root {root}: {path} 자동화 경로가 거부되었습니다: 읽기 루트 {root} 밖입니다: {path} @msg automation path rejected: outside the read roots {roots}: {path} 자동화 경로가 거부되었습니다: 읽기 루트 {roots} 밖입니다: {path} @msg a linked JavaScript file is outside the read roots 연결된 JavaScript 파일이 읽기 루트 밖에 있습니다 +@msg a linked image file is outside the read roots 연결된 이미지 파일이 읽기 루트 밖에 있습니다 +@msg a linked file's export folder is outside the read roots 연결된 파일의 내보내기 폴더가 읽기 루트 밖에 있습니다 +@msg a linked file's editing data can't be read to check it against the read roots 연결된 파일의 편집 데이터를 읽을 수 없어 읽기 루트와 대조할 수 없습니다 @msg automation path rejected: outside the write root {root}: {path} 자동화 경로가 거부되었습니다: 쓰기 루트 {root} 밖입니다: {path} @msg automation path rejected: outside the write roots {roots}: {path} 자동화 경로가 거부되었습니다: 쓰기 루트 {roots} 밖입니다: {path} @msg automation path rejected: path is empty 자동화 경로가 거부되었습니다: 경로가 비어 있습니다 @@ -5810,6 +5982,7 @@ lighting Light 광원 @msg missing panel layout 패널 레이아웃이 없습니다 @msg unsupported native docking operation 지원되지 않는 기본 도킹 작업 Linux Display Server Linux 디스플레이 서버 + Low-Latency Drawing 저지연 그리기 X11 (XWayland) When a Pen Is Attached 펜 연결 시 X11 (XWayland) If a drawing tablet's pen doesn't draw, choose an X11 (XWayland) option. 드로잉 태블릿의 펜으로 그려지지 않으면 X11 (XWayland) 옵션을 선택하세요. X11 (XWayland) X11 (XWayland) @@ -5862,6 +6035,7 @@ lighting Light 광원 Cove 오목 Depth 깊이 Front 앞면 + Side 옆면 Isometric Bottom 등각 밑면 Isometric Left 등각 왼쪽 Isometric Right 등각 오른쪽 @@ -5956,7 +6130,7 @@ lighting Light 광원 @msg each of `{GRAPHICS}` must be an object `{GRAPHICS}`의 각 항목은 개체여야 합니다 @msg `{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}` `{GRAPHICS}` 항목에는 symbol, face, x, y, scale, rotation만 사용할 수 있으며 `{k}`은(는) 사용할 수 없습니다 @msg each of `{GRAPHICS}` needs `symbol`, the name of a symbol `{GRAPHICS}`의 각 항목에는 심볼 이름인 `symbol`이 필요합니다 -@msg `{GRAPHICS}` face must be front or back `{GRAPHICS}`의 face는 front 또는 back이어야 합니다 +@msg `{GRAPHICS}` face must be front, back or side `{GRAPHICS}`의 face는 front, back 또는 side여야 합니다 @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} `{GRAPHICS}`의 {key}은(는) {lo}에서 {hi} 사이의 숫자여야 합니다 @msg `{GRAPHICS}` must be an array `{GRAPHICS}`은(는) 배열이어야 합니다 @msg Graphics map onto the Plane, Extrude and Revolve object types 그래픽은 평면, 돌출, 회전체 개체 유형에 매핑됩니다 @@ -6972,6 +7146,12 @@ anchor Points: 포인트: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode`는 "free", "keepAngles" 또는 "symmetric"이어야 합니다 @msg `{key}` must be [x, y] `{key}`은(는) [x, y]여야 합니다 +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter 단위 변환기 + Unit Converter Panel 단위 변환기 패널 + Copy with Units 단위 포함 복사 + From Selection 선택 영역에서 + # Color Effects add-on: Select by Color Kind. Select by Color Kind 색상 종류로 선택 Objects with Spot Colors 별색을 사용한 개체 @@ -7197,6 +7377,14 @@ breakText Glyphs 글리프 Remove Gaps 간격 제거 @msg that makes too many pieces (at most 100000): make the dashes longer 조각이 너무 많아집니다(최대 100000개). 대시를 더 길게 하십시오 @msg select paths, or segments, to divide 나눌 패스나 세그먼트를 선택하십시오 +# Path Precision Tools add-on: Smooth Bridge. + Smooth Bridge… 부드러운 브리지… + Smooth Bridge 부드러운 브리지 + Keep Originals 원본 유지 +@msg select two circles to bridge 연결할 원 두 개를 선택하십시오 +@msg one circle is inside the other 한 원이 다른 원 안에 있습니다 +@msg the circles are too far apart for this radius: raise the radius 이 반경에서는 원이 너무 멀리 떨어져 있습니다. 반경을 늘리십시오 +@msg the circles are too far apart for this radius 이 반경에서는 원이 너무 멀리 떨어져 있습니다 # Path Precision Tools add-on: Common Tangents. Common Tangents… 공통 접선… Common Tangents 공통 접선 @@ -7905,7 +8093,7 @@ breakText Glyphs 글리프 @msg `scale` must be a number from 0.001 to 1000 `scale`은(는) 0.001에서 1000 사이의 숫자여야 합니다 @msg `scale` must be a number in (0, 100] `scale`은(는) (0, 100] 범위의 숫자여야 합니다 @msg `scope.{key}` must be a non-empty array `scope.{key}`은(는) 비어 있지 않은 배열이어야 합니다 -@msg `scope` must be "document", {artboards} or {layers} `scope`은(는) "document", {artboards} 또는 {layers}여야 합니다 +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope`은(는) "document", {{artboards: [index, …]}} 또는 {{layers: [id, …]}}여야 합니다 @msg `scope` must be "selection" or "document", not {other} `scope`은(는) "selection" 또는 "document"여야 합니다: {other} @msg `script` must be a string `script`은(는) 문자열이어야 합니다 @msg `seriesIndexes` is a non-empty list of series indexes `seriesIndexes`은(는) 계열 인덱스가 하나 이상 있는 목록입니다 @@ -7984,6 +8172,8 @@ breakText Glyphs 글리프 @msg `{f}` is the copy of a document open now `{f}`은(는) 지금 열려 있는 문서의 복사본입니다 @msg `{id}` is no writable format (see document.formats) `{id}`은(는) 기록할 수 있는 형식이 아닙니다(document.formats 참조) @msg `{id}` isn't a loaded library `{id}`은(는) 불러온 라이브러리가 아닙니다 +@msg `{file}` has no swatches of its own `{file}`에 자체 견본이 없습니다 +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}`에 패턴 견본이 있어 .vcswatches 파일에 담을 수 없습니다 @msg `{key}` has no colours `{key}`에 색상이 없습니다 @msg `{key}` holds more than {MAX_EDIT_WORDS} words `{key}`에 단어가 {MAX_EDIT_WORDS}개보다 많습니다 @msg `{key}` is a design name `{key}`은(는) 디자인 이름입니다 @@ -8276,7 +8466,13 @@ breakText Glyphs 글리프 @msg colorModel must be {own} (the document's mode), grayscale or bitmap colorModel은 {own}(문서의 모드), grayscale 또는 bitmap이어야 합니다 @msg colour groups can't go into colour groups 색상 그룹은 색상 그룹 안에 넣을 수 없습니다 @msg colour, mode and spot apply to solid-colour swatches only colour, mode, spot은 단색 견본에만 적용됩니다 -@msg column {column}: `{cell}` is a `%` column of graph data files, which are not read {column}열: `{cell}`은(는) 그래프 데이터 파일의 `%` 열이며, 이 열은 읽지 않습니다 +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path {line}행, {column}열: `{var}`의 그래프 데이터 파일 `{path}`은(는) 상대 경로입니다. `base` 또는 절대 경로를 지정하세요 +@msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} {line}행, {column}열: `{var}`의 그래프 데이터 파일을 읽을 수 없습니다: {e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` isn't followed: {r} {line}행, {column}열: `{var}`의 그래프 데이터 파일 `{path}`을(를) 따라가지 않습니다: {r} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes {line}행, {column}열: `{var}`의 그래프 데이터 파일 `{path}`이(가) {MAX_GRAPH_DATA_FILE}바이트보다 큽니다 +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes {line}행, {column}열: `{var}`의 그래프 데이터 파일 `{path}`에서 나온 그래프 값이 {MAX_GRAPH_CSV}바이트보다 깁니다 +@msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all {line}행, {column}열: 그래프 데이터 파일이 모두 합쳐 {MAX_GRAPH_FILES_TOTAL}바이트를 넘습니다 +@msg `base` is empty `base`가 비어 있습니다 @msg column {column}: `{cell}` names `{name}`, which is a {_1} variable {column}열: `{cell}`이(가) 가리키는 `{name}`은(는) {_1} 변수입니다 @msg column {column}: `{cell}` names no variable {column}열: `{cell}`이(가) 가리키는 변수가 없습니다 @msg column {column}: the variable name is longer than {MAX_NAME} characters {column}열: 변수 이름이 {MAX_NAME}자보다 깁니다 @@ -8287,6 +8483,7 @@ breakText Glyphs 글리프 @msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes 컴파운드 모양에는 패스, 컴파운드 패스, 그룹, 컴파운드 모양, 문자, 블렌드, 엔벨로프를 넣을 수 있습니다 @msg compound {_1} must contain exactly one open path to join 컴파운드 {_1}에는 연결할 열린 패스가 정확히 하나 있어야 합니다 @msg connect needs a path other than the one extended connect에는 연장한 패스가 아닌 다른 패스가 필요합니다 +@msg connect needs extend connect에는 extend가 필요합니다 @msg connect needs id connect에는 id가 필요합니다 @msg connect path has no open end connect 패스에 열린 끝이 없습니다 @msg continuation must be an array of path chunks continuation은 패스 조각의 배열이어야 합니다 @@ -8799,7 +8996,7 @@ breakText Glyphs 글리프 @msg nothing to print: every artboard picked is blank 인쇄할 것이 없습니다: 선택한 아트보드가 모두 비어 있습니다 @msg nothing to print: the document has no art that prints 인쇄할 것이 없습니다: 문서에 인쇄되는 아트웍이 없습니다 @msg nothing to repeat 반복할 항목이 없습니다 -@msg numbers out of order in {_1} quantifier {_1} 수량자의 숫자 순서가 잘못되었습니다 +@msg numbers out of order in {{}} quantifier {{}} 수량자의 숫자 순서가 잘못되었습니다 @msg object is not a path 개체가 패스가 아닙니다 @msg object transparency cannot be sampled onto highlighted characters; disable Transparency in Eyedropper Options or select the whole object 개체 투명도는 강조 표시한 글자에 샘플링할 수 없습니다. 스포이드 옵션에서 투명도를 끄거나 개체 전체를 선택하세요 @msg object {_1} can't be set as point type 개체 {_1}은(는) 포인트 문자로 설정할 수 없습니다 @@ -9163,7 +9360,7 @@ breakText Glyphs 글리프 @msg the page has no area 페이지에 면적이 없습니다 @msg the page's type in an unread object's box isn't in its page art 읽지 않은 개체의 상자에 있는 페이지 문자가 페이지 아트웍에 없습니다 @msg the paint behind the proxy is not a gradient 프록시 뒤의 페인트가 그레이디언트가 아닙니다 -@msg the paint is not a freeform gradient (apply one with paint.editGradient {kind}) 페인트가 자유 형태 그레이디언트가 아닙니다(paint.editGradient {kind}(으)로 적용하세요) +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) 페인트가 자유 형태 그레이디언트가 아닙니다(paint.editGradient {{kind: "freeform"}}(으)로 적용하세요) @msg the parameters or body do not form one function 매개변수나 본문이 하나의 함수를 이루지 않습니다 @msg the parent must be a layer or sublayer 상위 항목은 레이어나 하위 레이어여야 합니다 @msg the pasted SVG filter {name} draws differently from the document's filter of that name, and no free name fits it 붙여넣은 SVG 필터 {name}은(는) 문서에 있는 같은 이름의 필터와 다르게 그려지며, 쓸 수 있는 빈 이름이 없습니다 @@ -9514,3 +9711,13 @@ breakText Glyphs 글리프 @msg A panel is not joined to the rest by a crease. 패널이 어떤 오시선으로도 나머지와 연결되어 있지 않습니다. @msg A fold line is on a non-printing layer. 접는 선이 인쇄되지 않는 레이어에 있습니다. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} 패널: {panels}, 힌지: {hinges}, 오류: {errors}, 경고: {warnings} + Fold Preview 접기 미리 보기 + Fold 접기 + Show Fold Lines 접는 선 표시 + Three-Quarter 3/4 보기 + Open a document to preview its folded shape. 접은 모양을 미리 보려면 문서를 여세요. +@msg Check the fold lines first. 먼저 접는 선을 검사하세요. +@msg Panels: {panels}, hinges: {hinges} 패널: {panels}, 힌지: {hinges} +@msg Other blanks not shown: {count} 표시되지 않은 다른 전개도: {count} +@msg A joint does not close by {gap} pt. 이음매가 {gap} pt만큼 닫히지 않습니다. +@msg Two panels pass through each other. 두 패널이 서로 관통합니다. diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 69aef91cfc..14cc29d30f 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -83,6 +83,27 @@ @msg Script file path exceeds 32,767 characters Het pad van het scriptbestand is langer dan 32.767 tekens @msg Script folder mask takes too many steps to match Het masker van de scriptmap vraagt te veel stappen om te vergelijken @msg the script opened more file data than one run may open (32 MiB) het script heeft meer bestandsgegevens geopend dan één uitvoering mag openen (32 MiB) +@msg Script file access denied: {path} Toegang tot het scriptbestand geweigerd: {path} +@msg Script file access to the app's own folders is not allowed Scriptbestanden mogen geen toegang krijgen tot de eigen mappen van de app +@msg Script file cannot encode the text Het scriptbestand kan de tekst niet coderen +@msg Script file could not be written Het scriptbestand kon niet worden geschreven +@msg Script file dialogs need a person to answer them Dialoogvensters voor scriptbestanden moeten door een persoon worden beantwoord +@msg Script file is not open for writing Het scriptbestand is niet geopend voor schrijven +@msg Script file name is already in use De naam van het scriptbestand is al in gebruik +@msg Script file name must be a name without a folder De naam van het scriptbestand moet een naam zonder map zijn +@msg Script file permission can be kept only for a script run from a file Toestemming voor scriptbestanden kan alleen worden bewaard voor een script dat vanuit een bestand wordt uitgevoerd +@msg Script file permission could not be saved De toestemming voor het scriptbestand kon niet worden opgeslagen +@msg Script folder is not empty De scriptmap is niet leeg +@msg Script files cannot make aliases Scriptbestanden kunnen geen aliassen maken +@msg Script file hidden setting cannot be changed De instelling Verborgen van het scriptbestand kan niet worden gewijzigd +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: een bestandsdialoogvenster kan niet worden geopend binnen een callback van een ingebouwde functie, een getter, een conversie of een bestand dat door $.evalFile wordt uitgevoerd; roep het aan vanuit de eigen code van het script +@msg the script wrote more file data than one run may write (32 MiB) het script heeft meer bestandsgegevens geschreven dan één uitvoering mag schrijven (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` voor het bestandsdialoogvenster van een script moet een van deze waarden zijn: once, always, deny, stop +@msg choose a file or folder first, or deny kies eerst een bestand of map, of weiger +@msg the script file permissions could not be saved: {e} de toestemmingen voor scriptbestanden konden niet worden opgeslagen: {e} +@msg this script's file access can be allowed only once de bestandstoegang van dit script kan maar één keer worden toegestaan +@msg Only the person at the keyboard can allow a script's file access Alleen de persoon aan het toetsenbord kan de bestandstoegang van een script toestaan +@msg A script is given at most 2,048 files: the files picked after them were left out Een script krijgt maximaal 2.048 bestanden: de bestanden die daarna zijn gekozen, zijn weggelaten @msg File.seek: takes a position and a mode File.seek: verwacht een positie en een modus @msg vc.run: give a command id, as a string vc.run: geef een opdracht-id, als string @msg vc.run: takes a command id and an object of parameters vc.run: verwacht een opdracht-id en een object met parameters @@ -192,6 +213,14 @@ liquify-list-end {0}, {1} {0} en {1} @msg the main script engine is new for each run and is never kept, so it cannot be dropped de hoofdscriptengine is bij elke uitvoering nieuw en wordt nooit bewaard, dus kan hij niet worden verwijderd @msg there is no script engine named {name} er is geen scriptengine met de naam {name} @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` is alleen voor een uitvoering zonder iemand om te vragen: in de app beantwoordt de persoon elk dialoogvenster +@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` moet een geheel getal van 1 tot {_1} zijn +@msg `args{place}` is nested more than 64 levels deep `args{place}` is meer dan 64 niveaus diep genest +@msg `args` must be an object `args` moet een object zijn +@msg `args` is larger than 1 MiB `args` is groter dan 1 MiB +@msg `path` is empty `path` is leeg +@msg `installed` takes a `path`, not a `source` `installed` neemt een `path`, geen `source` +@msg `path` must name a .js or .jsx file `path` moet een .js- of .jsx-bestand aanwijzen +@msg give exactly one of `path` and `source` geef precies een van `path` en `source` @msg Running a script Er wordt een script uitgevoerd @msg Data Recovery can't keep copies in {path}: {e} Gegevensherstel kan geen kopieën bewaren in {path}: {e} @msg Plug-ins can't be loaded from {path}: {e} Plug-ins kunnen niet worden geladen uit {path}: {e} @@ -616,6 +645,8 @@ liquify-list-end {0}, {1} {0} en {1} Check Script Script controleren Some scripts were not listed Sommige scripts zijn niet weergegeven The Scripts folder cannot be read De map Scripts kan niet worden gelezen + Loading scripts… Scripts laden… + The Scripts folder is still being read De map Scripts wordt nog gelezen Other Script… Ander script… Document Setup… Documentinstellingen… Switch Units Eenheden wisselen @@ -733,6 +764,8 @@ liquify-list-end {0}, {1} {0} en {1} Shear… Schuin zetten… Transform Each… Elk afzonderlijk transformeren… Reset Bounding Box Begrenzingskader herstellen + Rotate Bounding Box Begrenzingskader roteren + Rotate Bounding Box… Begrenzingskader roteren… Arrange Schikken Bring to Front Naar de voorgrond brengen Bring Forward Naar voren brengen @@ -1238,6 +1271,13 @@ liquify-list-end {0}, {1} {0} en {1} Previous Document Vorig document Cascade Trapsgewijs schikken Tile Naast elkaar schikken + Tile All Vertically Alles verticaal naast elkaar schikken + Tile All Horizontally Alles horizontaal naast elkaar schikken + 2-Up Layout Indeling met 2 + 3-Up Layout Indeling met 3 + 4-Up Layout Indeling met 4 + 6-Up Layout Indeling met 6 + Arrange Documents Documenten schikken Float in Window In venster zweven Float All in Windows Alles in vensters zweven Consolidate All Windows Alle vensters samenvoegen @@ -1283,6 +1323,11 @@ liquify-list-end {0}, {1} {0} en {1} Saturation and brightness Verzadiging en helderheid Color field Kleurveld {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Wielweergave + Box View Vakweergave + Box Channel Kanaal van het vak + Color box Kleurvak + Color Wheel Options Opties voor kleurenwiel CSS Properties CSS-eigenschappen Document Info Documentinfo Flattener Preview Afvlakvoorbeeld @@ -2019,6 +2064,7 @@ lighting Light Licht Play Current Selection Huidige selectie afspelen Save Actions… Acties opslaan… Load Actions… Acties laden… + Replace Actions… Acties vervangen… Reset Actions Acties opnieuw instellen Replace the current actions with the default set? De huidige acties vervangen door de standaardset? Append adds the default set after the current sets instead. Toevoegen voegt in plaats daarvan de standaardset toe na de huidige sets. @@ -2179,7 +2225,7 @@ digits Malayalam Malayalam Composite Fonts Samengestelde lettertypen Export Composite Fonts Samengestelde lettertypen exporteren Import Composite Fonts Samengestelde lettertypen importeren -@msg each font must be {name, parts} elk lettertype moet {name, parts} zijn +@msg each font must be {{name, parts}} elk lettertype moet {{name, parts}} zijn @msg unknown key `{k}`; a font takes name and parts onbekende sleutel `{k}`; een lettertype neemt name en parts @msg each font needs a name elk lettertype heeft een naam nodig @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` kan geen naam van een samengesteld lettertype zijn (1 tot {COMPOSITE_NAME_MAX} tekens, geen besturingstekens) @@ -2192,7 +2238,7 @@ digits Malayalam Malayalam @msg two composite fonts are named `{_1}` twee samengestelde lettertypen heten `{_1}` @msg `{_1}` is the name of an installed font `{_1}` is de naam van een geïnstalleerd lettertype @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2} gebruikt `{font}`, een samengesteld lettertype -@msg give fonts: [{name, parts}…] geef fonts op: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] geef fonts op: [{{name, parts}}…] @msg path is empty path is leeg @msg fonts must be a list of composite fonts fonts moet een lijst van samengestelde lettertypen zijn @msg names must be strings names moeten tekenreeksen zijn @@ -2235,6 +2281,7 @@ digits Malayalam Malayalam Underline Onderstrepen Vertical Scale % Verticale schaal % Axis As + Axis Angle Ashoek ICF Top/Right ICF boven/rechts ICF Bottom/Left ICF onder/links Show Font Height Options Opties voor letterhoogte tonen @@ -2277,6 +2324,7 @@ digits Malayalam Malayalam Rule: Regel: Save changes to {name} Wijzigingen opslaan in {name} Save theme to My Themes Thema opslaan in Mijn thema's + Set the current fill or stroke to the selected color De huidige vulling of contour op de geselecteerde kleur instellen Set the selected color to the current color De geselecteerde kleur op de huidige kleur instellen Copy All Styles Alle stijlen kopiëren Exported {path} {path} geëxporteerd @@ -2492,7 +2540,7 @@ digits Malayalam Malayalam Stroke: click for swatches, Shift-click for the color mixer Lijn: klik voor stalen, Shift-klik voor de kleurenmixer This panel is on the roadmap (see the parity plan). Dit paneel staat op de roadmap (zie het pariteitsplan). Open a document to navigate it. Open een document om erin te navigeren. - View Artboard Only Alleen tekengebied weergeven + View Artboard Contents Only Alleen inhoud van tekengebied weergeven Contextual Alternates Contextuele alternatieven Default Figure Standaardcijfer Discretionary Ligatures Optionele ligaturen @@ -2635,7 +2683,7 @@ digits Malayalam Malayalam Overprint Preview (separations) Overprintvoorbeeld (separaties) Show All Plates Alle platen weergeven Show all plates Alle platen weergeven - Show/hide plate (Alt-click: only this plate) Plaat weergeven/verbergen (Alt-klik: alleen deze plaat) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Plaat weergeven/verbergen (Alt-klik: alleen deze plaat; nogmaals Alt-klik: alle platen) Simulate Paper Papier simuleren Use Black Point Compensation Zwartpuntcompensatie gebruiken Working CMYK (don't tag) Werk-CMYK (niet taggen) @@ -2675,6 +2723,8 @@ digits Malayalam Malayalam Tip extends past the end point Punt steekt uit voorbij het eindpunt Tip on the end point Punt op het eindpunt Variable Width Profile Variabel breedteprofiel + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Het penseel van de contour behoudt zijn eigen grootte, dus een breedteprofiel verandert de contour niet. Verwijder het penseel om een profiel te gebruiken. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Het penseel van de contour behoudt zijn eigen grootte, dus een breedteprofiel verandert de contour niet. Verwijder het penseel om een profiel te gebruiken. Weight: Dikte: Art using a deleted global swatch keeps its colour. Artwork met een verwijderd globaal staal behoudt zijn kleur. Color Group: {name} Kleurgroep: {name} @@ -2784,6 +2834,10 @@ digits Malayalam Malayalam Flip Horizontal Horizontaal spiegelen Flip Vertical Verticaal spiegelen Polygon Properties: Veelhoekeigenschappen: + Line Properties: Lijneigenschappen: + Line Length: Lijnlengte: + Line Angle: Lijnhoek: + Constrain Pie Angle Taarthoek vastleggen Rectangle Properties: Rechthoekeigenschappen: Shape Properties: Vormeigenschappen: Shape Properties Vormeigenschappen @@ -2825,6 +2879,7 @@ digits Malayalam Malayalam Scatter: Verspreiding: Rotation: Rotatie: Rotation relative to: Rotatie ten opzichte van: + Hue Jitter: Tintvariatie: Brush Scale Options Opties voor penseelschaling Scale Proportionately Proportioneel schalen Stretch to Fit Stroke Length Uitrekken tot lijnlengte @@ -2863,6 +2918,7 @@ digits Malayalam Malayalam Size: Grootte: Calligraphic Brush Options Opties voor kalligrafisch penseel Bristle Brush Options Opties voor borstelpenseel + Roundness Rondheid Roundness: Rondheid: Shape: Vorm: Bristle Length: Borstellengte: @@ -3180,6 +3236,7 @@ digits Malayalam Malayalam BLANK DOCUMENT PRESETS LEGE DOCUMENTVOORINSTELLINGEN Bleed Afrulling Change to Right-to-Left Layout Omschakelen naar lay-out van rechts naar links + Columns Kolommen Columns: Kolommen: Documents you create appear here. Documenten die je maakt, verschijnen hier. More Settings Meer instellingen @@ -3313,6 +3370,9 @@ digits Malayalam Malayalam Open a document to preview its pages Open een document om een voorbeeld van de pagina's te bekijken Output › Mode Uitvoer › Modus Overprint and Transparency Flattener Options Opties voor overprint en transparantiepletter + Custom… Aangepast… + Custom Transparency Flattener Options Aangepaste opties voor transparantieafvlakking + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS heeft geen alfatransparantie, en Overdrukken bepaalt of overdrukken behouden blijven. Place the pages with the placement again Plaats de pagina's opnieuw met de plaatsing Placement: Plaatsing: Preserve CMYK Numbers CMYK-waarden behouden @@ -3362,14 +3422,19 @@ digits Malayalam Malayalam Around Object Rond object Background: Achtergrond: Changing these settings changes how raster effects look when exported, flattened or expanded. Als je deze instellingen wijzigt, verandert hoe rastereffecten eruitzien bij exporteren, pletten of uitbreiden. + Add Around Toevoegen rond object + Anti Alias Anti-aliasing + Color Model Kleurmodel Color Model: Kleurmodel: Create Clipping Mask Knipmasker maken Preserve Spot Colors Spotkleuren behouden + Resolution Resolutie Resolution: Resolutie: Transparent Transparant Layout Order: Indelingsvolgorde: Change to Left-to-Right Layout Omschakelen naar lay-out van links naar rechts Artboards: {n} Tekenborden: {n} + Rows Rijen Rows: Rijen: Assign Toewijzen Color Group: Kleurgroep: @@ -3518,6 +3583,8 @@ antiAlias Sharp Scherp Every option matches {base}. Elke optie komt overeen met {base}. Files of a PDF standard can't be password-protected. Bestanden volgens een PDF-standaard kunnen niet met een wachtwoord worden beveiligd. Files of this standard tag their colours with ICC profiles. Bestanden volgens deze standaard voorzien hun kleuren van ICC-profielen. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Bestanden volgens deze standaard voorzien hun kleuren van ICC-profielen, behalve CMYK-kleuren in het profiel voor uitvoerintentie, die als DeviceCMYK worden geschreven. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. Met ‘Geen profielen opnemen’ en een CMYK-uitvoerintentie wordt elke CMYK-kleur als DeviceCMYK geschreven, tenzij deze wordt omgezet naar een CMYK-bestemming met een ander profiel. Flattener preset: Voorinstelling voor afvlakking: General › Thumbnails Algemeen › Miniaturen Grayscale images Grijswaardenafbeeldingen @@ -3701,6 +3768,12 @@ antiAlias Sharp Scherp LF (macOS, Linux) LF (macOS, Linux) CRLF (Windows) CRLF (Windows) Text Export Options Opties tekstexport + Chinese Big 5 Chinees Big 5 + Cyrillic Cyrillisch + Greek Grieks + Turkish Turks + Baltic Baltisch + Central European Centraal-Europees Character Set: Tekenset: Join the lines of each paragraph De regels van elke alinea samenvoegen Line Breaks Regeleinden @@ -3730,6 +3803,9 @@ antiAlias Sharp Scherp Variable Options Variabeleopties Define a variable first Definieer eerst een variabele Adjust Adjoining Width Points Aangrenzende breedtepunten aanpassen + Incoming Inkomend + Outgoing Uitgaand + Single Width Only Slechts één breedte Keep both sides the same width Beide zijden dezelfde breedte houden Side 1: Zijde 1: Side 2: Zijde 2: @@ -3830,9 +3906,17 @@ theme Appearance Vormgeving Break Link to Symbol Koppeling met symbool verbreken Brush Definition Penseeldefinitie Brush Options… Penseelopties… + Options of Selected Object… Opties voor geselecteerd object… + Options of Selected Object Opties voor geselecteerd object +@msg no path painted with a brush is selected geen met een penseel geschilderd pad geselecteerd +@msg the selected paths are painted with brushes of different types de geselecteerde paden zijn geschilderd met penselen van verschillende typen +@msg give `params` or `reset`, not both geef `params` of `reset`, niet beide +@msg a bristle brush has no options of its own on a path een borstelpenseel heeft geen eigen opties op een pad Current Brush Huidig penseel Current Symbol Huidig symbool Delete Brush Penseel verwijderen + Delete Color Kleur verwijderen + Restore Generated Table Gegenereerde tabel herstellen Delete Symbol Symbool verwijderen Delete the selected symbol? Het geselecteerde symbool verwijderen? Delete the selected symbols? De geselecteerde symbolen verwijderen? @@ -4109,6 +4193,7 @@ theme Appearance Vormgeving Select Art Kunst selecteren Set Current Layer Huidige laag instellen Flatten Artwork Kunst afvlakken + Locate Layer Laag lokaliseren Locate Object Object lokaliseren Lock Others Overigen vergrendelen Merge Selected Selectie samenvoegen @@ -4285,6 +4370,7 @@ theme Appearance Vormgeving 90° & 45° Angles Hoeken van 90° & 45° 90° Angles Hoeken van 90° Additional Plug-ins Folder Extra map met plug-ins + Plug-in Instruction Budget Instructiebudget voor plug-ins Additional Fonts Folder Extra map met lettertypen Alignment Guides Uitlijnhulplijnen Anchor Points, Handle, and Bounding Box Display Weergave van ankerpunten, greep en begrenzingskader @@ -4311,6 +4397,7 @@ theme Appearance Vormgeving Data Recovery Gegevensherstel Default Language Standaardtaal Disable Auto Add/Delete Automatisch toevoegen/verwijderen uitschakelen + Interpolate Control Points When Moving Anchors Richtingsgrepen interpoleren bij het verplaatsen van ankerpunten Display All Blacks Accurately Alle zwarttinten nauwkeurig weergeven Display All Blacks as Rich Black Alle zwarttinten weergeven als rijk zwart Display Bitmaps as Anti-aliased Images in Pixel Preview Bitmaps in pixelvoorbeeld weergeven als afbeeldingen met antialiasing @@ -4327,6 +4414,7 @@ theme Appearance Vormgeving Enable Rubber Band for Rubberband inschakelen voor Enable Touch Gestures Touchgebaren inschakelen Switch Selection and Drawing Modes Wisselen tussen selectie- en tekenmodus + Select Last Selection Tool Laatst gebruikte selectiegereedschap kiezen Enable Touch Workspace Touch-werkruimte inschakelen English: UK Engels: VK Every (minutes) Elke (minuten) @@ -4398,6 +4486,9 @@ theme Appearance Vormgeving Printing / Exporting Afdrukken / exporteren Real-time Drawing and Editing Tekenen en bewerken in realtime Use Monitor Profile for Canvas Monitorprofiel gebruiken voor canvas + Refresh Monitor Profile Monitorprofiel vernieuwen +@msg turn on Use Monitor Profile for Canvas first schakel eerst 'Monitorprofiel gebruiken voor canvas' in +@msg this build doesn't read display profiles deze versie leest geen beeldschermprofielen The canvas is drawn in sRGB. Het canvas wordt in sRGB getekend. Canvas display profile: Weergaveprofiel van het canvas: The system matches the window to the display's colors. Het systeem stemt het venster af op de kleuren van het scherm. @@ -4459,6 +4550,7 @@ theme Appearance Vormgeving Scroll Sideways with Cmd/Ctrl + Wheel Horizontaal scrollen met Cmd/Ctrl + muiswiel Scrub Numeric Fields by Dragging Numerieke velden aanpassen door te slepen Linux Display Server Linux-weergaveserver + Low-Latency Drawing Tekenen met lage latentie Print Preview Afdrukvoorbeeld Print Setup Afdrukinstellingen Bitmap Bitmap @@ -4793,6 +4885,9 @@ font-technology Variable Variabel Search commands, tools, panels and effects… Opdrachten, gereedschappen, panelen en effecten zoeken… No commands match Geen opdrachten gevonden {pos} of {total}: {name} {pos} van {total}: {name} + No menu item Geen menu-item + Toolbar Gereedschapsbalk + {toolbar}, in the {tool} group {toolbar}, in de groep {tool} @plural {n} result|{n} results {n} resultaat|{n} resultaten @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} van {n} resultaat. Typ verder om ze te beperken.|{shown} van {n} resultaten. Typ verder om ze te beperken. Recent Commands Recente opdrachten @@ -4829,6 +4924,7 @@ font-technology Variable Variabel The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Het muiswiel met Cmd/Ctrl ingedrukt schuift het canvas zijwaarts. Dragging sideways on a numeric field's label changes the field's value. Zijwaarts slepen over het label van een numeriek veld wijzigt de waarde van het veld. A two-finger rotate gesture on a trackpad rotates the canvas view. Een draaigebaar met twee vingers op een trackpad draait de weergave van het canvas. + When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Als u ankerpunten verplaatst, behoudt elke curve met één verplaatst uiteinde zijn vorm ten opzichte van zijn uiteinden. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Als u de sneltoets van een gereedschap ingedrukt houdt, is dat gereedschap gekozen tot u loslaat, en daarna wordt het vorige gereedschap weer gekozen. Shows the bounding box while you move the selection or draw a shape. Toont het begrenzingskader terwijl u de selectie verplaatst of een vorm tekent. Create Trim Marks draws Japanese-style marks instead of Roman ones. Afsnijtekens maken tekent tekens in Japanse stijl in plaats van Romeinse. @@ -4859,6 +4955,29 @@ font-technology Variable Variabel The unit for East Asian type measurements, which no field uses yet. De eenheid voor maten van Oost-Aziatische tekst, die nog geen enkel veld gebruikt. When on, a number typed without a unit into a field in picas is read in points. Wanneer dit aan staat, wordt een getal dat zonder eenheid in een veld in pica's wordt getypt, in punten gelezen. With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options. Met XML-id worden objectnamen als XML-id's getoond in Lagen, Variabelen en Laagopties. + The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl. De stap voor tekstgrootte en regelafstand: Cmd/Ctrl+Shift+. en Cmd/Ctrl+Shift+, veranderen de grootte één stap, of vijf met Alt erbij; in horizontale tekst verandert Alt met de pijl omhoog of omlaag de regelafstand één stap, of vijf met Cmd/Ctrl. + The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl. De stap voor spatiëring en tekenpaarspatiëring, in duizendsten van een em: in horizontale tekst verandert Alt met de pijl links of rechts de tekenpaarspatiëring bij de cursor of de spatiëring van de geselecteerde tekst één stap, of vijf met Cmd/Ctrl. + The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. De stap voor basislijnverschuiving: in horizontale tekst verplaatsen Alt en Shift met de pijl omhoog of omlaag de basislijn één stap, of vijf met Cmd/Ctrl. + Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. Toont de opties voor Japanse en andere Oost-Aziatische tekst in de panelen Teken, Alinea, OpenType en Glyphs, en de opdracht Samengestelde lettertypen. + Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. Toont de opties voor Arabische, Hebreeuwse en Indische tekst in de panelen Teken en Alinea, zoals alinearichting, kashida's en cijfers. + The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. De selectiegereedschappen selecteren tekst alleen op de basislijn, het kader van de vlaktekst of het pad, niet overal binnen het tekstvak. + Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. Lettertypemenu's tonen elk lettertype met de Engelse naam; uitgeschakeld toont een lettertype met ook een naam in de eigen taal die naam. + New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. Nieuwe vlaktekst begint met Automatisch formaat aan, zodat een rechthoekig kader met horizontale tekst in hoogte groeit of krimpt tot de tekst past. + Font lists and the Type › Font menu show a sample of each font beside its name. Lettertypelijsten en het menu Lettertype tonen naast elke naam een voorbeeld van het lettertype. + Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on. Lettertypevoorbeelden worden in donkere tekst op wit getekend, ongeacht de helderheid van de interface; dit geldt alleen zolang voorvertoningen in menu's aan staan. + How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is. Hoe hoog elke rij is in de lijsten van lettertypevelden, zoals dat van het paneel Teken, en dus hoe groot elk voorbeeld is. + How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first. Hoeveel van de laatst gebruikte lettertypen, van 1 tot 15, Recente lettertypen en de lettertypelijsten tonen, het nieuwste eerst. + When you change the font or font style of text, characters the new font has no glyph for keep the font they had. Als u het lettertype of de letterstijl van tekst wijzigt, houden tekens waarvoor het nieuwe lettertype geen glyph heeft hun oude lettertype. + A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export. Een roze markering op het canvas toont glyphs die door OpenType-functies zijn vervangen, zoals ligaturen; ze wordt niet afgedrukt of geëxporteerd. + With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from. Met het Type-gereedschap toont het selecteren van één teken ernaast op het canvas een rij alternatieve glyphs om uit te kiezen. + A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export. Een roze markering op het canvas toont tekst in een vervangend lettertype omdat het eigen lettertype ontbreekt; ze wordt niet afgedrukt of geëxporteerd. + New type made with a Type tool starts with placeholder text, selected, so typing replaces it. Nieuwe tekst die met een tekstgereedschap wordt gemaakt, begint met geselecteerde opvultekst die uw invoer vervangt. + Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list. Een lijstteken zoals 1. of * gevolgd door een spatie aan het begin van een alinea typen maakt van de alinea een lijst. + Fonts in this folder show in the font menus and can be used without being installed. Lettertypen in deze map verschijnen in de lettertypemenu's en kunnen zonder installatie worden gebruikt. + Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows. Een grafische stijl op tekst toepassen verwijdert de eigen vulling of lijn van de tekens waar de stijl er een heeft, zodat de verf van de stijl zichtbaar is. + Align and Distribute measure point type by the ink of its glyphs instead of its em box. Uitlijnen en Verdelen meten punttekst naar de inkt van de glyphs in plaats van naar het em-vak. + Align and Distribute measure area type by the ink of its glyphs instead of its frame. Uitlijnen en Verdelen meten vlaktekst naar de inkt van de glyphs in plaats van naar het kader. + The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box. Het selectiekader en het paneel Transformeren meten punttekst naar de inkt van de glyphs in plaats van naar het em-vak. Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply. Lijnt tekenen, verplaatsen en schalen uit op de onderverdelingen van het raster, ook als het raster verborgen is; zolang dit aan staat, geldt Uitlijnen op pixel niet. The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead. De kleur van hulplijnen die niet geselecteerd zijn; een tekenbord met een hulplijnlabel tekent zijn eigen hulplijnen in de kleur van het label. Draws guides as solid lines or as dots, including the guides already in the document. Tekent hulplijnen als doorgetrokken lijnen of als stippen, ook de hulplijnen die al in het document staan. @@ -4902,6 +5021,8 @@ font-technology Variable Variabel Couldn't paste from the clipboard: {e} Kon niet vanaf het klembord plakken: {e} Channel Kanaal Circle Cirkel + Circle Tool Cirkelgereedschap + Circle too large Cirkel te groot Clip to Art Clippen op artwork Colorize Inkleuren Gamma Gamma @@ -5118,6 +5239,13 @@ imageTrace Outline Contour Show External Script Warning Waarschuwing voor externe scripts tonen A Script Is Running Er wordt een script uitgevoerd Script Alert Scriptmelding + Script File Access Bestandstoegang van script + The script asks to read a file you choose. Het script vraagt een bestand te lezen dat u kiest. + The script asks to read and write a file you choose. Het script vraagt een bestand te lezen en te schrijven dat u kiest. + The script asks to read and write a folder you choose, with everything in it. Het script vraagt een map die u kiest te lezen en te schrijven, met alles wat erin staat. + Allow Once Eenmaal toestaan + Always Allow This Script Dit script altijd toestaan + Deny Weigeren A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Een script kan de geopende documenten wijzigen en via de uitgevoerde opdrachten bestanden schrijven. Voer alleen scripts uit die u vertrouwt. Do not show this warning again Deze waarschuwing niet meer tonen Stop the script and undo what it did? Then quit again. Het script stoppen en de wijzigingen ervan ongedaan maken? Sluit daarna opnieuw af. @@ -5194,6 +5322,7 @@ imageTrace Outline Contour @msg Saved {path} {path} opgeslagen @msg Select text or click into text with the Type tool to insert glyphs Selecteer tekst of klik met het tekstgereedschap in tekst om glyphs in te voegen @msg Shape Builder: no region under the pointer Vormbouwer: geen gebied onder de aanwijzer +@msg Shape Builder: select all paths you want to merge Vormbouwer: selecteer alle paden die je wilt samenvoegen @msg Shape Builder: select paths or compound paths Vormbouwer: selecteer paden of samengestelde paden @msg Show All Hidden Attributes: nothing is hidden Alle verborgen kenmerken tonen: er is niets verborgen @msg Split Into Grid: select paths large enough for the grid In raster verdelen: selecteer paden die groot genoeg zijn voor het raster @@ -5304,6 +5433,7 @@ imageTrace Outline Contour @msg bad trailer onjuiste trailer @msg balance must be between 0 and 100 balance moet tussen 0 en 100 liggen @msg batch step {_1} (`{id}`) failed: {e} batchstap {_1} (`{id}`) is mislukt: {e} +@msg action step {_1} (`{id}`) failed: {reason} actiestap {_1} (`{id}`) is mislukt: {reason} @msg brightness must be dark|mediumDark|mediumLight|light brightness moet dark|mediumDark|mediumLight|light zijn @msg can't encode the document: {0} kan het document niet coderen: {0} @msg can't parse shortcut `{c}` kan sneltoets `{c}` niet parseren @@ -5321,6 +5451,7 @@ imageTrace Outline Contour @msg choose a folder to export to kies een map om naar te exporteren @msg choose a location for the package kies een locatie voor het pakket @msg clipboard is empty het klembord is leeg +@msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: er moet ten minste één kleur in de kleurentabel blijven @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` is geen kleur zoals "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: maximaal {MAX_TABLE} kleuren @msg command `{0}` is not available right now: {1} opdracht `{0}` is nu niet beschikbaar: {1} @@ -5375,9 +5506,15 @@ imageTrace Outline Contour @msg no PNG encoder geen PNG-encoder @msg no active document geen actief document @msg no active perspective plane geen actief perspectiefvlak +@msg the perspective grid is hidden het perspectiefraster is verborgen +@msg Automatic Plane Positioning is off: turn on anchorPoint or gridlineIntersection (perspective.widget.options) Automatische vlakpositionering staat uit: zet anchorPoint of gridlineIntersection aan (perspective.widget.options) +@msg anchorPoint must be true or false anchorPoint moet true of false zijn +@msg gridlineIntersection must be true or false gridlineIntersection moet true of false zijn +@msg tolerance must be 0 or more tolerance moet 0 of meer zijn +@msg give `at` or `clear`, not both geef `at` of `clear`, niet beide @msg no anchor points selected geen ankerpunten geselecteerd -@msg `points` must be three [x, y] pairs of numbers `points` moet uit drie getallenparen [x, y] bestaan -@msg direct-select three anchor points, or give `points` selecteer met directe selectie drie ankerpunten of geef `points` op +@msg `points` must be two or three [x, y] pairs of numbers `points` moet uit twee of drie getallenparen [x, y] bestaan +@msg direct-select two or three anchor points, or give `points` selecteer met directe selectie twee of drie ankerpunten of geef `points` op @msg no circle passes through these points: two are the same or all three lie on one line er gaat geen cirkel door deze punten: twee zijn gelijk of alle drie liggen op één lijn @msg no app to open files here hier is geen app om bestanden mee te openen @msg no artboard geen tekengebied @@ -5468,6 +5605,9 @@ imageTrace Outline Contour @msg no such user library gebruikersbibliotheek bestaat niet @msg no such view weergave bestaat niet @msg no such width point breedtepunt bestaat niet +@msg `single` must be `incoming` or `outgoing` `single` moet `incoming` of `outgoing` zijn +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` en `outIndex` moeten de twee helften van één onderbroken breedtepunt zijn +@msg a discontinuous width point keeps its place een onderbroken breedtepunt behoudt zijn plaats @msg no swatch `{name}` geen staal `{name}` @msg no swatch library `{l}` (see swatch.library.list) geen stalenbibliotheek `{l}` (zie swatch.library.list) @msg no symbol instances selected geen symboolinstanties geselecteerd @@ -5705,6 +5845,8 @@ imageTrace Outline Contour @msg {label}: lost track of a shape's style {label}: de stijl van een vorm is kwijtgeraakt @msg {label}: select paths {label}: selecteer paden @msg {label}: select paths, compound paths, groups or text {label}: selecteer paden, samengestelde paden, groepen of tekst +@msg a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first een lijn of ander open pad dat geen oppervlak omsluit, verandert de vorm van het resultaat niet; pas er eerst Object › Pad › Contour omzetten op toe om het op te nemen +@msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first {label} leverde een leeg resultaat op: een lijn of ander open pad omsluit geen oppervlak; pas er eerst Object › Pad › Contour omzetten op toe om het op te nemen @msg {label}… {label}… @msg {name}: CRC mismatch {name}: CRC komt niet overeen @msg {name}: no local header {name}: geen lokale header @@ -5731,6 +5873,9 @@ imageTrace Outline Contour @msgplural Discarded {n} recovered document|Discarded {n} recovered documents {n} hersteld document verworpen|{n} herstelde documenten verworpen @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them {n} hersteld document teruggezet: sla het op om het te behouden|{n} herstelde documenten teruggezet: sla ze op om ze te behouden @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} Geopend met {n} opmerking: {first}|Geopend met {n} opmerkingen: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Gekopieerd met {n} opmerking: {first}|Gekopieerd met {n} opmerkingen: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Geknipt met {n} opmerking: {first}|Geknipt met {n} opmerkingen: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Afbeelding getraceerd met {n} opmerking: {first}|Afbeelding getraceerd met {n} opmerkingen: {first} @msgplural {notice}. Opened with {n} note: {first}|{notice}. Opened with {n} notes: {first} {notice}. Geopend met {n} opmerking: {first}|{notice}. Geopend met {n} opmerkingen: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} {path} opgeslagen met {n} opmerking: {first}|{path} opgeslagen met {n} opmerkingen: {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first {n} afbeelding ingesloten; {missing} ontbreken: koppel ze eerst opnieuw|{n} afbeeldingen ingesloten; {missing} ontbreken: koppel ze eerst opnieuw @@ -5757,6 +5902,8 @@ imageTrace Outline Contour @msg All colors are within the CMYK gamut Alle kleuren vallen binnen het CMYK-gamut @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} kleur valt buiten het CMYK-gamut|{n} kleuren vallen buiten het CMYK-gamut @msg Unembedded to {_1} Extern gemaakt: {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} {n} afbeelding extern gemaakt in {folder}|{n} afbeeldingen extern gemaakt in {folder} +@msg every numbered name for {name} is taken in that folder elke genummerde naam voor {name} is al vergeven in die map @msg Reset {_1} {_1} opnieuw ingesteld @msg Sent to {_1} Verzonden naar {_1} @msg {_1} files {_1}-bestanden @@ -5770,6 +5917,8 @@ imageTrace Outline Contour @msg Reload the page to go on (changes not saved yet may be lost). Laad de pagina opnieuw om door te gaan (nog niet opgeslagen wijzigingen kunnen verloren gaan). @msg tool (a tool id) is required tool (een gereedschaps-id) is vereist @msg {tool} isn't in a toolbar group of several tools {tool} zit niet in een werkbalkgroep met meerdere gereedschappen +@msg Presentation Mode hides the toolbars: change the screen mode to show them Presentatiemodus verbergt de werkbalken: wijzig de schermmodus om ze te tonen +@msg Tab has hidden the toolbars: press Tab to show them Tab heeft de werkbalken verborgen: druk op Tab om ze te tonen @msg onto must name a panel floating in another group onto moet een zwevend paneel in een andere groep benoemen @msg below and above must name a panel floating in another group below en above moeten een zwevend paneel in een andere groep benoemen @msg give only one of onto, below and above geef slechts één van onto, below en above @@ -6149,7 +6298,7 @@ imageTrace Outline Contour @msg `scale` must be a number from 0.001 to 1000 `scale` moet een getal van 0,001 tot 1000 zijn @msg `scale` must be a number in (0, 100] `scale` moet een getal in (0, 100] zijn @msg `scope.{key}` must be a non-empty array `scope.{key}` moet een niet-lege array zijn -@msg `scope` must be "document", {artboards} or {layers} `scope` moet "document", {artboards} of {layers} zijn +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` moet "document", {{artboards: [index, …]}} of {{layers: [id, …]}} zijn @msg `scope` must be "selection" or "document", not {other} `scope` moet "selection" of "document" zijn, niet {other} @msg `script` must be a string `script` moet een string zijn @msg `seriesIndexes` is a non-empty list of series indexes `seriesIndexes` is een niet-lege lijst met reeksindexen @@ -6228,6 +6377,8 @@ imageTrace Outline Contour @msg `{f}` is the copy of a document open now `{f}` is de kopie van een document dat nu geopend is @msg `{id}` is no writable format (see document.formats) `{id}` is geen schrijfbare indeling (zie document.formats) @msg `{id}` isn't a loaded library `{id}` is geen geladen bibliotheek +@msg `{file}` has no swatches of its own `{file}` heeft geen eigen stalen +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` heeft patroonstalen, die een .vcswatches-bestand niet kan bevatten @msg `{key}` has no colours `{key}` heeft geen kleuren @msg `{key}` holds more than {MAX_EDIT_WORDS} words `{key}` bevat meer dan {MAX_EDIT_WORDS} woorden @msg `{key}` is a design name `{key}` is de naam van een ontwerp @@ -6340,6 +6491,8 @@ imageTrace Outline Contour @msg a legend draws at most {MAX_CHIPS} swatches een legenda tekent maximaal {MAX_CHIPS} stalen @msg a linked JavaScript file is outside the read roots een gekoppeld JavaScript-bestand staat buiten de leesroots @msg a linked image file is outside the read roots een gekoppeld afbeeldingsbestand staat buiten de leesroots +@msg a linked file's export folder is outside the read roots de exportmap van een gekoppeld bestand staat buiten de leesroots +@msg a linked file's editing data can't be read to check it against the read roots de bewerkingsgegevens van een gekoppeld bestand kunnen niet worden gelezen om ze aan de leesroots te toetsen @msg a name names one asset: give multiple: false, or one object een naam noemt één asset: geef multiple: false, of één object @msg a namespace declaration uses a reserved prefix or URI een naamruimtedeclaratie gebruikt een gereserveerd voorvoegsel of een gereserveerde URI @msg a namespace qualifier is undefined een naamruimtekwalificatie is niet gedefinieerd @@ -6522,7 +6675,13 @@ imageTrace Outline Contour @msg colorModel must be {own} (the document's mode), grayscale or bitmap colorModel moet {own} (de modus van het document), grayscale of bitmap zijn @msg colour groups can't go into colour groups kleurgroepen kunnen niet in kleurgroepen worden geplaatst @msg colour, mode and spot apply to solid-colour swatches only colour, mode en spot gelden alleen voor stalen met een effen kleur -@msg column {column}: `{cell}` is a `%` column of graph data files, which are not read kolom {column}: `{cell}` is een `%`-kolom van grafiekgegevensbestanden, die niet worden gelezen +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path regel {line}, kolom {column}: het grafiekgegevensbestand `{path}` voor `{var}` is een relatief pad: geef `base` of een absoluut pad op +@msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} regel {line}, kolom {column}: het grafiekgegevensbestand voor `{var}` kan niet worden gelezen: {e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` isn't followed: {r} regel {line}, kolom {column}: het grafiekgegevensbestand `{path}` voor `{var}` wordt niet gevolgd: {r} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes regel {line}, kolom {column}: het grafiekgegevensbestand `{path}` voor `{var}` is groter dan {MAX_GRAPH_DATA_FILE} bytes +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes regel {line}, kolom {column}: het grafiekgegevensbestand `{path}` voor `{var}` geeft een grafiekwaarde langer dan {MAX_GRAPH_CSV} bytes +@msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all regel {line}, kolom {column}: de grafiekgegevensbestanden bevatten samen meer dan {MAX_GRAPH_FILES_TOTAL} bytes +@msg `base` is empty `base` is leeg @msg column {column}: `{cell}` names `{name}`, which is a {_1} variable kolom {column}: `{cell}` noemt `{name}`, en dat is een variabele van het type {_1} @msg column {column}: `{cell}` names no variable kolom {column}: `{cell}` noemt geen variabele @msg column {column}: the variable name is longer than {MAX_NAME} characters kolom {column}: de naam van de variabele is langer dan {MAX_NAME} tekens @@ -6533,6 +6692,7 @@ imageTrace Outline Contour @msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes samengestelde vormen accepteren paden, samengestelde paden, groepen, samengestelde vormen, tekst, mengsels en omvormingen @msg compound {_1} must contain exactly one open path to join samengesteld object {_1} moet precies één open pad bevatten om te verbinden @msg connect needs a path other than the one extended connect heeft een ander pad nodig dan het pad dat wordt verlengd +@msg connect needs extend connect heeft extend nodig @msg connect needs id connect heeft id nodig @msg connect path has no open end het pad van connect heeft geen open uiteinde @msg continuation must be an array of path chunks continuation moet een array van padstukken zijn @@ -7045,7 +7205,7 @@ imageTrace Outline Contour @msg nothing to print: every artboard picked is blank niets om af te drukken: elk gekozen tekengebied is leeg @msg nothing to print: the document has no art that prints niets om af te drukken: het document heeft geen illustraties die worden afgedrukt @msg nothing to repeat niets om te herhalen -@msg numbers out of order in {_1} quantifier getallen in de verkeerde volgorde in kwantor {_1} +@msg numbers out of order in {{}} quantifier getallen in de verkeerde volgorde in kwantor {{}} @msg object is not a path het object is geen pad @msg object transparency cannot be sampled onto highlighted characters; disable Transparency in Eyedropper Options or select the whole object objecttransparantie kan niet op gemarkeerde tekens worden overgenomen; schakel Transparantie uit in Opties voor pipet of selecteer het hele object @msg object {_1} can't be set as point type object {_1} kan niet als punttekst worden gezet @@ -7410,7 +7570,7 @@ imageTrace Outline Contour @msg the page has no area de pagina heeft geen oppervlak @msg the page's type in an unread object's box isn't in its page art de tekst van de pagina in het kader van een ongelezen object zit niet in de pagina-illustratie ervan @msg the paint behind the proxy is not a gradient de verf achter de proxy is geen verloop -@msg the paint is not a freeform gradient (apply one with paint.editGradient {kind}) de verf is geen verloop in vrije vorm (pas er een toe met paint.editGradient {kind}) +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) de verf is geen verloop in vrije vorm (pas er een toe met paint.editGradient {{kind: "freeform"}}) @msg the parameters or body do not form one function de parameters of de body vormen niet één functie @msg the parent must be a layer or sublayer het bovenliggende item moet een laag of sublaag zijn @msg the pasted SVG filter {name} draws differently from the document's filter of that name, and no free name fits it het geplakte SVG-filter {name} tekent anders dan het filter met die naam in het document, en er is geen vrije naam die past @@ -7937,6 +8097,7 @@ imageTrace Outline Contour Ascent Stijghoogte Cap Height Kaphoogte x Height x-hoogte + Em Box Height Em-vakhoogte Justify Uitvullen First Baseline Eerste basislijn Vertical Align Verticaal uitlijnen @@ -8044,6 +8205,7 @@ mark-style Japanese Japans Cove Cove Depth Diepte Front Voorkant + Side Zijkant Isometric Bottom Isometrisch onder Isometric Left Isometrisch links Isometric Right Isometrisch rechts @@ -8138,7 +8300,7 @@ mark-style Japanese Japans @msg each of `{GRAPHICS}` must be an object elk item van `{GRAPHICS}` moet een object zijn @msg `{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}` items van `{GRAPHICS}` nemen symbol, face, x, y, scale en rotation aan, niet `{k}` @msg each of `{GRAPHICS}` needs `symbol`, the name of a symbol elk item van `{GRAPHICS}` heeft `symbol` nodig, de naam van een symbool -@msg `{GRAPHICS}` face must be front or back face in `{GRAPHICS}` moet front of back zijn +@msg `{GRAPHICS}` face must be front, back or side face in `{GRAPHICS}` moet front, back of side zijn @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} in `{GRAPHICS}` moet een getal van {lo} tot {hi} zijn @msg `{GRAPHICS}` must be an array `{GRAPHICS}` moet een array zijn @msg Graphics map onto planar faces: use the Extrude or Plane object type Illustraties worden op platte vlakken geplaatst: gebruik het objecttype Extruderen of Vlak @@ -8343,6 +8505,8 @@ mark-style Japanese Japans Reset Tracking and Kerning Tracking en kerning herstellen Reset Horizontal Scale Horizontale schaal herstellen Highlight Font Name Lettertypenaam markeren + Highlight Font Size Lettertypegrootte markeren + Other… Andere… Highlight Kerning Kerning markeren Highlight Tracking Tracking markeren @msg span must be "object" or "selection", got {v} span moet "object" of "selection" zijn, maar is {v} @@ -8404,6 +8568,11 @@ mark-style Japanese Japans Edge Only Alleen rand Overlay Edge Rand bedekken Path Length Padlengte + Grid Size Rastergrootte + Grid Colors Rasterkleuren + Flattener Preset Voorinstelling voor afvlakking + X X + Y Y @msg the file's layers weren't read ({_1}): it comes in as its page, in one layer de lagen van het bestand zijn niet ingelezen ({_1}): het komt binnen als zijn pagina, in één laag @msg the file's layers weren't read from its editing data ({_1}): they come from its PDF part de lagen van het bestand zijn niet ingelezen uit de bewerkingsgegevens ({_1}): ze komen uit het PDF-gedeelte @msg the file's variable bindings weren't all read (bindings skipped: {_1}): those objects aren't bound to their variables niet alle variabelekoppelingen van het bestand zijn ingelezen (overgeslagen koppelingen: {_1}): die objecten zijn niet aan hun variabelen gekoppeld @@ -8411,6 +8580,8 @@ mark-style Japanese Japans @msg the file's variable library couldn't be read: the Variables panel doesn't list it de variabelenbibliotheek van het bestand kan niet worden ingelezen: het Variabelen-paneel toont die niet @msg a variable of unknown kind can't be bound to objects een variabele van onbekend type kan niet aan objecten worden gekoppeld @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` moet grayscale, rgb, hsb, cmyk of websafe zijn +@msg `view` must be wheel or box `view` moet wheel of box zijn +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` moet hue, saturation, brightness, red, green of blue zijn @msg the Color Picker is not open de kleurenkiezer is niet open @msg the screen color sampler is already open de schermkleurkiezer is al open @msg this system has no screen color sampler dit systeem heeft geen schermkleurkiezer @@ -8745,6 +8916,13 @@ swatch Bright Violet Felviolet @msg the spine has no segments de as heeft geen segmenten @msg variables are locked variabelen zijn vergrendeld @msg variables that aren't text were left out: {kinds} variabelen die geen tekst zijn, zijn weggelaten: {kinds} +variable-kind Visibility Zichtbaarheid +variable-kind Linked File Gekoppeld bestand +variable-kind Graph Data Diagramgegevens +variable-kind Unknown Onbekend +variable-list-two {0}, {1} {0} en {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} en {1} @msg a new document won't read these variables back with their kind: {names} een nieuw document leest deze variabelen niet terug met hun soort: {names} @msg a new document refuses this file because of these variables: {names} een nieuw document weigert dit bestand vanwege deze variabelen: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them de kop `{header}` voor `{name}` zou worden gelezen als de variabele `{other}`: wijzig de naam van een van beide @@ -9285,6 +9463,12 @@ anchor Points: Punten: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` moet "free", "keepAngles" of "symmetric" zijn @msg `{key}` must be [x, y] `{key}` moet [x, y] zijn +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Eenhedenomrekenaar + Unit Converter Panel Deelvenster Eenhedenomrekenaar + Copy with Units Kopiëren met eenheden + From Selection Uit selectie + # Color Effects add-on: Select by Color Kind. Select by Color Kind Selecteren op kleursoort Objects with Spot Colors Objecten met steunkleuren @@ -9486,6 +9670,14 @@ breakText Glyphs Glyphs Remove Gaps Tussenruimten verwijderen @msg that makes too many pieces (at most 100000): make the dashes longer dat geeft te veel stukken (hoogstens 100000): maak de streepjes langer @msg select paths, or segments, to divide selecteer paden of segmenten om te verdelen +# Path Precision Tools add-on: Smooth Bridge. + Smooth Bridge… Vloeiende brug… + Smooth Bridge Vloeiende brug + Keep Originals Originelen behouden +@msg select two circles to bridge selecteer twee cirkels om te verbinden +@msg one circle is inside the other de ene cirkel ligt binnen de andere +@msg the circles are too far apart for this radius: raise the radius de cirkels liggen te ver uit elkaar voor deze straal: vergroot de straal +@msg the circles are too far apart for this radius de cirkels liggen te ver uit elkaar voor deze straal # Path Precision Tools add-on: Common Tangents. Common Tangents… Gemeenschappelijke raaklijnen… Common Tangents Gemeenschappelijke raaklijnen @@ -9953,3 +10145,13 @@ breakText Glyphs Glyphs @msg A panel is not joined to the rest by a crease. Een paneel is door geen rillijn met de rest verbonden. @msg A fold line is on a non-printing layer. Een vouwlijn staat op een laag die niet wordt afgedrukt. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panelen: {panels}, scharnieren: {hinges}, fouten: {errors}, waarschuwingen: {warnings} + Fold Preview Vouwvoorbeeld + Fold Vouwen + Show Fold Lines Vouwlijnen tonen + Three-Quarter Driekwart + Open a document to preview its folded shape. Open een document om de gevouwen vorm te bekijken. +@msg Check the fold lines first. Controleer eerst de vouwlijnen. +@msg Panels: {panels}, hinges: {hinges} Panelen: {panels}, scharnieren: {hinges} +@msg Other blanks not shown: {count} Andere uitslagen niet getoond: {count} +@msg A joint does not close by {gap} pt. Een naad sluit {gap} pt niet. +@msg Two panels pass through each other. Twee panelen gaan door elkaar heen. diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 0147515ffe..aeec776910 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -137,6 +137,8 @@ Shear… Pochyl… Transform Each… Przekształć każdy… Reset Bounding Box Resetuj obwiednię + Rotate Bounding Box Obróć obwiednię + Rotate Bounding Box… Obróć obwiednię… Arrange Ułóż Bring to Front Przenieś na wierzch Bring Forward Przesuń do przodu @@ -676,6 +678,13 @@ Previous Document Poprzedni dokument Cascade Kaskadowo Tile Sąsiadująco + Tile All Vertically Wszystkie sąsiadująco w pionie + Tile All Horizontally Wszystkie sąsiadująco w poziomie + 2-Up Layout Układ po 2 + 3-Up Layout Układ po 3 + 4-Up Layout Układ po 4 + 6-Up Layout Układ po 6 + Arrange Documents Rozmieść dokumenty Float in Window Pływające w oknie Float All in Windows Wszystkie pływające w oknach Consolidate All Windows Scal wszystkie okna @@ -714,6 +723,11 @@ Saturation and brightness Nasycenie i jasność Color field Pole koloru {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Widok koła + Box View Widok kwadratu + Box Channel Kanał kwadratu + Color box Kwadrat koloru + Color Wheel Options Opcje koła kolorów CSS Properties Właściwości CSS Document Info Informacje o dokumencie Flattener Preview Podgląd spłaszczania @@ -1460,6 +1474,7 @@ lighting Light Światło Play Current Selection Odtwórz bieżące zaznaczenie Save Actions… Zapisz operacje… Load Actions… Wczytaj operacje… + Replace Actions… Zastąp operacje… Reset Actions Resetuj operacje Replace the current actions with the default set? Zastąpić bieżące operacje zestawem domyślnym? Append adds the default set after the current sets instead. Dołącz dodaje zamiast tego zestaw domyślny po bieżących zestawach. @@ -1620,7 +1635,7 @@ digits Malayalam Malajalam Composite Fonts Fonty złożone Export Composite Fonts Eksportuj fonty złożone Import Composite Fonts Importuj fonty złożone -@msg each font must be {name, parts} każdy font musi mieć postać {name, parts} +@msg each font must be {{name, parts}} każdy font musi mieć postać {{name, parts}} @msg unknown key `{k}`; a font takes name and parts nieznany klucz `{k}`; font przyjmuje name i parts @msg each font needs a name każdy font musi mieć nazwę @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` nie może być nazwą fontu złożonego (od 1 do {COMPOSITE_NAME_MAX} znaków, bez znaków sterujących) @@ -1633,7 +1648,7 @@ digits Malayalam Malajalam @msg two composite fonts are named `{_1}` dwa fonty złożone mają nazwę `{_1}` @msg `{_1}` is the name of an installed font `{_1}` to nazwa zainstalowanego fontu @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2} używa `{font}`, który jest fontem złożonym -@msg give fonts: [{name, parts}…] podaj fonts: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] podaj fonts: [{{name, parts}}…] @msg path is empty path jest puste @msg fonts must be a list of composite fonts fonts musi być listą fontów złożonych @msg names must be strings names muszą być ciągami znaków @@ -1676,6 +1691,7 @@ digits Malayalam Malajalam Underline Podkreślenie Vertical Scale % Skala pionowa % Axis Oś + Axis Angle Kąt osi ICF Top/Right ICF góra/prawo ICF Bottom/Left ICF dół/lewo Show Font Height Options Pokaż opcje wysokości czcionki @@ -1718,6 +1734,7 @@ digits Malayalam Malajalam Rule: Reguła: Save changes to {name} Zapisz zmiany w {name} Save theme to My Themes Zapisz motyw w Moich motywach + Set the current fill or stroke to the selected color Ustaw bieżące wypełnienie lub obrys na zaznaczony kolor Set the selected color to the current color Ustaw zaznaczony kolor na bieżący Copy All Styles Kopiuj wszystkie style Exported {path} Wyeksportowano {path} @@ -2038,7 +2055,7 @@ digits Malayalam Malajalam Stroke: click for swatches, Shift-click for the color mixer Obrys: kliknij, aby wybrać próbkę, z Shift — mikser kolorów This panel is on the roadmap (see the parity plan). Ten panel jest w planach (patrz plan zgodności). Open a document to navigate it. Otwórz dokument, aby się po nim poruszać. - View Artboard Only Pokaż tylko obszar kompozycji + View Artboard Contents Only Pokaż tylko zawartość obszaru kompozycji Contextual Alternates Alternatywy kontekstowe Default Figure Cyfry domyślne Discretionary Ligatures Ligatury opcjonalne @@ -2188,7 +2205,7 @@ digits Malayalam Malajalam Overprint Preview (separations) Podgląd nadruku (rozbarwienia) Show All Plates Pokaż wszystkie płyty Show all plates Pokaż wszystkie płyty - Show/hide plate (Alt-click: only this plate) Pokaż/ukryj płytę (kliknięcie z Alt: tylko ta płyta) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Pokaż/ukryj płytę (kliknięcie z Alt: tylko ta płyta; ponowne kliknięcie z Alt: wszystkie płyty) Simulate Paper Symuluj papier Use Black Point Compensation Użyj kompensacji punktu czerni Working CMYK (don't tag) Roboczy CMYK (bez znacznika) @@ -2228,11 +2245,13 @@ digits Malayalam Malajalam Tip extends past the end point Czubek wystaje poza punkt końcowy Tip on the end point Czubek na punkcie końcowym Variable Width Profile Profil zmiennej szerokości + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Pędzel obrysu zachowuje własny rozmiar, więc profil szerokości go nie zmienia. Usuń pędzel, aby użyć profilu. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Pędzel obrysu zachowuje własny rozmiar, więc profil szerokości go nie zmienia. Usuń pędzel, aby użyć profilu. Weight: Grubość: Art using a deleted global swatch keeps its colour. Kompozycja używająca usuniętej próbki globalnej zachowa swój kolor. Color Group: {name} Grupa kolorów: {name} - Delete the selected items and their artwork? Usunąć zaznaczone elementy razem z grafiką? - Delete this layer and its artwork? Usunąć tę warstwę razem z grafiką? + Delete the selected items and their artwork? Usunąć zaznaczone elementy razem z kompozycją? + Delete this layer and its artwork? Usunąć tę warstwę razem z kompozycją? Delete “{name}”? Usunąć „{name}”? Document Swatches Próbki dokumentu Edit or Apply Color Group Edytuj lub zastosuj grupę kolorów @@ -2338,6 +2357,10 @@ digits Malayalam Malajalam Flip Horizontal Odbij w poziomie Flip Vertical Odbij w pionie Polygon Properties: Właściwości wielokąta: + Line Properties: Właściwości linii: + Line Length: Długość linii: + Line Angle: Kąt linii: + Constrain Pie Angle Zachowaj kąt wycinka Rectangle Properties: Właściwości prostokąta: Shape Properties: Właściwości kształtu: Shape Properties Właściwości kształtu @@ -2378,6 +2401,7 @@ digits Malayalam Malajalam Scatter: Rozproszenie: Rotation: Obrót: Rotation relative to: Obrót względem: + Hue Jitter: Zmienność barwy: Brush Scale Options Opcje skali pędzla Scale Proportionately Skaluj proporcjonalnie Stretch to Fit Stroke Length Rozciągnij do długości obrysu @@ -2416,6 +2440,7 @@ digits Malayalam Malajalam Size: Rozmiar: Calligraphic Brush Options Opcje pędzla kaligraficznego Bristle Brush Options Opcje pędzla włosiankowego + Roundness Okrągłość Roundness: Okrągłość: Shape: Kształt: Bristle Length: Długość włosia: @@ -2670,7 +2695,7 @@ digits Malayalam Malajalam Consider Open Filled Paths as Closed Traktuj otwarte wypełnione ścieżki jako zamknięte In Merge Mode, Clicking Stroke Splits the Path W trybie scalania kliknięcie obrysu dzieli ścieżkę Pick Color From: Źródło koloru: - Artwork Grafika + Artwork Kompozycja Cursor Swatch Preview Podgląd próbek przy kursorze Selection: Zaznaczanie: Straight Line Linia prosta @@ -2747,6 +2772,7 @@ digits Malayalam Malajalam BLANK DOCUMENT PRESETS USTAWIENIA PUSTEGO DOKUMENTU Bleed Spad Change to Right-to-Left Layout Zmień na układ od prawej do lewej + Columns Kolumny Columns: Kolumny: Documents you create appear here. Tu pojawią się utworzone dokumenty. More Settings Więcej ustawień @@ -2879,6 +2905,9 @@ digits Malayalam Malajalam Open a document to preview its pages Otwórz dokument, aby podejrzeć jego strony Output › Mode Wyjście › Tryb Overprint and Transparency Flattener Options Opcje nadruku i spłaszczania przezroczystości + Custom… Niestandardowe… + Custom Transparency Flattener Options Niestandardowe opcje spłaszczania przezroczystości + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS nie ma przezroczystości alfa, a Nadruki określają, czy nadruki są zachowywane. Place the pages with the placement again Ponownie rozmieść strony według położenia Placement: Położenie: Preserve CMYK Numbers Zachowaj wartości CMYK @@ -2927,14 +2956,19 @@ digits Malayalam Malajalam Around Object Wokół obiektu Background: Tło: Changing these settings changes how raster effects look when exported, flattened or expanded. Zmiana tych ustawień zmienia wygląd efektów rastrowych po eksporcie, spłaszczeniu lub rozszerzeniu. + Add Around Dodaj wokół obiektu + Anti Alias Wygładzanie + Color Model Model kolorów Color Model: Model kolorów: Create Clipping Mask Utwórz maskę przycinającą Preserve Spot Colors Zachowaj kolory dodatkowe + Resolution Rozdzielczość Resolution: Rozdzielczość: Transparent Przezroczyste Layout Order: Kolejność układu: Change to Left-to-Right Layout Zmień na układ od lewej do prawej Artboards: {n} Obszary kompozycji: {n} + Rows Wiersze Rows: Wiersze: Assign Przypisz Color Group: Grupa kolorów: @@ -3061,6 +3095,8 @@ antiAlias Sharp Ostre Every option matches {base}. Wszystkie opcje są zgodne z {base}. Files of a PDF standard can't be password-protected. Plików standardu PDF nie można chronić hasłem. Files of this standard tag their colours with ICC profiles. Pliki tego standardu oznaczają kolory profilami ICC. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Pliki tego standardu oznaczają kolory profilami ICC, z wyjątkiem kolorów CMYK w profilu docelowych warunków wyjściowych, które są zapisywane jako DeviceCMYK. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. Przy opcji „Nie dołączaj profili” i docelowych warunkach wyjściowych CMYK każdy kolor CMYK jest zapisywany jako DeviceCMYK, chyba że zostanie przekonwertowany do miejsca docelowego CMYK z innym profilem. Flattener preset: Ustawienie spłaszczania: General › Thumbnails Ogólne › Miniatury Grayscale images Obrazy w skali szarości @@ -3237,7 +3273,7 @@ antiAlias Sharp Ostre Export Preset: Ustawienie eksportu: Folders: Foldery: Insert Wstaw - Nothing is selected. Select the art to export, then open this tab again. Nic nie zaznaczono. Zaznacz grafikę do eksportu i ponownie otwórz tę kartę. + Nothing is selected. Select the art to export, then open this tab again. Nic nie zaznaczono. Zaznacz kompozycję do eksportu i ponownie otwórz tę kartę. One File of the Selection Jeden plik z zaznaczenia Start at: Zacznij od: {n} objects selected Zaznaczone obiekty: {n} @@ -3271,6 +3307,12 @@ antiAlias Sharp Ostre Encoding: Kodowanie: Line Endings: Znaki końca wiersza: Text Export Options Opcje eksportu tekstu + Chinese Big 5 Chiński Big 5 + Cyrillic Cyrylica + Greek Grecki + Turkish Turecki + Baltic Bałtycki + Central European Środkowoeuropejski Character Set: Zestaw znaków: Join the lines of each paragraph Połącz wiersze każdego akapitu Line Breaks Podziały wierszy @@ -3300,6 +3342,9 @@ antiAlias Sharp Ostre Variable Options Opcje zmiennej Define a variable first Najpierw zdefiniuj zmienną Adjust Adjoining Width Points Dopasuj sąsiednie punkty szerokości + Incoming Wejściowa + Outgoing Wyjściowa + Single Width Only Tylko jedna szerokość Keep both sides the same width Zachowaj jednakową szerokość obu stron Side 1: Strona 1: Side 2: Strona 2: @@ -3411,9 +3456,17 @@ theme Appearance Wygląd Break Link to Symbol Zerwij łącze z symbolem Brush Definition Definicja pędzla Brush Options… Opcje pędzla… + Options of Selected Object… Opcje zaznaczonego obiektu… + Options of Selected Object Opcje zaznaczonego obiektu +@msg no path painted with a brush is selected nie zaznaczono ścieżki malowanej pędzlem +@msg the selected paths are painted with brushes of different types zaznaczone ścieżki są malowane pędzlami różnych typów +@msg give `params` or `reset`, not both podaj `params` albo `reset`, nie oba +@msg a bristle brush has no options of its own on a path pędzel włosiankowy nie ma własnych opcji na ścieżce Current Brush Bieżący pędzel Current Symbol Bieżący symbol Delete Brush Usuń pędzel + Delete Color Usuń kolor + Restore Generated Table Przywróć wygenerowaną tablicę Delete Symbol Usuń symbol Delete the selected symbol? Usunąć zaznaczony symbol? Delete the selected symbols? Usunąć zaznaczone symbole? @@ -3541,6 +3594,13 @@ theme Appearance Wygląd Objects Obiekty Paths Ścieżki Path Length Długość ścieżek + Grid Size Rozmiar siatki + Grid Colors Kolory siatki + Flattener Preset Ustawienie spłaszczania + X X + Y Y + Orange Pomarańczowy + Purple Fioletowy Add Guide Dodaj linię pomocniczą Edit Selection Edytuj zaznaczenie Recall Selection Przywołaj zaznaczenie @@ -3692,6 +3752,7 @@ theme Appearance Wygląd Select Art Zaznacz kompozycję Set Current Layer Ustaw bieżącą warstwę Flatten Artwork Spłaszcz kompozycję + Locate Layer Znajdź warstwę Locate Object Znajdź obiekt Lock Others Zablokuj pozostałe Merge Selected Scal zaznaczone @@ -3866,6 +3927,7 @@ theme Appearance Wygląd 90° & 45° Angles Kąty 90° i 45° 90° Angles Kąty 90° Additional Plug-ins Folder Dodatkowy folder wtyczek + Plug-in Instruction Budget Budżet instrukcji wtyczek Additional Fonts Folder Dodatkowy folder czcionek Alignment Guides Linie wyrównania Anchor Points, Handle, and Bounding Box Display Wyświetlanie punktów kontrolnych, uchwytów i obwiedni @@ -3892,6 +3954,7 @@ theme Appearance Wygląd Data Recovery Odzyskiwanie danych Default Language Język domyślny Disable Auto Add/Delete Wyłącz automatyczne dodawanie/usuwanie + Interpolate Control Points When Moving Anchors Interpoluj uchwyty kierunkowe podczas przesuwania punktów kontrolnych Display All Blacks Accurately Wyświetlaj wszystkie czernie dokładnie Display All Blacks as Rich Black Wyświetlaj wszystkie czernie jako czerń głęboką Display Bitmaps as Anti-aliased Images in Pixel Preview Wyświetlaj bitmapy wygładzone w podglądzie pikseli @@ -3908,6 +3971,7 @@ theme Appearance Wygląd Enable Rubber Band for Włącz gumkę podglądu dla Enable Touch Gestures Włącz gesty dotykowe Switch Selection and Drawing Modes Przełącz tryby zaznaczania i rysowania + Select Last Selection Tool Wybierz ostatnie narzędzie zaznaczania Enable Touch Workspace Włącz dotykowy obszar roboczy English: UK Angielski: Wielka Brytania Every (minutes) Co (minuty) @@ -3979,6 +4043,9 @@ theme Appearance Wygląd Printing / Exporting Drukowanie / eksportowanie Real-time Drawing and Editing Rysowanie i edycja w czasie rzeczywistym Use Monitor Profile for Canvas Użyj profilu monitora dla płótna + Refresh Monitor Profile Odśwież profil monitora +@msg turn on Use Monitor Profile for Canvas first najpierw włącz „Użyj profilu monitora dla płótna” +@msg this build doesn't read display profiles ta wersja nie odczytuje profili wyświetlaczy The canvas is drawn in sRGB. Płótno jest rysowane w sRGB. Canvas display profile: Profil wyświetlacza płótna: The system matches the window to the display's colors. System dopasowuje okno do kolorów wyświetlacza. @@ -4040,6 +4107,7 @@ theme Appearance Wygląd Scroll Sideways with Cmd/Ctrl + Wheel Przewijaj w poziomie kółkiem z Cmd/Ctrl Scrub Numeric Fields by Dragging Zmieniaj pola liczbowe przeciąganiem Linux Display Server Serwer wyświetlania Linux + Low-Latency Drawing Rysowanie z niskim opóźnieniem Print Preview Podgląd wydruku Print Setup Ustawienia wydruku Bitmap Bitmapa @@ -4227,6 +4295,8 @@ axis Both Obie Reset Tracking and Kerning Resetuj światło i kerning Reset Horizontal Scale Resetuj skalę poziomą Highlight Font Name Wyróżnij nazwę czcionki + Highlight Font Size Wyróżnij rozmiar czcionki + Other… Inny… Highlight Kerning Wyróżnij kerning Highlight Tracking Wyróżnij światło Step Type Krok tekstu @@ -4361,6 +4431,9 @@ font-technology Variable Zmienne Search commands, tools, panels and effects… Szukaj poleceń, narzędzi, paneli i efektów… No commands match Żadne polecenie nie pasuje {pos} of {total}: {name} {pos} z {total}: {name} + No menu item Brak pozycji menu + Toolbar Pasek narzędzi + {toolbar}, in the {tool} group {toolbar}, w grupie {tool} @plural {n} result|{n} results {n} wynik|{n} wyniki|{n} wyników @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} z {n} wyniku. Pisz dalej, aby je zawęzić.|{shown} z {n} wyników. Pisz dalej, aby je zawęzić.|{shown} z {n} wyników. Pisz dalej, aby je zawęzić. Recent Commands Ostatnie polecenia @@ -4384,23 +4457,24 @@ font-technology Variable Zmienne Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. Narzędzia do rysowania pokazują wskaźnik w kształcie krzyżyka zamiast swojej ikony; Caps Lock działa tak samo, dopóki jest włączony. Shows a tip when the pointer rests on a button or field that has one. Pokazuje wskazówkę, gdy wskaźnik zatrzyma się na przycisku lub polu, które ją ma. Shows a warning before a script you choose runs. Pokazuje ostrzeżenie przed uruchomieniem wybranego skryptu. - Smooths the edges of artwork on the canvas. Wygładza krawędzie grafiki na obszarze roboczym. + Smooths the edges of artwork on the canvas. Wygładza krawędzie kompozycji na obszarze roboczym. Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Zaznacz › Taki sam › Kolor wypełnienia, Kolor obrysu oraz Wypełnienie i obrys dopasowują tylko ten sam odcień globalnej lub dodatkowej próbki, a nie dowolny jej odcień. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Pokazuje stronę startową, gdy nie jest otwarty żaden dokument; po wyłączeniu okno pozostaje puste, dopóki nie klikniesz Strona startowa. Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Mierzy obiekty razem z obrysami i efektami zmieniającymi kształt na potrzeby rozmiaru, położenia i wyrównania; cienie, poświaty i rozmycia nie są mierzone. At 100% zoom, one inch of the document takes 96 screen points instead of 72. Przy powiększeniu 100% jeden cal dokumentu zajmuje 96 punktów ekranu zamiast 72. Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Dwukrotne kliknięcie grupy, ścieżki lub obrazu narzędziem Zaznaczanie otwiera je w trybie izolacji. - Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Wypełnienia i obrysy wzorkiem przekształcają się razem z grafiką, chyba że przekształcenie lub menu panelu Przekształć wybierze inaczej. - Live corner radii scale with the art, unless the scale chooses otherwise. Promienie narożników dynamicznych skalują się razem z grafiką, chyba że skalowanie wybierze inaczej. - Stroke weights, dashes and effect distances scale with the art, unless the scale chooses otherwise. Grubości obrysów, kreski i odległości efektów skalują się razem z grafiką, chyba że skalowanie wybierze inaczej. + Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Wypełnienia i obrysy wzorkiem przekształcają się razem z kompozycją, chyba że przekształcenie lub menu panelu Przekształć wybierze inaczej. + Live corner radii scale with the art, unless the scale chooses otherwise. Promienie narożników dynamicznych skalują się razem z kompozycją, chyba że skalowanie wybierze inaczej. + Stroke weights, dashes and effect distances scale with the art, unless the scale chooses otherwise. Grubości obrysów, kreski i odległości efektów skalują się razem z kompozycją, chyba że skalowanie wybierze inaczej. The mouse wheel zooms the canvas instead of scrolling it. Kółko myszy powiększa obszar roboczy zamiast go przewijać. The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Kółko myszy z wciśniętym Cmd/Ctrl przewija obszar roboczy w poziomie. Dragging sideways on a numeric field's label changes the field's value. Przeciąganie w bok po etykiecie pola liczbowego zmienia wartość pola. A two-finger rotate gesture on a trackpad rotates the canvas view. Gest obrotu dwoma palcami na gładziku obraca widok obszaru roboczego. + When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Podczas przesuwania punktów kontrolnych każda krzywa z jednym przesuniętym końcem zachowuje kształt względem swoich końców. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Przytrzymanie skrótu narzędzia wybiera je do momentu puszczenia klawisza, a potem ponownie wybierane jest poprzednie narzędzie. Shows the bounding box while you move the selection or draw a shape. Pokazuje obwiednię podczas przesuwania zaznaczenia lub rysowania kształtu. Create Trim Marks draws Japanese-style marks instead of Roman ones. Utwórz znaczniki przycięcia rysuje znaczniki w stylu japońskim zamiast rzymskich. - New art takes only the fill and stroke of the selection; off, it takes the selected object's whole appearance. Nowa grafika przejmuje tylko wypełnienie i obrys zaznaczenia; po wyłączeniu przejmuje cały wygląd zaznaczonego obiektu. + New art takes only the fill and stroke of the selection; off, it takes the selected object's whole appearance. Nowa kompozycja przejmuje tylko wypełnienie i obrys zaznaczenia; po wyłączeniu przejmuje cały wygląd zaznaczonego obiektu. Changing the width or height in the Transform panel, the Properties panel or the Control bar changes the other in proportion. Zmiana szerokości lub wysokości w panelu Przekształć, panelu Właściwości lub panelu Sterowanie proporcjonalnie zmienia drugi wymiar. A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. Właściwości dynamicznego prostokąta pokazują jedno pole Promień narożnika dla wszystkich czterech narożników; po wyłączeniu każdy narożnik ma własne pole. What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. Co przekształcają zmiany w panelu Przekształć: obiekt, kafelki jego wzorka lub oba; Domyślne podąża za opcją Przekształcaj kafelki wzorków. @@ -4413,7 +4487,7 @@ font-technology Variable Zmienne How near, in pixels, a point must come to an anchor or ruler guide for Snap to Point to snap it; with Smart Guides on, Smart Guides' Snapping Tolerance applies instead. Jak blisko, w pikselach, punkt musi podejść do punktu kontrolnego lub linii pomocniczej linijki, aby Przyciągaj do punktów go przyciągnęło; przy włączonych inteligentnych liniach pomocniczych obowiązuje ich tolerancja przyciągania. With the Selection tool, Cmd/Ctrl-click selects the object under the selected one at the pointer; each further click goes one object deeper. Z narzędziem Zaznaczanie Cmd/Ctrl+kliknięcie zaznacza obiekt pod zaznaczonym w miejscu wskaźnika; każde kolejne kliknięcie schodzi o jeden obiekt głębiej. Zoom In and Zoom Out bring the center of the selection to the middle of the view. Powiększ i Pomniejsz przenoszą środek zaznaczenia na środek widoku. - Locked and hidden artwork inside an artboard moves, scales and is copied with the artboard, as the other artwork does. Zablokowana i ukryta grafika wewnątrz obszaru kompozycji jest przesuwana, skalowana i kopiowana razem z nim, tak jak pozostała grafika. + Locked and hidden artwork inside an artboard moves, scales and is copied with the artboard, as the other artwork does. Zablokowana i ukryta kompozycja wewnątrz obszaru kompozycji jest przesuwana, skalowana i kopiowana razem z nim, tak jak pozostała kompozycja. The size of anchor points and direction handle ends on the canvas; larger anchors can also be picked from farther away. Rozmiar punktów kontrolnych i końców uchwytów kierunkowych na obszarze roboczym; większe punkty kontrolne można chwycić także z większej odległości. Draws the ends of direction handles as solid dots, hollow dots or larger solid dots. Rysuje końce uchwytów kierunkowych jako pełne kropki, puste kropki lub większe pełne kropki. With the Direct Selection tool, the anchor under the pointer is highlighted. Z narzędziem Zaznaczanie bezpośrednie punkt kontrolny pod wskaźnikiem jest wyróżniany. @@ -4427,6 +4501,29 @@ font-technology Variable Zmienne The unit for East Asian type measurements, which no field uses yet. Jednostka miar tekstu wschodnioazjatyckiego, której żadne pole jeszcze nie używa. When on, a number typed without a unit into a field in picas is read in points. Gdy opcja jest włączona, liczba wpisana bez jednostki w polu w pica jest odczytywana w punktach. With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options. Przy ID XML nazwy obiektów są wyświetlane jako ID XML w Warstwach, Zmiennych i Opcjach warstwy. + The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl. Krok rozmiaru tekstu i interlinii: Cmd/Ctrl+Shift+. i Cmd/Ctrl+Shift+, zmieniają rozmiar o jeden krok, a z Alt o pięć; w tekście poziomym Alt ze strzałką w górę lub w dół zmienia interlinię o jeden krok, a z Cmd/Ctrl o pięć. + The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl. Krok światła i kerningu, w tysięcznych częściach em: w tekście poziomym Alt ze strzałką w lewo lub w prawo zmienia kerning przy kursorze lub światło zaznaczonego tekstu o jeden krok, a z Cmd/Ctrl o pięć. + The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. Krok przesunięcia linii bazowej: w tekście poziomym Alt i Shift ze strzałką w górę lub w dół przesuwają linię bazową o jeden krok, a z Cmd/Ctrl o pięć. + Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. Pokazuje opcje tekstu japońskiego i innego wschodnioazjatyckiego w panelach Znak, Akapit, OpenType i Glify oraz polecenie Fonty złożone. + Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. Pokazuje opcje tekstu arabskiego, hebrajskiego i indyjskiego w panelach Znak i Akapit, takie jak kierunek akapitu, kaszidy i cyfry. + The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. Narzędzia zaznaczania zaznaczają tekst tylko na jego linii bazowej, ramce tekstu w obszarze lub jego ścieżce, a nie w dowolnym miejscu jego obwiedni. + Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. Menu czcionek pokazują każdą czcionkę pod angielską nazwą; po wyłączeniu czcionka, która ma też nazwę we własnym języku, pokazuje tę nazwę. + New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. Nowy tekst w obszarze zaczyna z włączonym automatycznym rozmiarem, więc prostokątna ramka tekstu poziomego rośnie lub maleje w pionie, by zmieścić tekst. + Font lists and the Type › Font menu show a sample of each font beside its name. Listy czcionek i menu Czcionka pokazują obok nazwy próbkę każdej czcionki. + Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on. Próbki czcionek są rysowane ciemnym tekstem na białym tle niezależnie od jasności interfejsu; działa to tylko przy włączonych podglądach czcionek w menu. + How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is. Wysokość każdego wiersza na listach pól czcionek, na przykład w panelu Znak, a więc i wielkość każdej próbki. + How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first. Ile ostatnio używanych czcionek, od 1 do 15, pokazują Ostatnie czcionki i listy czcionek, od najnowszej. + When you change the font or font style of text, characters the new font has no glyph for keep the font they had. Gdy zmienisz czcionkę lub styl czcionki tekstu, znaki, dla których nowa czcionka nie ma glifu, zachowują dotychczasową czcionkę. + A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export. Różowe wyróżnienie na obszarze roboczym oznacza glify zastąpione przez funkcje OpenType, takie jak ligatury; nie jest drukowane ani eksportowane. + With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from. W narzędziu Tekst zaznaczenie jednego znaku pokazuje obok niego na obszarze roboczym rząd jego alternatywnych glifów do wyboru. + A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export. Różowe wyróżnienie na obszarze roboczym oznacza tekst rysowany czcionką zastępczą, bo brakuje jego czcionki; nie jest drukowane ani eksportowane. + New type made with a Type tool starts with placeholder text, selected, so typing replaces it. Nowy tekst utworzony narzędziem tekstowym zaczyna się od zaznaczonego tekstu zastępczego, którego miejsce zajmuje wpisywany tekst. + Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list. Wpisanie znacznika listy, takiego jak 1. lub *, a potem spacji na początku akapitu zmienia akapit w listę. + Fonts in this folder show in the font menus and can be used without being installed. Czcionki z tego folderu są widoczne w menu czcionek i można ich używać bez instalowania. + Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows. Zastosowanie stylu graficznego do tekstu usuwa własne wypełnienie lub obrys znaków tam, gdzie styl je ma, więc widać farbę stylu. + Align and Distribute measure point type by the ink of its glyphs instead of its em box. Wyrównaj i Rozmieść mierzą tekst punktowy według tuszu jego glifów zamiast jego kwadratu em. + Align and Distribute measure area type by the ink of its glyphs instead of its frame. Wyrównaj i Rozmieść mierzą tekst w obszarze według tuszu jego glifów zamiast jego ramki. + The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box. Obwiednia i panel Przekształć mierzą tekst punktowy według tuszu jego glifów zamiast jego kwadratu em. Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply. Przyciąga rysowanie, przesuwanie i skalowanie do podpodziałów siatki, nawet gdy siatka jest ukryta; dopóki jest włączone, Przyciągaj do pikseli nie działa. The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead. Kolor niezaznaczonych linii pomocniczych; obszar kompozycji z Etykietą linii pomocniczych rysuje własne linie pomocnicze w kolorze etykiety. Draws guides as solid lines or as dots, including the guides already in the document. Rysuje linie pomocnicze jako linie ciągłe lub kropki, także te, które już są w dokumencie. @@ -4436,22 +4533,22 @@ font-technology Variable Zmienne Draws the grid as lines, or as dots along the major gridlines at each subdivision. Rysuje siatkę jako linie albo jako kropki wzdłuż głównych linii siatki przy każdym podpodziale. The distance between major gridlines, in every open document and in new ones; a VectorCraft document opens with the grid it was saved with. Odstęp między głównymi liniami siatki w każdym otwartym dokumencie i w nowych; dokument VectorCraft otwiera się z siatką, z którą został zapisany. How many parts each major grid square is divided into; Snap to Grid snaps to these parts, even when the zoom hides their lines. Na ile części dzieli się każdy główny kwadrat siatki; Przyciągaj do siatki przyciąga do tych części, nawet gdy powiększenie ukrywa ich linie. - Draws the grid behind the artwork; off, the grid is drawn over it. Rysuje siatkę za grafiką; po wyłączeniu siatka jest rysowana na niej. - In Pixel Preview at 600% zoom or more, the active view shows a line at the edge of every document pixel over the artwork. W Podglądzie pikseli przy powiększeniu 600% lub większym aktywny widok pokazuje nad grafiką linię na krawędzi każdego piksela dokumentu. + Draws the grid behind the artwork; off, the grid is drawn over it. Rysuje siatkę za kompozycją; po wyłączeniu siatka jest rysowana na niej. + In Pixel Preview at 600% zoom or more, the active view shows a line at the edge of every document pixel over the artwork. W Podglądzie pikseli przy powiększeniu 600% lub większym aktywny widok pokazuje nad kompozycją linię na krawędzi każdego piksela dokumentu. The color of the tile edge and the dashed swatch bounds shown while you edit a pattern. Kolor krawędzi kafelka i przerywanych granic próbki widocznych podczas edycji wzorka. - Snaps drawing, moving and transforming to nearby art and shows guides and labels; Pixel Preview turns them off, and Snap to Grid snaps to the grid instead. Przyciąga rysowanie, przesuwanie i przekształcanie do pobliskiej grafiki oraz pokazuje linie pomocnicze i etykiety; Podgląd pikseli je wyłącza, a Przyciągaj do siatki przyciąga zamiast nich do siatki. + Snaps drawing, moving and transforming to nearby art and shows guides and labels; Pixel Preview turns them off, and Snap to Grid snaps to the grid instead. Przyciąga rysowanie, przesuwanie i przekształcanie do pobliskiej kompozycji oraz pokazuje linie pomocnicze i etykiety; Podgląd pikseli je wyłącza, a Przyciągaj do siatki przyciąga zamiast nich do siatki. The color of Smart Guide lines and labels. Kolor linii i etykiet inteligentnych linii pomocniczych. - Shows a line along the edge or center that art lines up with; off, art still lines up without the line, and Snap to Glyph does not apply. Pokazuje linię wzdłuż krawędzi lub środka, do których wyrównuje się grafika; po wyłączeniu grafika nadal się wyrównuje bez linii, a Przyciągaj do glifów nie działa. + Shows a line along the edge or center that art lines up with; off, art still lines up without the line, and Snap to Glyph does not apply. Pokazuje linię wzdłuż krawędzi lub środka, do których wyrównuje się kompozycja; po wyłączeniu kompozycja nadal się wyrównuje bez linii, a Przyciągaj do glifów nie działa. With a selection tool, outlines the unselected object under the pointer in its layer color while you are not dragging. Przy narzędziu zaznaczania obrysowuje niezaznaczony obiekt pod wskaźnikiem kolorem jego warstwy, dopóki nie przeciągasz. - Shows the size or angle next to the pointer while you scale, rotate, shear or reflect art. Pokazuje rozmiar lub kąt obok wskaźnika podczas skalowania, obracania, pochylania lub odbijania grafiki. + Shows the size or angle next to the pointer while you scale, rotate, shear or reflect art. Pokazuje rozmiar lub kąt obok wskaźnika podczas skalowania, obracania, pochylania lub odbijania kompozycji. While you draw, points snap to lines at the chosen Angles through the point the segment or shape starts from. Podczas rysowania punkty przyciągają się do linii pod wybranymi kątami przechodzących przez punkt, od którego zaczyna się segment lub kształt. The set of angles the construction guides follow while Construction Guides is on. Zestaw kątów, wzdłuż których biegną linie konstrukcyjne, gdy Linie konstrukcyjne są włączone. Names what a point snaps to, such as an anchor, a path or an alignment; off, points snap the same way without the names. Nazywa to, do czego przyciąga się punkt, np. punkt kontrolny, ścieżkę lub wyrównanie; po wyłączeniu punkty przyciągają się tak samo, bez nazw. - Shows distances, angles and how far art has moved next to the pointer while you draw or move it. Pokazuje obok wskaźnika odległości, kąty i to, o ile przesunęła się grafika, podczas rysowania lub przesuwania. - Snaps moved or resized art to the same gap as between nearby objects, and marks the equal gaps. Przyciąga przesuniętą grafikę lub grafikę o zmienionym rozmiarze do takiego samego odstępu jak między pobliskimi obiektami i zaznacza równe odstępy. + Shows distances, angles and how far art has moved next to the pointer while you draw or move it. Pokazuje obok wskaźnika odległości, kąty i to, o ile przesunęła się kompozycja, podczas rysowania lub przesuwania. + Snaps moved or resized art to the same gap as between nearby objects, and marks the equal gaps. Przyciąga przesuniętą kompozycję lub kompozycję o zmienionym rozmiarze do takiego samego odstępu jak między pobliskimi obiektami i zaznacza równe odstępy. With something selected, holding Alt/Option over another object or an artboard shows the distances between it and the selection. Gdy coś jest zaznaczone, przytrzymanie Alt/Option nad innym obiektem lub obszarem kompozycji pokazuje odległości między nim a zaznaczeniem. A selection dragged back to within the Snapping Tolerance of where the drag began goes back to exactly that place; a copy does not. Zaznaczenie przeciągnięte z powrotem na odległość tolerancji przyciągania od miejsca, w którym zaczęło się przeciąganie, wraca dokładnie w to miejsce; kopia nie. - How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. Jak blisko na ekranie wskaźnik lub przeciągany punkt musi znaleźć się przy grafice, aby inteligentne linie pomocnicze go przyciągnęły; odległość jest taka sama przy każdym powiększeniu. + How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. Jak blisko na ekranie wskaźnik lub przeciągany punkt musi znaleźć się przy kompozycji, aby inteligentne linie pomocnicze go przyciągnęły; odległość jest taka sama przy każdym powiększeniu. Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. Przyciąga koniec odcinka lub okrąg rysowany od środka tak, aby dotykał pobliskiej krzywej. Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. Przyciąga koniec odcinka tak, aby spotykał pobliski prosty segment pod kątem prostym. Reset all preferences to their defaults? Przywrócić domyślne wartości wszystkich preferencji? @@ -4470,6 +4567,8 @@ font-technology Variable Zmienne Couldn't paste from the clipboard: {e} Nie udało się wkleić ze schowka: {e} Channel Kanał Circle Okrąg + Circle Tool Narzędzie Okrąg + Circle too large Okrąg jest za duży Clip to Art Przytnij do kompozycji Colorize Koloruj Gamma Gamma @@ -4687,6 +4786,13 @@ imageTrace Outline Kontur Show External Script Warning Pokazuj ostrzeżenie o skryptach zewnętrznych A Script Is Running Skrypt jest uruchomiony Script Alert Komunikat skryptu + Script File Access Dostęp skryptu do plików + The script asks to read a file you choose. Skrypt prosi o odczyt wybranego przez Ciebie pliku. + The script asks to read and write a file you choose. Skrypt prosi o odczyt i zapis wybranego przez Ciebie pliku. + The script asks to read and write a folder you choose, with everything in it. Skrypt prosi o odczyt i zapis wybranego przez Ciebie folderu wraz z całą jego zawartością. + Allow Once Zezwól raz + Always Allow This Script Zawsze zezwalaj temu skryptowi + Deny Odmów A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Skrypt może zmieniać otwarte dokumenty i zapisywać pliki za pomocą wykonywanych poleceń. Uruchamiaj tylko skrypty, którym ufasz. Do not show this warning again Nie pokazuj więcej tego ostrzeżenia Stop the script and undo what it did? Then quit again. Zatrzymać skrypt i cofnąć jego zmiany? Następnie zakończ program ponownie. @@ -4703,6 +4809,8 @@ imageTrace Outline Kontur @msg the script is no longer in the Scripts folder skryptu nie ma już w folderze Scripts Some scripts were not listed Niektóre skrypty nie zostały wyświetlone The Scripts folder cannot be read Nie można odczytać folderu Scripts + Loading scripts… Wczytywanie skryptów… + The Scripts folder is still being read Folder Scripts jest nadal odczytywany @msg the script's run is no longer available uruchomienie skryptu nie jest już dostępne @msg a failed command changed undo steps that could not be put back, so the script was stopped nieudane polecenie zmieniło kroki cofania, których nie udało się przywrócić, więc skrypt został zatrzymany @msg a recovery copy could not be written, so the script was not run nie udało się zapisać kopii odzyskiwania, więc skrypt nie został uruchomiony @@ -4715,8 +4823,6 @@ imageTrace Outline Kontur @msg Script file could not be read Nie udało się odczytać pliku skryptu @msg Script folder has more than 2,048 entries Folder skryptu ma więcej niż 2048 pozycji @msg Script file open mode must be r, w, e or a Tryb otwarcia pliku skryptu musi być r, w, e lub a -@msg Script file writing is not available Zapisywanie plików skryptu jest niedostępne -@msg Script file dialogs are not available Okna dialogowe plików skryptu są niedostępne @msg Script files cannot be opened in another application Plików skryptu nie można otworzyć w innej aplikacji @msg Script file access is unavailable on the web Dostęp do plików skryptu jest niedostępny w przeglądarce @msg Script has 256 files open Skrypt ma otwartych 256 plików @@ -4833,6 +4939,27 @@ liquify-list-end {0}, {1} {0} i {1} @msg there is no script engine named {name} nie ma silnika skryptów o nazwie {name} @msg Running a script Uruchamianie skryptu @msg Copied the script report Skopiowano raport skryptu +@msg Script file access denied: {path} Odmówiono skryptowi dostępu do plików: {path} +@msg Script file access to the app's own folders is not allowed Skrypt nie ma dostępu do własnych folderów aplikacji +@msg Script file cannot encode the text Plik skryptu nie może zakodować tekstu +@msg Script file could not be written Nie można zapisać pliku skryptu +@msg Script file dialogs need a person to answer them Okna dialogowe plików skryptu wymagają osoby, która na nie odpowie +@msg Script file is not open for writing Plik skryptu nie jest otwarty do zapisu +@msg Script file name is already in use Nazwa pliku skryptu jest już używana +@msg Script file name must be a name without a folder Nazwa pliku skryptu musi być nazwą bez folderu +@msg Script file permission can be kept only for a script run from a file Uprawnienie do plików można zachować tylko dla skryptu uruchomionego z pliku +@msg Script file permission could not be saved Nie można zapisać uprawnienia skryptu do plików +@msg Script folder is not empty Folder skryptu nie jest pusty +@msg Script files cannot make aliases Pliki skryptu nie mogą tworzyć aliasów +@msg Script file hidden setting cannot be changed Nie można zmienić ustawienia ukrycia pliku skryptu +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: okna dialogowego plików nie można otworzyć w wywołaniu zwrotnym funkcji wbudowanej, gettera, konwersji ani pliku uruchamianego przez $.evalFile; wywołaj je z własnego kodu skryptu +@msg the script wrote more file data than one run may write (32 MiB) skrypt zapisał więcej danych plików, niż może zapisać jedno uruchomienie (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` dla okna dialogowego plików skryptu musi być jedną z wartości: once, always, deny, stop +@msg choose a file or folder first, or deny najpierw wybierz plik lub folder albo odmów +@msg the script file permissions could not be saved: {e} nie można zapisać uprawnień skryptów do plików: {e} +@msg this script's file access can be allowed only once na dostęp tego skryptu do plików można zezwolić tylko raz +@msg Only the person at the keyboard can allow a script's file access Na dostęp skryptu do plików może zezwolić tylko osoba przy klawiaturze +@msg A script is given at most 2,048 files: the files picked after them were left out Skrypt otrzymuje najwyżej 2 048 plików: pliki wybrane po nich zostały pominięte @msg Copied the link info Skopiowano informacje o łączu @msg Corners edits the corners of a path Narożniki edytuje narożniki ścieżki @msg Couldn't copy to the system clipboard: {e} Nie udało się skopiować do schowka systemowego: {e} @@ -4908,6 +5035,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg Saved {path} Zapisano {path} @msg Select text or click into text with the Type tool to insert glyphs Zaznacz tekst lub kliknij w tekst narzędziem Tekst, aby wstawić glify @msg Shape Builder: no region under the pointer Kreator kształtów: brak obszaru pod wskaźnikiem +@msg Shape Builder: select all paths you want to merge Kreator kształtów: zaznacz wszystkie ścieżki, które chcesz scalić @msg Shape Builder: select paths or compound paths Kreator kształtów: zaznacz ścieżki lub ścieżki złożone @msg Show All Hidden Attributes: nothing is hidden Pokaż wszystkie ukryte atrybuty: nic nie jest ukryte @msg Split Into Grid: select paths large enough for the grid Podziel na siatkę: zaznacz ścieżki wystarczająco duże dla siatki @@ -4962,6 +5090,8 @@ liquify-list-end {0}, {1} {0} i {1} @msg `{min_key}` is greater than `{max_key}` `{min_key}` jest większe niż `{max_key}` @msg give at least one of `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` podaj co najmniej jeden z parametrów `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` musi mieć wartość grayscale, rgb, hsb, cmyk lub websafe +@msg `view` must be wheel or box `view` musi mieć wartość wheel lub box +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` musi mieć wartość hue, saturation, brightness, red, green lub blue @msg `{k}` must be [x, y] `{k}` musi mieć postać [x, y] @msg `{name}` has no options `{name}` nie ma opcji @msg `{name}` is a built-in workspace; choose another name `{name}` to wbudowany obszar roboczy; wybierz inną nazwę @@ -5050,6 +5180,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg bad trailer nieprawidłowa sekcja trailer @msg balance must be between 0 and 100 balance musi mieścić się w zakresie od 0 do 100 @msg batch step {_1} (`{id}`) failed: {e} krok wsadowy {_1} (`{id}`) nie powiódł się: {e} +@msg action step {_1} (`{id}`) failed: {reason} krok operacji {_1} (`{id}`) nie powiódł się: {reason} @msg brightness must be dark|mediumDark|mediumLight|light brightness musi mieć wartość dark|mediumDark|mediumLight|light @msg can't encode the document: {0} nie można zakodować dokumentu: {0} @msg can't parse shortcut `{c}` nie można przeanalizować skrótu `{c}` @@ -5063,12 +5194,13 @@ liquify-list-end {0}, {1} {0} i {1} @msg check an asset to export zaznacz zasób do eksportu @msg check an artboard to export zaznacz obszar kompozycji do eksportu @msg check a layer to export zaznacz warstwę do eksportu -@msg select the art to export first najpierw zaznacz grafikę do eksportu +@msg select the art to export first najpierw zaznacz kompozycję do eksportu @msg choice must be "merge" or "add", not `{choice}` wybór musi mieć wartość "merge" lub "add", nie `{choice}` @msg choose a direction to divide in wybierz kierunek podziału @msg choose a folder to export to wybierz folder docelowy eksportu @msg choose a location for the package wybierz lokalizację pakietu @msg clipboard is empty schowek jest pusty +@msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: w tablicy kolorów musi zostać co najmniej jeden kolor @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` nie jest kolorem w rodzaju "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: maksymalnie {MAX_TABLE} kolorów @msg command `{0}` is not available right now: {1} polecenie `{0}` jest teraz niedostępne: {1} @@ -5136,9 +5268,15 @@ liquify-list-end {0}, {1} {0} i {1} @msg no PNG encoder brak kodera PNG @msg no active document brak aktywnego dokumentu @msg no active perspective plane brak aktywnej płaszczyzny perspektywy +@msg the perspective grid is hidden siatka perspektywy jest ukryta +@msg Automatic Plane Positioning is off: turn on anchorPoint or gridlineIntersection (perspective.widget.options) Automatyczne pozycjonowanie płaszczyzny jest wyłączone: włącz anchorPoint lub gridlineIntersection (perspective.widget.options) +@msg anchorPoint must be true or false anchorPoint musi mieć wartość true lub false +@msg gridlineIntersection must be true or false gridlineIntersection musi mieć wartość true lub false +@msg tolerance must be 0 or more tolerance musi wynosić 0 lub więcej +@msg give `at` or `clear`, not both podaj `at` albo `clear`, nie oba naraz @msg no anchor points selected nie zaznaczono punktów kontrolnych -@msg `points` must be three [x, y] pairs of numbers `points` musi zawierać trzy pary liczb [x, y] -@msg direct-select three anchor points, or give `points` zaznacz bezpośrednio trzy punkty kontrolne lub podaj `points` +@msg `points` must be two or three [x, y] pairs of numbers `points` musi zawierać dwie lub trzy pary liczb [x, y] +@msg direct-select two or three anchor points, or give `points` zaznacz bezpośrednio dwa lub trzy punkty kontrolne lub podaj `points` @msg no circle passes through these points: two are the same or all three lie on one line przez te punkty nie przechodzi żaden okrąg: dwa są takie same albo wszystkie trzy leżą na jednej prostej @msg no app to open files here brak aplikacji do otwierania plików @msg no artboard brak obszaru kompozycji @@ -5240,6 +5378,9 @@ liquify-list-end {0}, {1} {0} i {1} @msg no such user library brak takiej biblioteki użytkownika @msg no such view brak takiego widoku @msg no such width point brak takiego punktu szerokości +@msg `single` must be `incoming` or `outgoing` `single` musi mieć wartość `incoming` lub `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` i `outIndex` muszą być dwiema połówkami jednego nieciągłego punktu szerokości +@msg a discontinuous width point keeps its place nieciągły punkt szerokości zachowuje swoje położenie @msg no swatch `{name}` brak próbki `{name}` @msg no swatch library `{l}` (see swatch.library.list) brak biblioteki próbek `{l}` (patrz swatch.library.list) @msg no symbol instances selected nie zaznaczono wystąpień symboli @@ -5501,6 +5642,13 @@ liquify-list-end {0}, {1} {0} i {1} @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} więcej niż {MAX_CSV_ROWS} zestawów danych: Importuj zestawy danych odczytuje najwyżej {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} więcej niż {MAX_CSV_COLS} zmiennych: Importuj zestawy danych odczytuje najwyżej {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} pominięto zmienne, które nie są tekstowe: {kinds} +variable-kind Visibility Widoczność +variable-kind Linked File Połączony plik +variable-kind Graph Data Dane wykresu +variable-kind Unknown Nieznany +variable-list-two {0}, {1} {0} i {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} i {1} @msg a new document won't read these variables back with their kind: {names} nowy dokument nie odczyta tych zmiennych z ich rodzajem: {names} @msg a new document refuses this file because of these variables: {names} nowy dokument odrzuca ten plik z powodu tych zmiennych: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them nagłówek `{header}` dla `{name}` zostałby odczytany jako zmienna `{other}`: zmień nazwę jednej z nich @@ -5526,6 +5674,8 @@ liquify-list-end {0}, {1} {0} i {1} @msg {label}: lost track of a shape's style {label}: utracono informację o stylu kształtu @msg {label}: select paths {label}: zaznacz ścieżki @msg {label}: select paths, compound paths, groups or text {label}: zaznacz ścieżki, ścieżki złożone, grupy lub tekst +@msg a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first linia lub inna otwarta ścieżka, która nie obejmuje żadnego obszaru, nie zmienia kształtu wyniku; aby ją uwzględnić, najpierw zastosuj do niej Obiekt › Ścieżka › Obrys konturu +@msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first {label} dało pusty wynik: linia lub inna otwarta ścieżka nie obejmuje żadnego obszaru; aby ją uwzględnić, najpierw zastosuj do niej Obiekt › Ścieżka › Obrys konturu @msg {label}… {label}… @msg {name}: CRC mismatch {name}: niezgodność CRC @msg {name}: no local header {name}: brak nagłówka lokalnego @@ -5552,6 +5702,9 @@ liquify-list-end {0}, {1} {0} i {1} @msgplural Discarded {n} recovered document|Discarded {n} recovered documents Odrzucono {n} odzyskany dokument|Odrzucono {n} odzyskane dokumenty|Odrzucono {n} odzyskanych dokumentów @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them Przywrócono {n} odzyskany dokument: zapisz go, aby go zachować|Przywrócono {n} odzyskane dokumenty: zapisz je, aby je zachować|Przywrócono {n} odzyskanych dokumentów: zapisz je, aby je zachować @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} Otwarto z {n} uwagą: {first}|Otwarto z {n} uwagami: {first}|Otwarto z {n} uwagami: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Skopiowano z {n} uwagą: {first}|Skopiowano z {n} uwagami: {first}|Skopiowano z {n} uwagami: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Wycięto z {n} uwagą: {first}|Wycięto z {n} uwagami: {first}|Wycięto z {n} uwagami: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Obrysowano obraz z {n} uwagą: {first}|Obrysowano obraz z {n} uwagami: {first}|Obrysowano obraz z {n} uwagami: {first} @msgplural {notice}. Opened with {n} note: {first}|{notice}. Opened with {n} notes: {first} {notice}. Otwarto z {n} uwagą: {first}|{notice}. Otwarto z {n} uwagami: {first}|{notice}. Otwarto z {n} uwagami: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} Zapisano {path} z {n} uwagą: {first}|Zapisano {path} z {n} uwagami: {first}|Zapisano {path} z {n} uwagami: {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first Osadzono {n} obraz; brakuje {missing}: najpierw połącz je ponownie|Osadzono {n} obrazy; brakuje {missing}: najpierw połącz je ponownie|Osadzono {n} obrazów; brakuje {missing}: najpierw połącz je ponownie @@ -5578,6 +5731,8 @@ liquify-list-end {0}, {1} {0} i {1} @msg All colors are within the CMYK gamut Wszystkie kolory mieszczą się w gamucie CMYK @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} kolor nie mieści się w gamucie CMYK|{n} kolory nie mieszczą się w gamucie CMYK|{n} kolorów nie mieści się w gamucie CMYK @msg Unembedded to {_1} Wyodrębniono do {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} Wyodrębniono {n} obraz do {folder}|Wyodrębniono {n} obrazy do {folder}|Wyodrębniono {n} obrazów do {folder} +@msg every numbered name for {name} is taken in that folder wszystkie numerowane nazwy dla {name} są zajęte w tym folderze @msg Reset {_1} Zresetowano {_1} @msg Sent to {_1} Wysłano do {_1} @msg {_1} files Pliki {_1} @@ -5593,6 +5748,8 @@ liquify-list-end {0}, {1} {0} i {1} @msg Reload the page to go on (changes not saved yet may be lost). Odśwież stronę, aby kontynuować (niezapisane zmiany mogą zostać utracone). @msg tool (a tool id) is required wymagane jest tool (identyfikator narzędzia) @msg {tool} isn't in a toolbar group of several tools {tool} nie należy do grupy kilku narzędzi na pasku narzędzi +@msg Presentation Mode hides the toolbars: change the screen mode to show them Tryb prezentacji ukrywa paski narzędzi: zmień tryb ekranu, aby je pokazać +@msg Tab has hidden the toolbars: press Tab to show them klawisz Tab ukrył paski narzędzi: naciśnij Tab, aby je pokazać @msg onto must name a panel floating in another group onto musi wskazywać panel pływający w innej grupie @msg below and above must name a panel floating in another group below i above muszą wskazywać panel pływający w innej grupie @msg give only one of onto, below and above podaj tylko jedno z: onto, below, above @@ -5603,7 +5760,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg `{what}` closes nothing `{what}` niczego nie zamyka @msg `{what}` closes something it didn't open `{what}` zamyka coś, czego nie otworzył @msg a mask that covers several layers comes in as a clipping group in each layer it covers maska obejmująca kilka warstw jest wczytywana jako grupa przycinająca w każdej obejmowanej warstwie -@msg a graph's records don't end where they should: its art was read as it is rekordy wykresu nie kończą się tam, gdzie powinny: jego grafika została wczytana tak, jak jest +@msg a graph's records don't end where they should: its art was read as it is rekordy wykresu nie kończą się tam, gdzie powinny: jego kompozycja została wczytana tak, jak jest @msg `{w}` takes no operands `{w}` nie przyjmuje operandów @msg a wraparound group is inside a compound path grupa oblewania tekstem jest wewnątrz ścieżki złożonej @msg a path has too many points ścieżka ma zbyt wiele punktów @@ -5627,7 +5784,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg more names that aren't UTF-8 were read as {label} ({count}) kolejne nazwy spoza UTF-8 odczytano jako {label} ({count}) @msg gradient “{name}” isn't defined in the file: a plain colour stands in for it gradient „{name}” nie jest zdefiniowany w pliku: zastąpiono go jednolitym kolorem @msg an image VectorCraft can't read was left out pominięto obraz, którego VectorCraft nie potrafi odczytać -@msg graphs come in as plain art, without their data or settings wykresy są wczytywane jako zwykła grafika, bez ich danych i ustawień +@msg graphs come in as plain art, without their data or settings wykresy są wczytywane jako zwykłe elementy kompozycji, bez ich danych i ustawień @msg an image whose data is cut short was left out pominięto obraz z uciętymi danymi @msg an embedded image of {_1} × {_2} pixels was reduced to {_3} × {_4} pixels to keep the layers osadzony obraz o wymiarach {_1} × {_2} pikseli zmniejszono do {_3} × {_4} pikseli, aby zachować warstwy @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel połączone obrazy pokazują zapisany w pliku podgląd niskiej rozdzielczości, dopóki ich pliki nie zostaną znalezione: połącz je ponownie w panelu Łącza @@ -5660,7 +5817,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg every numbered name for {name} is taken in the document's folder wszystkie numerowane nazwy dla {name} są zajęte w folderze dokumentu @msg No linked files to look for Brak połączonych plików do wyszukania @msg The link is inside a symbol, graph design, pattern or opacity mask and has no place on the canvas Łącze znajduje się w symbolu, wzorze wykresu, wzorku lub masce krycia i nie ma miejsca na obszarze roboczym -@msg the art of a graph design in a graph series is drawn again from the design: edit the design to change it grafika wzoru wykresu w serii danych wykresu jest rysowana od nowa na podstawie wzoru: aby ją zmienić, edytuj wzór +@msg the art of a graph design in a graph series is drawn again from the design: edit the design to change it kompozycja wzoru wykresu w serii danych wykresu jest rysowana od nowa na podstawie wzoru: aby ją zmienić, edytuj wzór @msg `id` is the step reference {r}, which only `run` and `command_batch` resolve `id` to odwołanie do kroku {r}, które rozwiązują tylko `run` i `command_batch` @msg `ids` must be an array of object ids, not {v} `ids` musi być tablicą identyfikatorów obiektów, nie {v} @msg `colors` must be an array of colors, not {v} `colors` musi być tablicą kolorów, nie {v} @@ -5681,6 +5838,9 @@ liquify-list-end {0}, {1} {0} i {1} @msg automation path rejected: outside the read root {root}: {path} odrzucono ścieżkę automatyzacji: poza katalogiem głównym odczytu {root}: {path} @msg automation path rejected: outside the read roots {roots}: {path} odrzucono ścieżkę automatyzacji: poza katalogami głównymi odczytu {roots}: {path} @msg a linked JavaScript file is outside the read roots połączony plik JavaScript jest poza katalogami głównymi odczytu +@msg a linked image file is outside the read roots połączony plik obrazu jest poza katalogami głównymi odczytu +@msg a linked file's export folder is outside the read roots folder eksportu połączonego pliku jest poza katalogami głównymi odczytu +@msg a linked file's editing data can't be read to check it against the read roots nie można odczytać danych edycji połączonego pliku, aby sprawdzić je względem katalogów głównych odczytu @msg automation path rejected: outside the write root {root}: {path} odrzucono ścieżkę automatyzacji: poza katalogiem głównym zapisu {root}: {path} @msg automation path rejected: outside the write roots {roots}: {path} odrzucono ścieżkę automatyzacji: poza katalogami głównymi zapisu {roots}: {path} @msg automation path rejected: path is empty odrzucono ścieżkę automatyzacji: ścieżka jest pusta @@ -5990,6 +6150,7 @@ liquify-list-end {0}, {1} {0} i {1} Ascent Wydłużenie górne Cap Height Wysokość wersalików x Height Wysokość x + Em Box Height Wysokość ramki firetowej Justify Justuj First Baseline Pierwsza linia bazowa Vertical Align Wyrównanie pionowe @@ -6113,6 +6274,7 @@ mark-style Japanese Japońskie Cove Wklęsłe Depth Głębokość Front Przód + Side Bok Isometric Bottom Izometryczny dół Isometric Left Izometryczny lewy Isometric Right Izometryczny prawy @@ -6185,11 +6347,11 @@ mark-style Japanese Japońskie @msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` musi być obiektem zawierającym tylko `mode` o wartości shaded lub wireframe @msg its 3D effect builds no solid jego efekt 3D nie tworzy żadnej bryły @msg bevel must be none or one of {_1} bevel musi mieć wartość none lub jedną z: {_1} -@msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1} nie może utworzyć brył z tego rysunku: jego wystąpienia symboli, przejścia i grupy przycinające zawierają zbyt wiele obiektów -@msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label} nie może utworzyć bryły z wystąpienia symbolu „{symbol}”: rysunek symbolu jest niedostępny -@msg {_1}: the clipping path is too complex to cut the art with {_1}: ścieżka przycinająca jest zbyt złożona, aby przyciąć nią rysunek +@msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1} nie może utworzyć brył z tej kompozycji: jej wystąpienia symboli, przejścia i grupy przycinające zawierają zbyt wiele obiektów +@msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label} nie może utworzyć bryły z wystąpienia symbolu „{symbol}”: kompozycja symbolu jest niedostępna +@msg {_1}: the clipping path is too complex to cut the art with {_1}: ścieżka przycinająca jest zbyt złożona, aby przyciąć nią kompozycję @msg {_1} takes at most {MAX_MEMBERS} objects {_1} przyjmuje najwyżej {MAX_MEMBERS} obiektów -@msg {_1} can't build solids from art nested more than {MAX_DEPTH} levels deep {_1} nie może utworzyć brył z rysunku zagnieżdżonego na więcej niż {MAX_DEPTH} poziomach +@msg {_1} can't build solids from art nested more than {MAX_DEPTH} levels deep {_1} nie może utworzyć brył z kompozycji zagnieżdżonej na więcej niż {MAX_DEPTH} poziomach @msg Revolve paint is too complex for this surface; reduce Segments or simplify the gradient Farba efektu Obrót jest zbyt złożona dla tej powierzchni; zmniejsz Segmenty lub uprość gradient @msg Revolve edge must be left or right Obrót: edge musi mieć wartość left lub right @msg Revolve cap must be a boolean Obrót: cap musi być wartością logiczną @@ -6207,21 +6369,21 @@ mark-style Japanese Japońskie @msg each of `{GRAPHICS}` must be an object każdy element `{GRAPHICS}` musi być obiektem @msg `{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}` elementy `{GRAPHICS}` przyjmują symbol, face, x, y, scale i rotation, a nie `{k}` @msg each of `{GRAPHICS}` needs `symbol`, the name of a symbol każdy element `{GRAPHICS}` wymaga `symbol`, nazwy symbolu -@msg `{GRAPHICS}` face must be front or back face w `{GRAPHICS}` musi mieć wartość front lub back +@msg `{GRAPHICS}` face must be front, back or side face w `{GRAPHICS}` musi mieć wartość front, back lub side @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} w `{GRAPHICS}` musi być liczbą od {lo} do {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` musi być tablicą @msg Graphics map onto the Plane, Extrude and Revolve object types Grafiki są nakładane na obiekty typu Płaszczyzna, Wyciągnięcie i Obrót @msg Revolve maps graphics onto its side: map them onto the front Obrót nakłada grafiki na swoją powierzchnię boczną: umieść je na przedniej stronie -@msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Grafiki są zbyt złożone dla tej powierzchni: uprość rysunki symboli lub zmniejsz Segmenty +@msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Grafiki są zbyt złożone dla tej powierzchni: uprość kompozycje symboli lub zmniejsz Segmenty @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` przyjmuje najwyżej {MAX_GRAPHICS} grafik @msg A plane has one face: map its graphics onto the front Płaszczyzna ma jedną stronę: umieść jej grafiki na przedniej stronie -@msg The graphics are too complex: simplify the symbols' art Grafiki są zbyt złożone: uprość rysunki symboli -@msg A graphic's art may be nested at most {MAX_LEVELS} levels deep: simplify the symbol's art Rysunek grafiki może być zagnieżdżony najwyżej na {MAX_LEVELS} poziomach: uprość rysunek symbolu -@msg A graphic's art may nest symbols at most {MAX_NESTING} levels deep: simplify the symbol's art Rysunek grafiki może zagnieżdżać symbole najwyżej na {MAX_NESTING} poziomach: uprość rysunek symbolu -@msg A graphic's art holds too many objects: simplify the symbol's art Rysunek grafiki zawiera zbyt wiele obiektów: uprość rysunek symbolu -@msg A graphic draws at most {MAX_PIECES} fills and strokes: simplify the symbol's art Grafika rysuje najwyżej {MAX_PIECES} wypełnień i obrysów: uprość rysunek symbolu +@msg The graphics are too complex: simplify the symbols' art Grafiki są zbyt złożone: uprość kompozycje symboli +@msg A graphic's art may be nested at most {MAX_LEVELS} levels deep: simplify the symbol's art Kompozycja grafiki może być zagnieżdżona najwyżej na {MAX_LEVELS} poziomach: uprość kompozycję symbolu +@msg A graphic's art may nest symbols at most {MAX_NESTING} levels deep: simplify the symbol's art Kompozycja grafiki może zagnieżdżać symbole najwyżej na {MAX_NESTING} poziomach: uprość kompozycję symbolu +@msg A graphic's art holds too many objects: simplify the symbol's art Kompozycja grafiki zawiera zbyt wiele obiektów: uprość kompozycję symbolu +@msg A graphic draws at most {MAX_PIECES} fills and strokes: simplify the symbol's art Grafika rysuje najwyżej {MAX_PIECES} wypełnień i obrysów: uprość kompozycję symbolu @msg `surface` must be one of {_1} `surface` musi mieć jedną z wartości: {_1} -@msg {label} draws the source art for this object instead of its 3D surface {label} rysuje dla tego obiektu rysunek źródłowy zamiast jego powierzchni 3D +@msg {label} draws the source art for this object instead of its 3D surface {label} rysuje dla tego obiektu kompozycję źródłową zamiast jego powierzchni 3D @msg {label} draws no faces for this object {label} nie rysuje żadnych ścian dla tego obiektu @msg the wireframe has more than {MAX_WIRE_EDGES} edges model szkieletowy ma więcej niż {MAX_WIRE_EDGES} krawędzi @msg The 3D surface is too complex; simplify the shape Powierzchnia 3D jest zbyt złożona; uprość kształt @@ -6343,18 +6505,23 @@ mark-style Japanese Japońskie Precision: Dokładność: Update Dimensions Aktualizuj wymiary @msg Angles require two straight segments Kąty wymagają dwóch prostych odcinków +@msg Choose original artwork, not a dimension's generated paths Wybierz oryginalną kompozycję, a nie ścieżki wygenerowane przez wymiar @msg Choose two different points Wybierz dwa różne punkty @msg Choose two non-parallel straight segments Wybierz dwa nierównoległe proste odcinki @msg Choose two nonzero angle arms Wybierz dwa niezerowe ramiona kąta +@msg Dimension is locked or hidden Wymiar jest zablokowany lub ukryty +@msg Dimension mode does not match its source Tryb wymiaru nie odpowiada jego źródłu @msg Dimension point is outside the canvas Punkt wymiaru leży poza obszarem roboczym @msg Dimension size is outside its supported range Rozmiar wymiaru jest poza obsługiwanym zakresem @msg First measured segment no longer exists Pierwszy mierzony odcinek już nie istnieje @msg Invalid dimension distance Nieprawidłowa odległość wymiaru @msg Invalid dimension font name Nieprawidłowa nazwa czcionki wymiaru +@msg Invalid dimension offset Nieprawidłowe odsunięcie wymiaru @msg Invalid drawing scale Nieprawidłowa skala rysunku @msg Invalid real scale Nieprawidłowa skala rzeczywista @msg Measured anchor no longer exists Mierzony punkt kontrolny już nie istnieje @msg Invalid measured point Nieprawidłowy mierzony punkt +@msg Invalid point Nieprawidłowy punkt @msg Measured segment no longer exists Mierzony odcinek już nie istnieje @msg Non-finite dimension Wymiar nie jest liczbą skończoną @msg Only linear dimensions are horizontal or vertical Tylko wymiary liniowe są poziome lub pionowe @@ -6471,8 +6638,8 @@ mark-style Japanese Japońskie @msg {id} opens another app: only the person at the keyboard can run it {id} otwiera inną aplikację: uruchomić to polecenie może tylko osoba przy klawiaturze @msg “{name}” is not a file „{name}” nie jest plikiem Enable Guides for 9-Slice Scaling Włącz linie pomocnicze skalowania 9-slice -@msg a mask has more than one art block maska ma więcej niż jeden blok grafiki -@msg mask art ends outside a mask dictionary grafika maski kończy się poza słownikiem maski +@msg a mask has more than one art block maska ma więcej niż jeden blok kompozycji +@msg mask art ends outside a mask dictionary kompozycja maski kończy się poza słownikiem maski @msg cancelled; nothing was changed anulowano; nic nie zostało zmienione @msg a linked image can't become a gradient mesh: embed it first połączony obraz nie może stać się siatką gradientu: najpierw go osadź @msg the image has no usable size or position obraz nie ma użytecznego rozmiaru ani położenia @@ -6531,7 +6698,7 @@ mark-style Japanese Japońskie Choose a filter Wybierz filtr Effect Gallery Galeria efektów Filters Filtry - Select artwork to apply effects Wybierz grafikę, aby zastosować efekty + Select artwork to apply effects Wybierz kompozycję, aby zastosować efekty @msg the file's variable bindings weren't all read (bindings skipped: {_1}): those objects aren't bound to their variables nie wszystkie powiązania zmiennych pliku zostały wczytane (pominięte powiązania: {_1}): te obiekty nie są powiązane ze swoimi zmiennymi @msg the file's variable library was partly read (entries skipped: {_1}): the Variables panel lists the rest biblioteka zmiennych pliku została wczytana tylko częściowo (pominięte wpisy: {_1}): panel Zmienne wyświetla resztę @msg the file's variable library couldn't be read: the Variables panel doesn't list it nie udało się wczytać biblioteki zmiennych pliku: panel Zmienne jej nie wyświetla @@ -6968,7 +7135,7 @@ axis Y Axis Oś Y Polar Grid Tool Options Opcje narzędzia Siatka biegunowa Fill Line Wypełnij odcinek Pathfinder Options Opcje odnajdywania ścieżek - Divide and Outline Will Remove Unpainted Artwork Podziel i Kontur usuwają niepomalowaną grafikę + Divide and Outline Will Remove Unpainted Artwork Podziel i Kontur usuwają niepomalowaną kompozycję @msg precision must be from 0.001 to 10 pt precision musi wynosić od 0,001 do 10 pt @msg `pathfinder` must be an object `pathfinder` musi być obiektem Add to Brushes Dodaj do pędzli @@ -7087,7 +7254,7 @@ anchor Points: Punkty: @msg select two open path ends, or two open paths, to average and join zaznacz dwa końce otwartych ścieżek lub dwie otwarte ścieżki do uśrednienia i połączenia # Artwork Cleanup add-on (Object › Plug-ins › Artwork Cleanup): its panel, tools, issue kinds and messages. - Artwork Cleanup Porządkowanie grafiki + Artwork Cleanup Porządkowanie kompozycji Simplify Anchors (Keep Shape)… Uprość punkty kontrolne (zachowaj kształt)… Health Check Kontrola stanu Show Issue Pokaż problem @@ -7109,7 +7276,7 @@ anchor Points: Punkty: Empty Text Paths Puste ścieżki tekstowe Zero-Opacity Objects Obiekty o zerowym kryciu Duplicate Objects Zduplikowane obiekty - Off-Artboard Art Grafika poza obszarami kompozycji + Off-Artboard Art Kompozycja poza obszarami kompozycji Duplicate Anchors Zduplikowane punkty kontrolne Tiny Handles Bardzo krótkie uchwyty Collinear Anchors Współliniowe punkty kontrolne @@ -7235,6 +7402,12 @@ anchor Points: Punkty: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` musi mieć wartość "free", "keepAngles" lub "symmetric" @msg `{key}` must be [x, y] `{key}` musi mieć postać [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Konwerter jednostek + Unit Converter Panel Panel Konwerter jednostek + Copy with Units Kopiuj z jednostkami + From Selection Z zaznaczenia + # Color Effects add-on: Select by Color Kind. Select by Color Kind Zaznacz według rodzaju koloru Objects with Spot Colors Obiekty z kolorami dodatkowymi @@ -7420,9 +7593,9 @@ breakText Glyphs Glify Dash 5 Kreska 5 Gap 5 Odstęp 5 -@msg {_1}: they came in as the page's art {_1}: zaimportowano je jako grafikę strony -@msg warped text objects that came in as drawn art, not as editable type: {_1} wypaczone obiekty tekstowe zaimportowane jako grafika, a nie jako edytowalny tekst: {_1} -@msg objects that drew differently from the file's own page came in as its art: {_1} obiekty rysowane inaczej niż własna strona pliku zaimportowano jako grafikę strony: {_1} +@msg {_1}: they came in as the page's art {_1}: zaimportowano je jako elementy kompozycji strony +@msg warped text objects that came in as drawn art, not as editable type: {_1} wypaczone obiekty tekstowe zaimportowane jako elementy kompozycji, a nie jako edytowalny tekst: {_1} +@msg objects that drew differently from the file's own page came in as its art: {_1} obiekty rysowane inaczej niż własna strona pliku zaimportowano jako elementy kompozycji strony: {_1} @msg You must choose a side pattern. Musisz wybrać wzór boczny. @msg invalid pattern tile choice nieprawidłowy wybór kafelka wzoru @@ -7460,6 +7633,14 @@ breakText Glyphs Glify Remove Gaps Usuń odstępy @msg that makes too many pieces (at most 100000): make the dashes longer to daje za dużo części (najwyżej 100000): wydłuż kreski @msg select paths, or segments, to divide zaznacz ścieżki lub segmenty do podzielenia +# Path Precision Tools add-on: Smooth Bridge. + Smooth Bridge… Gładki most… + Smooth Bridge Gładki most + Keep Originals Zachowaj oryginały +@msg select two circles to bridge zaznacz dwa okręgi do połączenia +@msg one circle is inside the other jeden okrąg jest wewnątrz drugiego +@msg the circles are too far apart for this radius: raise the radius okręgi są zbyt daleko od siebie dla tego promienia: zwiększ promień +@msg the circles are too far apart for this radius okręgi są zbyt daleko od siebie dla tego promienia # Path Precision Tools add-on: Common Tangents. Common Tangents… Wspólne styczne… Common Tangents Wspólne styczne @@ -7544,7 +7725,7 @@ breakText Glyphs Glify @msg `{name}` is a static symbol: set its Symbol Type to Dynamic first `{name}` jest symbolem statycznym: najpierw ustaw jego typ symbolu na Dynamiczny @msg Only the fill, stroke, opacity and blend of a path, compound path or type selected in a symbol instance can change W ścieżce, ścieżce złożonej lub tekście zaznaczonym w wystąpieniu symbolu można zmienić tylko wypełnienie, obrys, krycie i tryb mieszania @msg path must be a list of child indices path musi być listą indeksów elementów podrzędnych -@msg no object at path {shown} in the symbol's art brak obiektu w ścieżce {shown} w grafice symbolu +@msg no object at path {shown} in the symbol's art brak obiektu w ścieżce {shown} w kompozycji symbolu @msg give fill, stroke, opacity and/or blend podaj fill, stroke, opacity i/lub blend @msg {key} cannot be set on a guide nie można ustawić {key} dla linii pomocniczej @msg {key} cannot be set on a blend nie można ustawić {key} dla przejścia @@ -7600,7 +7781,7 @@ breakText Glyphs Glify Release Type on a Path Uwolnij tekst na ścieżce Text and Path Tekst i ścieżka Path Only Tylko ścieżka -@msg The art is too large to copy as a picture: other apps get no PNG of it Grafika jest zbyt duża, aby skopiować ją jako obraz: inne aplikacje nie otrzymają jej w formacie PNG +@msg The art is too large to copy as a picture: other apps get no PNG of it Kompozycja jest zbyt duża, aby skopiować ją jako obraz: inne aplikacje nie otrzymają jej w formacie PNG # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). Select by Artboards Zaznacz według obszarów kompozycji @@ -7778,9 +7959,9 @@ breakText Glyphs Glify Stencil Bridges Mostki szablonu Shortest Crossing Najkrótsze przejście Direction Kierunek -@msg The selected art has no islands to bridge Zaznaczona grafika nie ma wysp do połączenia -@msg No bridge of this width fits across the selected art Żaden mostek o tej szerokości nie mieści się w zaznaczonej grafice -@msg Some islands could not be joined to the area around the art Niektórych wysp nie udało się połączyć z obszarem wokół grafiki +@msg The selected art has no islands to bridge Zaznaczona kompozycja nie ma wysp do połączenia +@msg No bridge of this width fits across the selected art Żaden mostek o tej szerokości nie mieści się w zaznaczonej kompozycji +@msg Some islands could not be joined to the area around the art Niektórych wysp nie udało się połączyć z obszarem wokół kompozycji @msg `width` must be from {lo} to {hi} pt `width` musi mieścić się w zakresie od {lo} do {hi} pt @msg `angle` must be from -180 to 180 degrees `angle` musi mieścić się w zakresie od -180 do 180 stopni @msg `roundness` must be from 0 to 100% `roundness` musi mieścić się w zakresie od 0 do 100% @@ -7823,11 +8004,11 @@ breakText Glyphs Glify @msg Object.{function} was given a value that is not an object Object.{function} otrzymało wartość, która nie jest obiektem @msg QName.prototype.toString needs a QName QName.prototype.toString wymaga obiektu QName @msg RegExp.prototype.{name} was called on a value that is not a RegExp object RegExp.prototype.{name} wywołano na wartości, która nie jest obiektem RegExp -@msg Stencil Bridges: the selected art is too large or too detailed to bridge Mostki szablonu: zaznaczona grafika jest zbyt duża lub zbyt szczegółowa, aby utworzyć mostki +@msg Stencil Bridges: the selected art is too large or too detailed to bridge Mostki szablonu: zaznaczona kompozycja jest zbyt duża lub zbyt szczegółowa, aby utworzyć mostki @msg String.prototype.toString was called on a value that is not a string String.prototype.toString wywołano na wartości, która nie jest ciągiem znaków @msg The {name} profile could not be read, so the new document has the default settings: {reason} Nie udało się odczytać profilu {name}, więc nowy dokument ma ustawienia domyślne: {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 Zalewka: ponad {_1} par obiektów leży na tyle blisko siebie, że wymaga zalewki, albo zbyt wiele obiektów ma wspólny zakres poziomy; stosuj zalewkę do mniejszej liczby obiektów naraz -@msg Weed Box and Lines: no weeding line fits outside the art, and the weed box is off Ramka i linie do wybierania: żadna linia do wybierania nie mieści się poza grafiką, a ramka do wybierania jest wyłączona +@msg Weed Box and Lines: no weeding line fits outside the art, and the weed box is off Ramka i linie do wybierania: żadna linia do wybierania nie mieści się poza kompozycją, a ramka do wybierania jest wyłączona @msg \\ at end of pattern \\ na końcu wzorca @msg `alignOn` cannot be empty `alignOn` nie może być puste @msg `alignOn` must be a string `alignOn` musi być ciągiem znaków @@ -7836,6 +8017,14 @@ breakText Glyphs Glify @msg `answers` has more than {MAX_ANSWERS} answers `answers` zawiera więcej niż {MAX_ANSWERS} odpowiedzi @msg `answers` is larger than 1 MiB `answers` ma rozmiar większy niż 1 MiB @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` służy tylko do uruchomienia, w którym nie ma kogo zapytać: w aplikacji na każde okno dialogowe odpowiada użytkownik +@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` musi być liczbą całkowitą od 1 do {_1} +@msg `args{place}` is nested more than 64 levels deep `args{place}` jest zagnieżdżone głębiej niż na 64 poziomy +@msg `args` must be an object `args` musi być obiektem +@msg `args` is larger than 1 MiB `args` ma rozmiar większy niż 1 MiB +@msg `path` is empty `path` jest puste +@msg `installed` takes a `path`, not a `source` `installed` przyjmuje `path`, a nie `source` +@msg `path` must name a .js or .jsx file `path` musi wskazywać plik .js lub .jsx +@msg give exactly one of `path` and `source` podaj dokładnie jedno z: `path` i `source` @msg `answers` must be a list of answers `answers` musi być listą odpowiedzi @msg `artboard` must be the index of an artboard of the document `artboard` musi być indeksem obszaru kompozycji dokumentu @msg `artboardsAt` must be [x, y] `artboardsAt` musi mieć postać [x, y] @@ -7879,7 +8068,7 @@ breakText Glyphs Glify @msg `rows` must be lists of numbers or nulls, not {r} `rows` musi zawierać listy liczb lub wartości null, a nie {r} @msg `scale` must be a number from 0.001 to 1000 `scale` musi być liczbą od 0,001 do 1000 @msg `scope.{key}` must be a non-empty array `scope.{key}` musi być niepustą tablicą -@msg `scope` must be "document", {artboards} or {layers} `scope` musi mieć wartość "document", {artboards} lub {layers} +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` musi mieć wartość "document", {{artboards: [index, …]}} lub {{layers: [id, …]}} @msg `side` must be "left", "right", "top" or "bottom" `side` musi mieć wartość "left", "right", "top" lub "bottom" @msg `side` places the artboard: leave out x, y, width and height `side` wyznacza położenie obszaru kompozycji: pomiń x, y, width i height @msg `source` is the only path in series group `target` `source` jest jedyną ścieżką w grupie serii `target` @@ -8025,8 +8214,8 @@ breakText Glyphs Glify @msg it is larger than {MAX_DICTIONARY_FILE_BYTES} bytes ma rozmiar większy niż {MAX_DICTIONARY_FILE_BYTES} bajtów @msg it isn't a file to nie jest plik @msg it names {_1} plates, and at most {MAX_PLATES} are read wymienia {_1} płyt, a odczytywanych jest najwyżej {MAX_PLATES} -@msg its art is too long or too detailed for a head jego grafika jest zbyt długa lub zbyt szczegółowa na grot -@msg its art paints nothing jego grafika niczego nie maluje +@msg its art is too long or too detailed for a head jego kompozycja jest zbyt długa lub zbyt szczegółowa na grot +@msg its art paints nothing jego kompozycja niczego nie maluje @msg its image is too large to read jego obraz jest zbyt duży do odczytania @msg its plates are too large: more than {MAX_SAMPLES} pixels together jego płyty są zbyt duże: łącznie ponad {MAX_SAMPLES} pikseli @msg its plates are too large: {_1} plates of {w} × {h} pixels jego płyty są zbyt duże: {_1} płyt o wymiarach {w} × {h} pikseli @@ -8065,7 +8254,7 @@ breakText Glyphs Glify @msg not a regular expression to nie jest wyrażenie regularne @msg not an action set: the text doesn't start with /version and a number to nie jest zestaw operacji: tekst nie zaczyna się od /version i liczby @msg nothing to repeat brak elementu do powtórzenia -@msg numbers out of order in {_1} quantifier liczby w niewłaściwej kolejności w kwantyfikatorze {_1} +@msg numbers out of order in {{}} quantifier liczby w niewłaściwej kolejności w kwantyfikatorze {{}} @msg object {_1} needs a 3D effect obiekt {_1} wymaga efektu 3D @msg object {_1}: a hollow Extrude & Bevel has no caps: turn on Cap to map a graphic obiekt {_1}: puste w środku Wyciągnięcie i fazowanie nie ma zakończeń: włącz opcję Zakończenie, aby odwzorować grafikę @msg object {_1}: with a depth of 0 the object has one face: map its graphics onto the front obiekt {_1}: przy głębokości 0 obiekt ma jedną ścianę: odwzoruj jego grafiki na przodzie @@ -8076,7 +8265,7 @@ breakText Glyphs Glify @msg operand too large operand jest zbyt duży @msg order is a whole number from 0 to {others}, not `{v}` order to liczba całkowita od 0 do {others}, a nie `{v}` @msg path chunks must share their boundary point fragmenty ścieżki muszą mieć wspólny punkt graniczny -@msg pdfCompatible: false needs the artboards to keep the editable artwork when useArtboards is false pdfCompatible: false wymaga obszarów kompozycji, aby zachować edytowalną grafikę, gdy useArtboards ma wartość false +@msg pdfCompatible: false needs the artboards to keep the editable artwork when useArtboards is false pdfCompatible: false wymaga obszarów kompozycji, aby zachować edytowalną kompozycję, gdy useArtboards ma wartość false @msg point x must be a number współrzędna x punktu musi być liczbą @msg point y must be a number współrzędna y punktu musi być liczbą @msg points must be [x,y] pairs points musi zawierać pary [x,y] @@ -8089,7 +8278,7 @@ breakText Glyphs Glify @msg select an object with a 3D effect zaznacz obiekt z efektem 3D @msg select an object with a 3D effect, or give its id in ids zaznacz obiekt z efektem 3D albo podaj jego identyfikator w ids @msg select one layer, group or object to rename zaznacz jedną warstwę, grupę lub obiekt, aby zmienić nazwę -@msg select the art to weed zaznacz grafikę do wybierania +@msg select the art to weed zaznacz kompozycję do wybierania @msg select the banner, or mark every artboard zaznacz baner albo oznacz każdy obszar kompozycji @msg select type on a path or area type zaznacz tekst na ścieżce lub tekst akapitowy @msg side is left or right, not `{v}` side ma wartość left lub right, a nie `{v}` @@ -8116,7 +8305,7 @@ breakText Glyphs Glify @msg the XPath prefix {shown} is not bound to a namespace prefiks XPath {shown} nie jest powiązany z przestrzenią nazw @msg the XPath variable ${shown} is not bound zmienna XPath ${shown} nie jest powiązana @msg the argument list is not an object lista argumentów nie jest obiektem -@msg the artwork is too large for EPS: what follows 256 MB of PostScript was left out grafika jest zbyt duża dla formatu EPS: pominięto wszystko po 256 MB kodu PostScript +@msg the artwork is too large for EPS: what follows 256 MB of PostScript was left out kompozycja jest zbyt duża dla formatu EPS: pominięto wszystko po 256 MB kodu PostScript @msg the banner has no width or height baner nie ma szerokości lub wysokości @msg the bitmaps hold more pixels than one file may bitmapy zawierają więcej pikseli, niż może mieścić jeden plik @msg the code runs past its last instruction kod wykracza poza swoją ostatnią instrukcję @@ -8138,7 +8327,7 @@ breakText Glyphs Glify @msg the library's file is outside the read roots plik biblioteki znajduje się poza katalogami głównymi odczytu @msg the line is too long, or the paths it passes too many, to check linia jest zbyt długa albo mija zbyt wiele ścieżek, aby ją sprawdzić @msg the method needs an XML value metoda wymaga wartości XML -@msg the paint is not a freeform gradient (apply one with paint.editGradient {kind}) malowanie obiektu nie jest gradientem dowolnym (zastosuj go poleceniem paint.editGradient {kind}) +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) malowanie obiektu nie jest gradientem dowolnym (zastosuj go poleceniem paint.editGradient {{kind: "freeform"}}) @msg the parameters or body do not form one function parametry lub treść nie tworzą jednej funkcji @msg the pasted SVG filter {name} draws differently from the document's filter of that name, and no free name fits it wklejony filtr SVG {name} rysuje inaczej niż filtr dokumentu o tej nazwie, a nie znaleziono dla niego wolnej nazwy @msg the paths are too many or too tangled to find where they cross ścieżek jest zbyt wiele lub są zbyt splątane, aby znaleźć miejsca ich przecięć @@ -8150,8 +8339,8 @@ breakText Glyphs Glify @msg the rectangle or line reaches too many paths to check prostokąt lub linia sięga zbyt wielu ścieżek, aby je sprawdzić @msg the right side of 'in' is not an object prawa strona operatora 'in' nie jest obiektem @msg the right side of 'instanceof' is not a function prawa strona operatora 'instanceof' nie jest funkcją -@msg the selected art is nested more than {MAX_DEPTH} levels deep zaznaczona grafika jest zagnieżdżona głębiej niż na {MAX_DEPTH} poziomów -@msg the selected art is too large to measure zaznaczona grafika jest zbyt duża, aby ją zmierzyć +@msg the selected art is nested more than {MAX_DEPTH} levels deep zaznaczona kompozycja jest zagnieżdżona głębiej niż na {MAX_DEPTH} poziomów +@msg the selected art is too large to measure zaznaczona kompozycja jest zbyt duża, aby ją zmierzyć @msg the selection has no outlines to weed around zaznaczenie nie ma konturów, wokół których można wybierać @msg the spacing makes more than {MAX_GROMMETS} grommets odstęp daje więcej niż {MAX_GROMMETS} oczek @msg the value bind was called on is not a function wartość, na której wywołano bind, nie jest funkcją @@ -8160,7 +8349,7 @@ breakText Glyphs Glify @msg the value is not a valid XML name wartość nie jest prawidłową nazwą XML @msg the value is not an XML attribute name wartość nie jest nazwą atrybutu XML @msg the value is not an XML name wartość nie jest nazwą XML -@msg the weeding lines cross the art's outlines too many times to measure; use fewer lines linie do wybierania przecinają kontury grafiki zbyt wiele razy, aby to zmierzyć; użyj mniejszej liczby linii +@msg the weeding lines cross the art's outlines too many times to measure; use fewer lines linie do wybierania przecinają kontury kompozycji zbyt wiele razy, aby to zmierzyć; użyj mniejszej liczby linii @msg the weeding lines pass too close to too many outline segments to measure; use fewer lines or a smaller gap linie do wybierania przebiegają zbyt blisko zbyt wielu segmentów konturu, aby to zmierzyć; użyj mniejszej liczby linii lub mniejszego odstępu @msg the weeding lines would be more than {max_pieces} pieces linie do wybierania składałyby się z więcej niż {max_pieces} części @msg the {_1} plate lies outside the file płyta {_1} leży poza plikiem @@ -8230,7 +8419,7 @@ breakText Glyphs Glify @msg DXF scale must be a positive number up to {_1}, not {scale} Skala DXF musi być liczbą dodatnią nie większą niż {_1}, a nie {scale} @msg DXF {field} `{s}`: {allowed} DXF {field} `{s}`: {allowed} @msg Draw Inside needs exactly one selected path, compound path or text Rysuj wewnątrz wymaga dokładnie jednej zaznaczonej ścieżki, ścieżki złożonej lub tekstu -@msg EPS Save writes all artwork: use document.export for selected-only EPS Zapis EPS obejmuje całą grafikę: użyj document.export, aby zapisać w EPS tylko zaznaczenie +@msg EPS Save writes all artwork: use document.export for selected-only EPS Zapis EPS obejmuje całą kompozycję: użyj document.export, aby zapisać w EPS tylko zaznaczenie @msg EPS flattener: {e} Spłaszczanie EPS: {e} @msg EPS options: {e} Opcje EPS: {e} @msg EPS {field} `{s}`: {allowed} EPS {field} `{s}`: {allowed} @@ -8419,12 +8608,14 @@ breakText Glyphs Glify @msg `{_1}` is built in and always listed `{_1}` jest wbudowane i zawsze widoczne na liście @msg `{_1}` is not a font file the last text.findFontFiles search found `{_1}` nie jest plikiem czcionki znalezionym przez ostatnie wyszukiwanie text.findFontFiles @msg `{_1}` would be overwritten by the package: choose a different folder or name `{_1}` zostałoby nadpisane przez pakiet: wybierz inny folder lub inną nazwę -@msg `{file}` has no art to place `{file}` nie zawiera grafiki do umieszczenia +@msg `{file}` has no art to place `{file}` nie zawiera kompozycji do umieszczenia @msg `{file}` is over {_1} MB `{file}` ma ponad {_1} MB @msg `{f}` belongs to a VectorCraft that is running `{f}` należy do uruchomionego programu VectorCraft @msg `{f}` is the copy of a document open now `{f}` to kopia otwartego teraz dokumentu @msg `{id}` is no writable format (see document.formats) `{id}` nie jest formatem z możliwością zapisu (patrz document.formats) @msg `{id}` isn't a loaded library `{id}` nie jest wczytaną biblioteką +@msg `{file}` has no swatches of its own `{file}` nie ma własnych próbek +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` zawiera próbki wzorków, których plik .vcswatches nie może przechować @msg `{key}` has no colours `{key}` nie zawiera kolorów @msg `{key}` is a design name `{key}` to nazwa wzoru @msg `{key}` is a design name or a list of them `{key}` to nazwa wzoru lub lista takich nazw @@ -8458,7 +8649,7 @@ breakText Glyphs Glify @msg `{name}` can't be edited this way `{name}` nie można edytować w ten sposób @msg `{name}` can't be renamed nazwy `{name}` nie można zmienić @msg `{name}` can't name a folder `{name}` nie może być nazwą folderu -@msg `{name}` has no art to place `{name}` nie zawiera grafiki do umieszczenia +@msg `{name}` has no art to place `{name}` nie zawiera kompozycji do umieszczenia @msg `{name}` has no text to place `{name}` nie zawiera tekstu do umieszczenia @msg `{name}` in the Word document is not UTF-8 or UTF-16 text `{name}` w dokumencie Word nie jest tekstem UTF-8 ani UTF-16 @msg `{name}` in the Word document is not well-formed XML: {e} `{name}` w dokumencie Word nie jest poprawnie sformułowanym kodem XML: {e} @@ -8570,7 +8761,7 @@ breakText Glyphs Glify @msg artboardLayout.spacing must be 0–{MAX_SPACING} pt artboardLayout.spacing musi wynosić 0–{MAX_SPACING} pt @msg artboards must be a non-empty list artboards musi być niepustą listą @msg artboards must be a number artboards musi być liczbą -@msg asset `{_1}` has no art to export zasób `{_1}` nie zawiera grafiki do wyeksportowania +@msg asset `{_1}` has no art to export zasób `{_1}` nie zawiera kompozycji do wyeksportowania @msg at most {MAX_KEYWORDS} keywords najwyżej {MAX_KEYWORDS} słów kluczowych @msg at most {MAX_MATCHES} matches are kept zachowywanych jest najwyżej {MAX_MATCHES} dopasowań @msg at most {MAX_POINTS} points najwyżej {MAX_POINTS} punktów @@ -8647,7 +8838,13 @@ breakText Glyphs Glify @msg colorModel must be {own} (the document's mode), grayscale or bitmap colorModel musi mieć wartość {own} (tryb dokumentu), grayscale lub bitmap @msg colour groups can't go into colour groups grup kolorów nie można umieszczać w grupach kolorów @msg colour, mode and spot apply to solid-colour swatches only color, mode i spot dotyczą tylko próbek kolorów jednolitych -@msg column {column}: `{cell}` is a `%` column of graph data files, which are not read kolumna {column}: `{cell}` to kolumna `%` plików danych wykresu, które nie są odczytywane +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path wiersz {line}, kolumna {column}: plik danych wykresu `{path}` dla `{var}` ma ścieżkę względną: podaj `base` albo ścieżkę bezwzględną +@msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} wiersz {line}, kolumna {column}: nie można odczytać pliku danych wykresu dla `{var}`: {e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` isn't followed: {r} wiersz {line}, kolumna {column}: plik danych wykresu `{path}` dla `{var}` nie jest pobierany: {r} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes wiersz {line}, kolumna {column}: plik danych wykresu `{path}` dla `{var}` jest większy niż {MAX_GRAPH_DATA_FILE} bajtów +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes wiersz {line}, kolumna {column}: plik danych wykresu `{path}` dla `{var}` daje wartość wykresu dłuższą niż {MAX_GRAPH_CSV} bajtów +@msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all wiersz {line}, kolumna {column}: pliki danych wykresu zawierają łącznie ponad {MAX_GRAPH_FILES_TOTAL} bajtów +@msg `base` is empty `base` jest puste @msg column {column}: `{cell}` names `{name}`, which is a {_1} variable kolumna {column}: `{cell}` wskazuje `{name}`, czyli zmienną typu {_1} @msg column {column}: `{cell}` names no variable kolumna {column}: `{cell}` nie wskazuje żadnej zmiennej @msg column {column}: the variable name is longer than {MAX_NAME} characters kolumna {column}: nazwa zmiennej ma więcej niż {MAX_NAME} znaków @@ -8658,6 +8855,7 @@ breakText Glyphs Glify @msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes kształty złożone przyjmują ścieżki, ścieżki złożone, grupy, kształty złożone, tekst, przejścia i koperty @msg compound {_1} must contain exactly one open path to join obiekt złożony {_1} musi zawierać dokładnie jedną otwartą ścieżkę do połączenia @msg connect needs a path other than the one extended connect wymaga ścieżki innej niż przedłużana +@msg connect needs extend connect wymaga extend @msg connect needs id connect wymaga id @msg connect path has no open end ścieżka w connect nie ma otwartego końca @msg copy needs path: the file to copy into the document's folder copy wymaga path: pliku do skopiowania do folderu dokumentu @@ -8838,7 +9036,7 @@ breakText Glyphs Glify @msg kind must be 1, 2 or 3, or give a preset `name` (see perspective.presets.list) kind musi wynosić 1, 2 lub 3, albo podaj `name` ustawienia (patrz perspective.presets.list) @msg kind must be graphic, fillColor, strokeColor, fillGradient, strokeGradient, fillPattern, strokePattern, charStyle or paraStyle kind musi mieć wartość graphic, fillColor, strokeColor, fillGradient, strokeGradient, fillPattern, strokePattern, charStyle lub paraStyle @msg knockout must be "on", "off", "neutral" or a bool, not {v} knockout musi mieć wartość "on", "off", "neutral" lub wartość logiczną, a nie {v} -@msg layer `{name}` has no art to export warstwa `{name}` nie zawiera grafiki do wyeksportowania +@msg layer `{name}` has no art to export warstwa `{name}` nie zawiera kompozycji do wyeksportowania @msg layer must name a layer or sublayer layer musi wskazywać warstwę lub podwarstwę @msg layers can't be intertwined: select the objects in them warstw nie można przeplatać: zaznacz znajdujące się w nich obiekty @msg layers go only at the top level or in layers, objects in layers and groups warstwy mogą się znajdować tylko na najwyższym poziomie lub w warstwach, a obiekty w warstwach i grupach @@ -8957,7 +9155,7 @@ breakText Glyphs Glify @msg no asset {id} brak zasobu {id} @msg no asset {id} (see assets.list) brak zasobu {id} (patrz assets.list) @msg no assets to export brak zasobów do wyeksportowania -@msg no assets yet: collect art for export first (assets.add) nie ma jeszcze zasobów: najpierw zbierz grafikę do eksportu (assets.add) +@msg no assets yet: collect art for export first (assets.add) nie ma jeszcze zasobów: najpierw zbierz kompozycję do eksportu (assets.add) @msg no brush named `{n}` brak pędzla o nazwie `{n}` @msg no character at byte {start} brak znaku w bajcie {start} @msg no colour brak koloru @@ -9020,7 +9218,7 @@ breakText Glyphs Glify @msg no saved views brak zapisanych widoków @msg no series {i} brak serii {i} @msg no slice {n} in the image (see slice.list) brak plasterka {n} w obrazie (patrz slice.list) -@msg no source art brak grafiki źródłowej +@msg no source art brak kompozycji źródłowej @msg no stop {i} (the gradient has {n}) brak punktu koloru {i} (gradient ma {n}) @msg no style `{name}` brak stylu `{name}` @msg no such assets (see assets.list) brak takich zasobów (patrz assets.list) @@ -9080,10 +9278,10 @@ breakText Glyphs Glify @msg nothing to change: give dx, dy, hScale, vScale or rotation nie ma czego zmienić: podaj dx, dy, hScale, vScale lub rotation @msg nothing to crop nie ma czego kadrować @msg nothing to export nie ma czego eksportować -@msg nothing to export: the document has no visible art nie ma czego eksportować: dokument nie zawiera widocznej grafiki +@msg nothing to export: the document has no visible art nie ma czego eksportować: dokument nie zawiera widocznej kompozycji @msg nothing to mark nie ma czego oznaczać @msg nothing to print: every artboard picked is blank nie ma czego drukować: każdy wybrany obszar kompozycji jest pusty -@msg nothing to print: the document has no art that prints nie ma czego drukować: dokument nie zawiera grafiki przeznaczonej do druku +@msg nothing to print: the document has no art that prints nie ma czego drukować: dokument nie zawiera kompozycji przeznaczonej do druku @msg object is not a path obiekt nie jest ścieżką @msg object transparency cannot be sampled onto highlighted characters; disable Transparency in Eyedropper Options or select the whole object przezroczystości obiektu nie można próbkować na wyróżnione znaki; wyłącz Przezroczystość w Opcjach kroplomierza albo zaznacz cały obiekt @msg object {_1} can't be set as point type obiektu {_1} nie można ustawić jako tekstu punktowego @@ -9130,12 +9328,12 @@ breakText Glyphs Glify @msg overlap: {o} pt is half a tile or more overlap: {o} pt to co najmniej połowa kafelka @msg overlapping Shaper paths must be in the same layer or group nakładające się ścieżki narzędzia Kształtowanie muszą znajdować się w tej samej warstwie lub grupie @msg overlapping edits nakładające się edycje -@msg page art conflicts with image data for {key} grafika strony jest sprzeczna z danymi obrazu dla {key} -@msg page art conflicts with pattern {name} grafika strony jest sprzeczna z wzorkiem {name} -@msg page art conflicts with swatch {name} grafika strony jest sprzeczna z próbką {name} -@msg page art is missing image data for {key} w grafice strony brakuje danych obrazu dla {key} -@msg page art is missing pattern {name} w grafice strony brakuje wzorka {name} -@msg page art is missing swatch {name} w grafice strony brakuje próbki {name} +@msg page art conflicts with image data for {key} kompozycja strony jest sprzeczna z danymi obrazu dla {key} +@msg page art conflicts with pattern {name} kompozycja strony jest sprzeczna ze wzorkiem {name} +@msg page art conflicts with swatch {name} kompozycja strony jest sprzeczna z próbką {name} +@msg page art is missing image data for {key} w kompozycji strony brakuje danych obrazu dla {key} +@msg page art is missing pattern {name} w kompozycji strony brakuje wzorka {name} +@msg page art is missing swatch {name} w kompozycji strony brakuje próbki {name} @msg page must be a whole number from 1 page musi być liczbą całkowitą od 1 @msg page thumbnail: {e} miniatura strony: {e} @msg page {page} of the PDF has no objects strona {page} pliku PDF nie zawiera obiektów @@ -9149,7 +9347,7 @@ breakText Glyphs Glify @msg passwords can have up to {MAX_PASSWORD} bytes hasła mogą mieć najwyżej {MAX_PASSWORD} bajtów @msg path has no open end ścieżka nie ma otwartego końca @msg paths must be strings paths musi zawierać ciągi znaków -@msg pdfCompatible: false needs every artboard to keep the editable artwork pdfCompatible: false wymaga wszystkich obszarów kompozycji, aby zachować edytowalną grafikę +@msg pdfCompatible: false needs every artboard to keep the editable artwork pdfCompatible: false wymaga wszystkich obszarów kompozycji, aby zachować edytowalną kompozycję @msg pdfs `{m}`: single or multiple pdfs `{m}`: single lub multiple @msg pickColorFrom is "artwork" or "swatches", not {v} pickColorFrom ma wartość "artwork" lub "swatches", a nie {v} @msg pins and moved must be non-empty lists of the same length pins i moved muszą być niepustymi listami tej samej długości @@ -9230,9 +9428,9 @@ breakText Glyphs Glify @msg select area type (text in a frame) zaznacz tekst akapitowy (tekst w ramce) @msg select area type and closed paths (at least one area type object) zaznacz tekst akapitowy i ścieżki zamknięte (co najmniej jeden obiekt tekstu akapitowego) @msg select area type whose first line can fit its frame zaznacz tekst akapitowy, którego pierwszy wiersz mieści się w ramce -@msg select artwork to add its colours zaznacz grafikę, aby dodać jej kolory -@msg select artwork to make a group of its colours zaznacz grafikę, aby utworzyć grupę z jej kolorów -@msg select artwork to recolour, or give a colour `group` zaznacz grafikę do zmiany kolorów albo podaj `group` kolorów +@msg select artwork to add its colours zaznacz kompozycję, aby dodać jej kolory +@msg select artwork to make a group of its colours zaznacz kompozycję, aby utworzyć grupę z jej kolorów +@msg select artwork to recolour, or give a colour `group` zaznacz kompozycję do zmiany kolorów albo podaj `group` kolorów @msg select exactly two path ends to join zaznacz dokładnie dwa końce ścieżek do połączenia @msg select members of a compound shape zaznacz elementy kształtu złożonego @msg select objects or give ids zaznacz obiekty albo podaj ids @@ -9245,11 +9443,11 @@ breakText Glyphs Glify @msg select something to export zaznacz coś do wyeksportowania @msg select something to export (or turn off selectedOnly) zaznacz coś do wyeksportowania (albo wyłącz selectedOnly) @msg select text to redefine the style from zaznacz tekst, na podstawie którego styl ma zostać zdefiniowany ponownie -@msg select the art and, on top of it, the mask object zaznacz grafikę oraz leżący nad nią obiekt maski -@msg select the art for the design zaznacz grafikę dla wzoru -@msg select the art for the pattern tile zaznacz grafikę dla kafelka wzorka -@msg select the art to add first najpierw zaznacz grafikę do dodania -@msg select the art to collect (or give its ids) zaznacz grafikę do zebrania (albo podaj jej identyfikatory) +@msg select the art and, on top of it, the mask object zaznacz kompozycję oraz leżący nad nią obiekt maski +@msg select the art for the design zaznacz kompozycję dla wzoru +@msg select the art for the pattern tile zaznacz kompozycję dla kafelka wzorka +@msg select the art to add first najpierw zaznacz kompozycję do dodania +@msg select the art to collect (or give its ids) zaznacz kompozycję do zebrania (albo podaj jej identyfikatory) @msg select the content and a path on top zaznacz zawartość oraz leżącą nad nią ścieżkę @msg select the images to relink, or pass ids zaznacz obrazy do ponownego połączenia albo przekaż ids @msg select the images, or pass ids zaznacz obrazy albo przekaż ids @@ -9323,7 +9521,7 @@ breakText Glyphs Glify @msg the container of the listed objects is gone kontener wymienionych obiektów już nie istnieje @msg the copy `{user_id}` can't be read as a library kopii `{user_id}` nie można odczytać jako biblioteki @msg the copy would leave the canvas kopia wykroczyłaby poza płótno -@msg the cut cannot be made on this art: {e} na tej grafice nie można wykonać cięcia: {e} +@msg the cut cannot be made on this art: {e} na tej kompozycji nie można wykonać cięcia: {e} @msg the data isn't an EMF or WMF picture dane nie są ilustracją EMF ani WMF @msg the data isn't an EPS or PostScript picture dane nie są ilustracją EPS ani PostScript @msg the deferred paste is no longer available odroczone wklejanie nie jest już dostępne @@ -9358,7 +9556,7 @@ breakText Glyphs Glify @msg the image's transparency doesn't fit it przezroczystość obrazu do niego nie pasuje @msg the job would print more than {MAX_PAGES} pages zadanie wydrukowałoby ponad {MAX_PAGES} stron @msg the job would print more than {_1} pages zadanie wydrukowałoby ponad {_1} stron -@msg the layers hold no art to mask warstwy nie zawierają grafiki do zamaskowania +@msg the layers hold no art to mask warstwy nie zawierają kompozycji do zamaskowania @msg the layout moved układ uległ przesunięciu @msg the library has a group `{name}` already biblioteka ma już grupę `{name}` @msg the library has no group `{name}` biblioteka nie ma grupy `{name}` @@ -9373,7 +9571,7 @@ breakText Glyphs Glify @msg the open and permissions passwords must differ hasło otwarcia i hasło uprawnień muszą się różnić @msg the operand stack overflowed stos operandów został przepełniony @msg the page has no area strona nie ma powierzchni -@msg the page's type in an unread object's box isn't in its page art tekstu strony w polu nieodczytanego obiektu nie ma w grafice tej strony +@msg the page's type in an unread object's box isn't in its page art tekstu strony w polu nieodczytanego obiektu nie ma w kompozycji tej strony @msg the paint behind the proxy is not a gradient malowanie wskazywane przez wskaźnik wypełnienia lub obrysu nie jest gradientem @msg the parent must be a layer or sublayer elementem nadrzędnym musi być warstwa lub podwarstwa @msg the path can't be extended ścieżki nie można przedłużyć @@ -9386,10 +9584,10 @@ breakText Glyphs Glify @msg the program uses too much memory program zużywa zbyt dużo pamięci @msg the rectangle must have a width and a height prostokąt musi mieć szerokość i wysokość @msg the rectangle needs a size and must lie on the canvas prostokąt wymaga rozmiaru i musi leżeć na płótnie -@msg the selected art has no width zaznaczona grafika nie ma szerokości +@msg the selected art has no width zaznaczona kompozycja nie ma szerokości @msg the selection draws nothing zaznaczenie niczego nie rysuje @msg the selection has no area zaznaczenie nie ma powierzchni -@msg the selection has no art to export zaznaczenie nie zawiera grafiki do wyeksportowania +@msg the selection has no art to export zaznaczenie nie zawiera kompozycji do wyeksportowania @msg the selection has no bounds zaznaczenie nie ma granic @msg the selection has no graphic style zaznaczenie nie ma stylu graficznego @msg the slice would leave the canvas plasterek wykroczyłby poza płótno @@ -9608,7 +9806,7 @@ breakText Glyphs Glify @msg {std} files are CMYK, and the file would have colours in {_1} pliki {std} są w CMYK, a plik zawierałby kolory w {_1} @msg {std} files embed their fonts, and the file would have one that isn't pliki {std} osadzają swoje czcionki, a plik zawierałby czcionkę nieosadzoną @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} to plik, z którego odczytano ten dokument, a przy odczycie pominięto część zawartości ({what}): nadpisanie go spowodowałoby jej trwałą utratę. Zapisz zamiast tego inny plik albo przekaż acknowledgeLoss: true, aby mimo to go zastąpić -@msg {ty} brushes need selected art (or params.{k}) pędzle {ty} wymagają zaznaczonej grafiki (lub params.{k}) +@msg {ty} brushes need selected art (or params.{k}) pędzle {ty} wymagają zaznaczonej kompozycji (lub params.{k}) @msg {v} is not an asset id {v} nie jest identyfikatorem zasobu @msg {what} can't be intertwined {what} nie można przeplatać @msg {what} doesn't fit the paper with its bleed and marks {what} nie mieści się na papierze wraz ze spadem i znacznikami @@ -9656,7 +9854,7 @@ breakText Glyphs Glify @msg Targa depth {_1}: 16, 24 or 32 bits per pixel Głębia Targa {_1}: 16, 24 lub 32 bity na piksel @msg Targa encoding failed: the pixel buffer doesn't match the image size Kodowanie Targa nie powiodło się: bufor pikseli nie odpowiada rozmiarowi obrazu @msg The 3D projection is not finite Rzut 3D nie jest skończony -@msg The 3D shadow is too complex; turn Shadows off or simplify the art Cień 3D jest zbyt złożony; wyłącz Cienie lub uprość grafikę +@msg The 3D shadow is too complex; turn Shadows off or simplify the art Cień 3D jest zbyt złożony; wyłącz Cienie lub uprość kompozycję @msg The shape contains invalid coordinates Kształt zawiera nieprawidłowe współrzędne @msg Too many Revolve faces for visibility evaluation Zbyt wiele ścian efektu Obrót do obliczenia widoczności @msg VectorCraft reads at most {ASE_MAX_ENTRIES} colors and groups from a swatch exchange file, and this library has {entries} VectorCraft odczytuje z pliku wymiany próbek najwyżej {ASE_MAX_ENTRIES} kolorów i grup, a ta biblioteka ma ich {entries} @@ -9770,3 +9968,13 @@ breakText Glyphs Glify @msg A panel is not joined to the rest by a crease. Panel nie jest połączony z resztą żadną linią bigowania. @msg A fold line is on a non-printing layer. Linia zgięcia znajduje się na warstwie niedrukowanej. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panele: {panels}, zawiasy: {hinges}, błędy: {errors}, ostrzeżenia: {warnings} + Fold Preview Podgląd złożenia + Fold Złożenie + Show Fold Lines Pokaż linie zgięcia + Three-Quarter Trzy czwarte + Open a document to preview its folded shape. Otwórz dokument, aby zobaczyć podgląd jego złożonego kształtu. +@msg Check the fold lines first. Najpierw sprawdź linie zgięcia. +@msg Panels: {panels}, hinges: {hinges} Panele: {panels}, zawiasy: {hinges} +@msg Other blanks not shown: {count} Inne wykroje nie są pokazane: {count} +@msg A joint does not close by {gap} pt. Połączenie nie domyka się o {gap} pt. +@msg Two panels pass through each other. Dwa panele przechodzą przez siebie. diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 8201db7ab6..78012c35eb 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -126,6 +126,7 @@ Add Anchor Point Adicionar Ponto de Ancoragem Add Anchor Point Tool Ferramenta Adicionar Ponto de Ancoragem Add Anchor Points Adicionar Pontos de Ancoragem + Add Around Adicionar ao Redor do Objeto Add Effect Adicionar Efeito Add Freeform Line Adicionar Linha Livre Add Freeform Point Adicionar Ponto Livre @@ -146,8 +147,12 @@ Add to Selection Adicionar à Seleção Add to Swatches Adicionar às Amostras Additional Plug-ins Folder Pasta Adicional de Plug-ins + Plug-in Instruction Budget Orçamento de Instruções de Plug-ins Additional Fonts Folder Pasta Adicional de Fontes Adjust Adjoining Width Points Ajustar Pontos de Largura Adjacentes + Incoming Entrada + Outgoing Saída + Single Width Only Somente Uma Largura Adjust Color Balance… Ajustar Equilíbrio de Cores… Adjust Colors Ajustar Cores Adjust Options: Opções de Ajuste: @@ -195,6 +200,7 @@ Angle: Ângulo: Angles Ângulos Animated Zoom Zoom Animado + Anti Alias Suavização Anti-Alias Suavização de Serrilhado Anti-alias Suavizar bordas Anti-alias Rasters Suavizar Rasters @@ -331,6 +337,12 @@ antiAlias Sharp Nítido Brush Definition Definição do Pincel Brush Libraries Bibliotecas de Pincéis Brush Options… Opções de Pincel… + Options of Selected Object… Opções do Objeto Selecionado… + Options of Selected Object Opções do Objeto Selecionado +@msg no path painted with a brush is selected nenhum demarcador pintado com pincel selecionado +@msg the selected paths are painted with brushes of different types os demarcadores selecionados estão pintados com pincéis de tipos diferentes +@msg give `params` or `reset`, not both informe `params` ou `reset`, não ambos +@msg a bristle brush has no options of its own on a path um pincel de cerdas não tem opções próprias em um demarcador Brush Strokes Traços de Pincel Brushes Pincéis Built-in Libraries Bibliotecas Integradas @@ -386,6 +398,12 @@ antiAlias Sharp Nítido Character Alignment Alinhamento de Caracteres Character / Paragraph Caractere / Parágrafo Character Rotation Rotação de Caractere + Chinese Big 5 Chinês Big 5 + Cyrillic Cirílico + Greek Grego + Turkish Turco + Baltic Báltico + Central European Europa Central Character Set: Conjunto de Caracteres: Character Style Options Opções de Estilo de Caractere Character Styles Estilos de Caractere @@ -446,6 +464,8 @@ antiAlias Sharp Nítido Choose a folder Escolher uma pasta Choose… Escolher… Circle Círculo + Circle Tool Ferramenta Círculo + Circle too large Círculo grande demais Clean Up… Limpar… Clear Limpar Clear All Tabs Limpar Todas as Paradas de Tabulação @@ -501,6 +521,7 @@ antiAlias Sharp Nítido Color Library… Biblioteca de Cores… Color Mode Modo de Cor Color Mode: Modo de Cor: + Color Model Modelo de Cor Color Model: Modelo de Cor: Color Models Modelos de Cor Color Picker Seletor de Cores @@ -518,6 +539,11 @@ antiAlias Sharp Nítido Saturation and brightness Saturação e Brilho Color field Campo de Cor {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Exibição em Roda + Box View Exibição em Caixa + Box Channel Canal da Caixa + Color box Caixa de cor + Color Wheel Options Opções da Roda de Cores Color Type: Tipo de Cor: Color blindness – Deuteranopia-type Daltonismo – tipo deuteranopia Color blindness – Protanopia-type Daltonismo – tipo protanopia @@ -529,6 +555,7 @@ antiAlias Sharp Nítido Colors Cores Colors: Cores: Column Graph Tool Ferramenta Gráfico de Colunas + Columns Colunas Columns: Colunas: Column… Coluna… Combine Slices Combinar Fatias @@ -704,6 +731,8 @@ antiAlias Sharp Nítido Delete Artboard Excluir Mesa de Trabalho Delete Artboards Excluir Mesas de Trabalho Delete Brush Excluir Pincel + Delete Color Excluir Cor + Restore Generated Table Restaurar Tabela Gerada Delete Character Style Excluir Estilo de Caractere Delete Empty Artboards Excluir Mesas de Trabalho Vazias Delete Freeform Point Excluir Ponto Livre @@ -770,6 +799,7 @@ antiAlias Sharp Nítido Direct Selection Tool Ferramenta Seleção Direta Direction Handles Alças de Direção Disable Auto Add/Delete Desativar Adicionar/Excluir Automático + Interpolate Control Points When Moving Anchors Interpolar Alças de Direção ao Mover Pontos de Ancoragem Disable Opacity Mask Desativar Máscara de Opacidade Discard Descartar Discard Empty Type Descartar Texto Vazio @@ -962,6 +992,7 @@ antiAlias Sharp Nítido Enable Rubber Band for Habilitar Elástico para Enable Touch Gestures Habilitar Gestos de Toque Switch Selection and Drawing Modes Alternar Modos de Seleção e Desenho + Select Last Selection Tool Selecionar Última Ferramenta de Seleção Enable Touch Workspace Habilitar Espaço de Trabalho de Toque Enable copying of text, images and other content Habilitar cópia de texto, imagens e outro conteúdo Enable in-menu font previews Habilitar visualizações de fonte no menu @@ -1141,6 +1172,8 @@ antiAlias Sharp Nítido Files Arquivos Files of a PDF standard can't be password-protected. Arquivos de um padrão PDF não podem ser protegidos por senha. Files of this standard tag their colours with ICC profiles. Os arquivos deste padrão etiquetam suas cores com perfis ICC. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Os arquivos deste padrão etiquetam suas cores com perfis ICC, exceto as cores CMYK no perfil de intenção de saída, que são gravadas como DeviceCMYK. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. Com “Não incluir perfis” e uma intenção de saída CMYK, cada cor CMYK é gravada como DeviceCMYK, a menos que seja convertida para um destino CMYK de outro perfil. Fill Preenchimento Fill & Stroke Preenchimento e Traçado Fill Color Cor de Preenchimento @@ -1185,6 +1218,8 @@ antiAlias Sharp Nítido Reset Tracking and Kerning Redefinir Rastreamento e Kerning Reset Horizontal Scale Redefinir Escala Horizontal Highlight Font Name Destacar Nome da Fonte + Highlight Font Size Destacar Tamanho da Fonte + Other… Outro… Highlight Kerning Destacar Kerning Highlight Tracking Destacar Rastreamento Step Type Ajustar Texto em Incrementos @@ -1712,6 +1747,7 @@ antiAlias Sharp Nítido Load SVG into Clipboard Carregar SVG na Área de Transferência Load Text into Clipboard Carregar Texto na Área de Transferência Local Libraries Bibliotecas Locais + Locate Layer Localizar Camada Locate Object Localizar Objeto Location Local Location: Local: @@ -2114,6 +2150,9 @@ antiAlias Sharp Nítido Overprint Stroke Sobreimpressão de Traçado Overprint and Transparency Flattener Sobreimpressão e Achatamento de Transparência Overprint and Transparency Flattener Options Opções de Sobreimpressão e Achatamento de Transparência + Custom… Personalizado… + Custom Transparency Flattener Options Opções Personalizadas de Achatamento de Transparência + EPS has no alpha transparency, and Overprints sets whether overprints are kept. O EPS não tem transparência alfa, e Sobreimpressões define se as sobreimpressões são mantidas. Overprint: Sobreimpressão: Overprints: Sobreimpressões: Override Character Color Substituir Cor do Caractere @@ -2208,6 +2247,7 @@ antiAlias Sharp Nítido Play Current Selection Reproduzir Seleção Atual Save Actions… Salvar Ações… Load Actions… Carregar Ações… + Replace Actions… Substituir Ações… Reset Actions Redefinir Ações Replace the current actions with the default set? Substituir as ações atuais pelo conjunto padrão? Append adds the default set after the current sets instead. Anexar adiciona o conjunto padrão depois dos conjuntos atuais. @@ -2222,6 +2262,10 @@ antiAlias Sharp Nítido Polar Grid Tool Ferramenta Grade Polar Polygon Polígono Polygon Properties: Propriedades do Polígono: + Line Properties: Propriedades da Linha: + Line Length: Comprimento da Linha: + Line Angle: Ângulo da Linha: + Constrain Pie Angle Restringir Ângulo da Fatia Polygon Tool Ferramenta Polígono Portrait Retrato Portuguese Português @@ -2364,6 +2408,9 @@ digits Malayalam Malaiala Real World: Mundo Real: Real-time Drawing and Editing Desenho e Edição em Tempo Real Use Monitor Profile for Canvas Usar Perfil do Monitor para a Tela + Refresh Monitor Profile Atualizar Perfil do Monitor +@msg turn on Use Monitor Profile for Canvas first ative primeiro "Usar Perfil do Monitor para a Tela" +@msg this build doesn't read display profiles esta versão não lê perfis de monitor The canvas is drawn in sRGB. A tela é desenhada em sRGB. Canvas display profile: Perfil do monitor para a tela: The system matches the window to the display's colors. O sistema ajusta a janela às cores do monitor. @@ -2532,6 +2579,8 @@ digits Malayalam Malaiala Reselect Resselecionar Reset Redefinir Reset Bounding Box Redefinir Caixa Delimitadora + Rotate Bounding Box Girar Caixa Delimitadora + Rotate Bounding Box… Girar Caixa Delimitadora… Reset Envelope Mesh Redefinir Malha do Envelope Reset Envelope Shape Redefinir Forma do Envelope Reset Essentials Redefinir Essentials @@ -2570,6 +2619,7 @@ digits Malayalam Malaiala Reshape Segment Remodelar Segmento Reshape Tool Ferramenta Remodelar Reshape Type Area Remodelar Área de Texto + Resolution Resolução Resolution: Resolução: Responsive Responsivo Restore Restaurar @@ -2597,6 +2647,7 @@ digits Malayalam Malaiala The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. A roda do mouse com Cmd/Ctrl pressionado rola a tela para os lados. Dragging sideways on a numeric field's label changes the field's value. Arrastar para os lados sobre o rótulo de um campo numérico muda o valor do campo. A two-finger rotate gesture on a trackpad rotates the canvas view. Um gesto de rotação com dois dedos no trackpad gira a visualização da tela. + When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Ao mover pontos de ancoragem, cada curva com uma extremidade movida mantém sua forma em relação às extremidades. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Manter pressionado o atalho de uma ferramenta a escolhe até você soltar, e então a ferramenta anterior é escolhida de novo. Shows the bounding box while you move the selection or draw a shape. Mostra a caixa delimitadora enquanto você move a seleção ou desenha uma forma. Create Trim Marks draws Japanese-style marks instead of Roman ones. Criar Marcas de Corte desenha marcas no estilo japonês em vez de romanas. @@ -2627,6 +2678,29 @@ digits Malayalam Malaiala The unit for East Asian type measurements, which no field uses yet. A unidade das medidas de texto do Leste Asiático, que nenhum campo usa ainda. When on, a number typed without a unit into a field in picas is read in points. Quando ativado, um número digitado sem unidade em um campo em picas é lido em pontos. With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options. Com ID XML, os nomes dos objetos aparecem como IDs XML em Camadas, Variáveis e Opções de Camada. + The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl. O passo do tamanho do texto e da entrelinha: Cmd/Ctrl+Shift+. e Cmd/Ctrl+Shift+, mudam o tamanho em um passo, ou em cinco com Alt também; em texto horizontal, Alt com a seta para cima ou para baixo muda a entrelinha em um passo, ou em cinco com Cmd/Ctrl. + The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl. O passo do tracking e do kerning, em milésimos de em: em texto horizontal, Alt com a seta para a esquerda ou para a direita muda o kerning no cursor ou o tracking do texto selecionado em um passo, ou em cinco com Cmd/Ctrl. + The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. O passo do deslocamento da linha de base: em texto horizontal, Alt e Shift com a seta para cima ou para baixo movem a linha de base em um passo, ou em cinco com Cmd/Ctrl. + Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. Mostra as opções de texto japonês e de outros idiomas do Leste Asiático nos painéis Caractere, Parágrafo, OpenType e Glifos, e o comando Fontes compostas. + Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. Mostra as opções de texto árabe, hebraico e índico nos painéis Caractere e Parágrafo, como a direção do parágrafo, as kashidas e os dígitos. + The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. As ferramentas de seleção selecionam o texto só na linha de base, no quadro do texto de área ou no seu demarcador, e não em qualquer ponto dentro da sua caixa. + Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. Os menus de fontes listam cada fonte pelo nome em inglês; desativado, uma fonte que também tem um nome no próprio idioma mostra esse nome. + New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. O novo texto de área começa com Tamanho Automático ativado, então um quadro retangular de texto horizontal cresce ou encolhe em altura para caber o texto. + Font lists and the Type › Font menu show a sample of each font beside its name. As listas de fontes e o menu Fonte mostram uma amostra de cada fonte ao lado do nome. + Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on. As amostras de fontes são desenhadas em texto escuro sobre branco, seja qual for o brilho da interface; vale só enquanto as visualizações de fontes nos menus estão ativadas. + How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is. A altura de cada linha nas listas dos campos de fonte, como o do painel Caractere, e portanto o tamanho de cada amostra. + How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first. Quantas das últimas fontes usadas, de 1 a 15, Fontes Recentes e as listas de fontes mostram, da mais recente para a mais antiga. + When you change the font or font style of text, characters the new font has no glyph for keep the font they had. Ao mudar a fonte ou o estilo da fonte de um texto, os caracteres para os quais a nova fonte não tem glifo mantêm a fonte que tinham. + A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export. Um realce rosa na tela de desenho marca os glifos substituídos por recursos OpenType, como as ligaduras; ele não é impresso nem exportado. + With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from. Com a ferramenta Texto, selecionar um único caractere mostra ao lado dele, na tela de desenho, uma fileira dos seus glifos alternativos para escolher. + A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export. Um realce rosa na tela de desenho marca o texto desenhado com uma fonte substituta porque a fonte dele está ausente; ele não é impresso nem exportado. + New type made with a Type tool starts with placeholder text, selected, so typing replaces it. O novo texto criado com uma ferramenta de texto começa com um texto de preenchimento selecionado, que a digitação substitui. + Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list. Digitar um marcador de lista como 1. ou * e depois um espaço no início de um parágrafo transforma o parágrafo em uma lista. + Fonts in this folder show in the font menus and can be used without being installed. As fontes desta pasta aparecem nos menus de fontes e podem ser usadas sem ser instaladas. + Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows. Aplicar um estilo gráfico a um texto remove o preenchimento ou o traçado próprio dos caracteres onde o estilo tem um, para que a pintura do estilo apareça. + Align and Distribute measure point type by the ink of its glyphs instead of its em box. Alinhar e Distribuir medem o texto de ponto pela tinta dos seus glifos em vez da sua caixa em. + Align and Distribute measure area type by the ink of its glyphs instead of its frame. Alinhar e Distribuir medem o texto de área pela tinta dos seus glifos em vez do seu quadro. + The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box. A caixa delimitadora e o painel Transformar medem o texto de ponto pela tinta dos seus glifos em vez da sua caixa em. Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply. Ajusta o desenho, o movimento e a escala às subdivisões da grade, mesmo com a grade oculta; enquanto está ativado, Ajustar ao Pixel não se aplica. The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead. A cor das guias não selecionadas; uma prancheta com Rótulo das Guias desenha as próprias guias na cor do rótulo. Draws guides as solid lines or as dots, including the guides already in the document. Desenha as guias como linhas contínuas ou como pontos, inclusive as guias que já estão no documento. @@ -2700,6 +2774,7 @@ digits Malayalam Malaiala Rounded Rectangle Retângulo Arredondado Rounded Rectangle Tool Ferramenta Retângulo Arredondado Rounded Rectangle… Retângulo Arredondado… + Rows Linhas Rows: Linhas: Rule: Regra: Rulers Réguas @@ -2849,6 +2924,9 @@ digits Malayalam Malaiala Search commands, tools, panels and effects… Pesquisar comandos, ferramentas, painéis e efeitos… No commands match Nenhum comando corresponde {pos} of {total}: {name} {pos} de {total}: {name} + No menu item Nenhum item de menu + Toolbar Barra de Ferramentas + {toolbar}, in the {tool} group {toolbar}, no grupo {tool} @plural {n} result|{n} results {n} resultado|{n} resultados @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} de {n} resultado. Continue digitando para filtrá-los.|{shown} de {n} resultados. Continue digitando para filtrá-los. Recent Commands Comandos recentes @@ -2920,6 +2998,7 @@ digits Malayalam Malaiala Set Text Definir Texto Set Zoom Definir Zoom Set base color to the current color Definir cor base para a cor atual + Set the current fill or stroke to the selected color Definir o preenchimento ou traçado atual para a cor selecionada Set the selected color to the current color Definir a cor selecionada para a cor atual Setup… Configuração… Shadows and Glows Sombras e Brilhos @@ -3027,7 +3106,7 @@ digits Malayalam Malaiala Show handles when multiple anchors are selected Mostrar alças quando vários pontos de ancoragem estão selecionados Show in Folder Mostrar na Pasta Show {kind} Brushes Mostrar Pincéis de {kind} - Show/hide plate (Alt-click: only this plate) Mostrar/ocultar placa (Alt-clique: somente esta placa) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Mostrar/ocultar placa (Alt-clique: somente esta placa; Alt-clique de novo: todas as placas) Show: Mostrar: Shown with the optimised preview. Exibido com a visualização otimizada. Side 1: Lado 1: @@ -3265,6 +3344,13 @@ digits Malayalam Malaiala Threshold Limite Thumbnail View Exibição em Miniatura Tile Bloco + Tile All Vertically Todos em Bloco na Vertical + Tile All Horizontally Todos em Bloco na Horizontal + 2-Up Layout Layout de 2 + 3-Up Layout Layout de 3 + 4-Up Layout Layout de 4 + 6-Up Layout Layout de 6 + Arrange Documents Organizar Documentos Tile Edge Color Cor da Borda do Bloco Tile Edge Color… Cor da Borda do Bloco… Tile Range: Intervalo de Blocos: @@ -3426,6 +3512,8 @@ digits Malayalam Malaiala V Spacing: Espaçamento V: V: V: Variable Width Profile Perfil de Largura Variável + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. O pincel do traçado mantém o próprio tamanho, então um perfil de largura não o altera. Remova o pincel para usar um perfil. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. O pincel do traçado mantém o próprio tamanho, então um perfil de largura não o altera. Remova o pincel para usar um perfil. Variables Variáveis New Variable… Nova variável… Unbind Variable Desassociar variável @@ -3467,7 +3555,7 @@ digits Malayalam Malaiala Vertical Type on a Path Tool Ferramenta Texto Vertical em um Caminho Vertical: Vertical: View Exibir - View Artboard Only Exibir Somente a Mesa de Trabalho + View Artboard Contents Only Exibir Somente o Conteúdo da Mesa de Trabalho View Opacity Mask Exibir Máscara de Opacidade View PDF after saving Exibir PDF após salvar Viewing Angle: Ângulo de Visualização: @@ -3834,6 +3922,7 @@ font-technology Variable Variáveis Scatter: Dispersão: Rotation: Rotação: Rotation relative to: Rotação relativa a: + Hue Jitter: Variação de matiz: Brush Scale Options Opções de escala do pincel Scale Proportionately Dimensionar proporcionalmente Stretch to Fit Stroke Length Esticar para ajustar ao comprimento do traço @@ -4104,6 +4193,7 @@ axis Both Ambos @msg Saved {path} {path} salvo @msg Select text or click into text with the Type tool to insert glyphs Selecione texto ou clique em um texto com a ferramenta Texto para inserir glifos @msg Shape Builder: no region under the pointer Criador de formas: nenhuma região sob o ponteiro +@msg Shape Builder: select all paths you want to merge Criador de formas: selecione todos os traçados que deseja mesclar @msg Shape Builder: select paths or compound paths Criador de formas: selecione traçados ou traçados compostos @msg Show All Hidden Attributes: nothing is hidden Mostrar todos os atributos ocultos: nada está oculto @msg Split Into Grid: select paths large enough for the grid Dividir em grade: selecione traçados grandes o bastante para a grade @@ -4237,6 +4327,7 @@ axis Both Ambos @msg bad trailer trailer inválido @msg balance must be between 0 and 100 balance deve estar entre 0 e 100 @msg batch step {_1} (`{id}`) failed: {e} a etapa {_1} do lote (`{id}`) falhou: {e} +@msg action step {_1} (`{id}`) failed: {reason} a etapa {_1} da ação (`{id}`) falhou: {reason} @msg brightness must be dark|mediumDark|mediumLight|light brightness deve ser dark|mediumDark|mediumLight|light @msg can't encode the document: {0} não foi possível codificar o documento: {0} @msg can't parse shortcut `{c}` não foi possível interpretar o atalho `{c}` @@ -4256,6 +4347,7 @@ axis Both Ambos @msg choose a folder to export to escolha uma pasta para exportar @msg choose a location for the package escolha um local para o pacote @msg clipboard is empty a área de transferência está vazia +@msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: pelo menos uma cor deve permanecer na tabela de cores @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` não é uma cor como "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: no máximo {MAX_TABLE} cores @msg command `{0}` is not available right now: {1} o comando `{0}` não está disponível agora: {1} @@ -4322,9 +4414,15 @@ axis Both Ambos @msg no PNG encoder sem codificador de PNG @msg no active document nenhum documento ativo @msg no active perspective plane nenhum plano de perspectiva ativo +@msg the perspective grid is hidden a grade de perspectiva está oculta +@msg Automatic Plane Positioning is off: turn on anchorPoint or gridlineIntersection (perspective.widget.options) O posicionamento automático do plano está desativado: ative anchorPoint ou gridlineIntersection (perspective.widget.options) +@msg anchorPoint must be true or false anchorPoint deve ser true ou false +@msg gridlineIntersection must be true or false gridlineIntersection deve ser true ou false +@msg tolerance must be 0 or more tolerance deve ser 0 ou mais +@msg give `at` or `clear`, not both informe `at` ou `clear`, não ambos @msg no anchor points selected nenhum ponto de ancoragem selecionado -@msg `points` must be three [x, y] pairs of numbers `points` deve ter três pares de números [x, y] -@msg direct-select three anchor points, or give `points` selecione diretamente três pontos de ancoragem ou informe `points` +@msg `points` must be two or three [x, y] pairs of numbers `points` deve ter dois ou três pares de números [x, y] +@msg direct-select two or three anchor points, or give `points` selecione diretamente dois ou três pontos de ancoragem ou informe `points` @msg no circle passes through these points: two are the same or all three lie on one line nenhum círculo passa por esses pontos: dois são iguais ou os três estão na mesma reta @msg no app to open files here nenhum aplicativo para abrir arquivos aqui @msg no artboard nenhuma prancheta @@ -4426,6 +4524,9 @@ axis Both Ambos @msg no such user library biblioteca do usuário inexistente @msg no such view vista inexistente @msg no such width point ponto de largura inexistente +@msg `single` must be `incoming` or `outgoing` `single` deve ser `incoming` ou `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` e `outIndex` devem ser as duas metades de um mesmo ponto de largura descontínuo +@msg a discontinuous width point keeps its place um ponto de largura descontínuo mantém sua posição @msg no swatch `{name}` nenhuma amostra `{name}` @msg no swatch library `{l}` (see swatch.library.list) nenhuma biblioteca de amostras `{l}` (veja swatch.library.list) @msg no symbol instances selected nenhuma instância de símbolo selecionada @@ -4683,6 +4784,13 @@ axis Both Ambos @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} mais de {MAX_CSV_ROWS} conjuntos de dados: Importar Conjuntos de Dados lê no máximo {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} mais de {MAX_CSV_COLS} variáveis: Importar Conjuntos de Dados lê no máximo {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} as variáveis que não são de texto foram omitidas: {kinds} +variable-kind Visibility Visibilidade +variable-kind Linked File Arquivo Vinculado +variable-kind Graph Data Dados do Gráfico +variable-kind Unknown Desconhecido +variable-list-two {0}, {1} {0} e {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} e {1} @msg a new document won't read these variables back with their kind: {names} um novo documento não lerá essas variáveis de volta com o tipo delas: {names} @msg a new document refuses this file because of these variables: {names} um novo documento recusa este arquivo por causa destas variáveis: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them o cabeçalho `{header}` de `{name}` seria lido como a variável `{other}`: renomeie uma delas @@ -4708,6 +4816,8 @@ axis Both Ambos @msg {label}: lost track of a shape's style {label}: perdeu o estilo de uma forma @msg {label}: select paths {label}: selecione traçados @msg {label}: select paths, compound paths, groups or text {label}: selecione traçados, traçados compostos, grupos ou texto +@msg a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first uma linha ou outro caminho aberto que não envolve nenhuma área não altera a forma do resultado; para incluí-lo, aplique primeiro Objeto › Caminho › Contornar Traçado a ele +@msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first {label} produziu um resultado vazio: uma linha ou outro caminho aberto não envolve nenhuma área; para incluí-lo, aplique primeiro Objeto › Caminho › Contornar Traçado a ele @msg {label}… {label}… @msg {name}: CRC mismatch {name}: CRC não confere @msg {name}: no local header {name}: sem cabeçalho local @@ -4733,6 +4843,9 @@ axis Both Ambos @msgplural Discarded {n} recovered document|Discarded {n} recovered documents {n} documento recuperado descartado|{n} documentos recuperados descartados @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them {n} documento recuperado restaurado: salve-o para mantê-lo|{n} documentos recuperados restaurados: salve-os para mantê-los @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} Aberto com {n} observação: {first}|Aberto com {n} observações: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Copiado com {n} observação: {first}|Copiado com {n} observações: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Recortado com {n} observação: {first}|Recortado com {n} observações: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Imagem rastreada com {n} observação: {first}|Imagem rastreada com {n} observações: {first} @msgplural {notice}. Opened with {n} note: {first}|{notice}. Opened with {n} notes: {first} {notice}. Aberto com {n} observação: {first}|{notice}. Aberto com {n} observações: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} {path} salvo com {n} observação: {first}|{path} salvo com {n} observações: {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first {n} imagem incorporada; faltam {missing}: revincule-as primeiro|{n} imagens incorporadas; faltam {missing}: revincule-as primeiro @@ -4759,6 +4872,8 @@ axis Both Ambos @msg All colors are within the CMYK gamut Todas as cores estão dentro do gamut CMYK @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} cor está fora do gamut CMYK|{n} cores estão fora do gamut CMYK @msg Unembedded to {_1} Desincorporado para {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} {n} imagem desincorporada para {folder}|{n} imagens desincorporadas para {folder} +@msg every numbered name for {name} is taken in that folder todos os nomes numerados para {name} já existem nessa pasta @msg Reset {_1} Redefinir {_1} @msg Sent to {_1} Enviado para {_1} @msg {_1} files {_1} arquivos @@ -4774,6 +4889,8 @@ axis Both Ambos @msg Reload the page to go on (changes not saved yet may be lost). Recarregue a página para continuar (alterações ainda não salvas podem ser perdidas). @msg tool (a tool id) is required tool (um id de ferramenta) é obrigatório @msg {tool} isn't in a toolbar group of several tools {tool} não está em um grupo de barra de ferramentas com várias ferramentas +@msg Presentation Mode hides the toolbars: change the screen mode to show them o Modo de Apresentação oculta as barras de ferramentas: altere o modo de tela para mostrá-las +@msg Tab has hidden the toolbars: press Tab to show them Tab ocultou as barras de ferramentas: pressione Tab para mostrá-las @msg onto must name a panel floating in another group onto deve nomear um painel flutuante em outro grupo @msg below and above must name a panel floating in another group below e above devem nomear um painel flutuante em outro grupo @msg give only one of onto, below and above informe apenas um entre onto, below e above @@ -4851,6 +4968,9 @@ axis Both Ambos @msg automation path rejected: outside the read root {root}: {path} caminho da automação rejeitado: fora da raiz de leitura {root}: {path} @msg automation path rejected: outside the read roots {roots}: {path} caminho da automação rejeitado: fora das raízes de leitura {roots}: {path} @msg a linked JavaScript file is outside the read roots um arquivo JavaScript vinculado está fora das raízes de leitura +@msg a linked image file is outside the read roots um arquivo de imagem vinculado está fora das raízes de leitura +@msg a linked file's export folder is outside the read roots a pasta de exportação de um arquivo vinculado está fora das raízes de leitura +@msg a linked file's editing data can't be read to check it against the read roots não é possível ler os dados de edição de um arquivo vinculado para verificá-los em relação às raízes de leitura @msg automation path rejected: outside the write root {root}: {path} caminho da automação rejeitado: fora da raiz de gravação {root}: {path} @msg automation path rejected: outside the write roots {roots}: {path} caminho da automação rejeitado: fora das raízes de gravação {roots}: {path} @msg automation path rejected: path is empty caminho da automação rejeitado: o caminho está vazio @@ -5333,6 +5453,7 @@ axis Both Ambos Name 40% Nome 40% Name* @ 66.67 % (RGB/Preview) Nome* @ 66.67 % (RGB/Visualização) Name* @ 66.67% (RGB/Preview) Nome* @ 66.67% (RGB/Visualização) + Roundness Arredondamento Roundness: Arredondamento: Fixed Fixo Pressure Pressão @@ -5500,7 +5621,7 @@ axis Both Ambos Composite Fonts Fontes compostas Export Composite Fonts Exportar fontes compostas Import Composite Fonts Importar fontes compostas -@msg each font must be {name, parts} cada fonte deve ser {name, parts} +@msg each font must be {{name, parts}} cada fonte deve ser {{name, parts}} @msg unknown key `{k}`; a font takes name and parts chave desconhecida `{k}`; uma fonte aceita name e parts @msg each font needs a name cada fonte precisa de um nome @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` não pode nomear uma fonte composta (de 1 a {COMPOSITE_NAME_MAX} caracteres, sem caracteres de controle) @@ -5513,7 +5634,7 @@ axis Both Ambos @msg two composite fonts are named `{_1}` duas fontes compostas se chamam `{_1}` @msg `{_1}` is the name of an installed font `{_1}` é o nome de uma fonte instalada @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2} usa `{font}`, uma fonte composta -@msg give fonts: [{name, parts}…] informe fonts: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] informe fonts: [{{name, parts}}…] @msg path is empty path está vazio @msg fonts must be a list of composite fonts fonts deve ser uma lista de fontes compostas @msg names must be strings names deve conter strings @@ -5608,12 +5729,20 @@ axis Both Ambos [Normal Paragraph Style] [Estilo de Parágrafo Normal] Joins Junções Axis Eixo + Axis Angle Ângulo do eixo Run Executar Run Script Executar script Stop Script Parar script Show External Script Warning Mostrar aviso de scripts externos A Script Is Running Um script está em execução Script Alert Alerta do script + Script File Access Acesso do script a arquivos + The script asks to read a file you choose. O script pede para ler um arquivo que você escolher. + The script asks to read and write a file you choose. O script pede para ler e gravar um arquivo que você escolher. + The script asks to read and write a folder you choose, with everything in it. O script pede para ler e gravar uma pasta que você escolher, com todo o seu conteúdo. + Allow Once Permitir uma vez + Always Allow This Script Sempre permitir este script + Deny Negar A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Um script pode alterar os documentos abertos e gravar arquivos pelos comandos que executa. Execute apenas scripts em que você confia. Do not show this warning again Não mostrar este aviso novamente Stop the script and undo what it did? Then quit again. Parar o script e desfazer o que ele fez? Depois, saia novamente. @@ -5630,6 +5759,8 @@ axis Both Ambos @msg the script is no longer in the Scripts folder o script não está mais na pasta Scripts Some scripts were not listed Alguns scripts não foram listados The Scripts folder cannot be read Não é possível ler a pasta Scripts + Loading scripts… Carregando scripts… + The Scripts folder is still being read A pasta Scripts ainda está sendo lida @msg the script's run is no longer available a execução do script não está mais disponível @msg a failed command changed undo steps that could not be put back, so the script was stopped um comando que falhou alterou etapas de desfazer que não puderam ser restauradas, então o script foi interrompido @msg a recovery copy could not be written, so the script was not run não foi possível gravar uma cópia de recuperação, portanto o script não foi executado @@ -5642,8 +5773,6 @@ axis Both Ambos @msg Script file could not be read Não foi possível ler o arquivo de script @msg Script folder has more than 2,048 entries A pasta de script tem mais de 2.048 entradas @msg Script file open mode must be r, w, e or a O modo de abertura do arquivo de script deve ser r, w, e ou a -@msg Script file writing is not available A gravação de arquivos de script não está disponível -@msg Script file dialogs are not available As caixas de diálogo de arquivos de script não estão disponíveis @msg Script files cannot be opened in another application Arquivos de script não podem ser abertos em outro aplicativo @msg Script file access is unavailable on the web O acesso a arquivos de script não está disponível na web @msg Script has 256 files open O script tem 256 arquivos abertos @@ -5760,6 +5889,27 @@ liquify-list-end {0}, {1} {0} e {1} @msg there is no script engine named {name} não há nenhum mecanismo de script chamado {name} @msg Running a script Executando um script @msg Copied the script report Relatório do script copiado +@msg Script file access denied: {path} Acesso do script a arquivos negado: {path} +@msg Script file access to the app's own folders is not allowed O script não pode acessar as pastas do próprio aplicativo +@msg Script file cannot encode the text O arquivo do script não consegue codificar o texto +@msg Script file could not be written Não foi possível gravar o arquivo do script +@msg Script file dialogs need a person to answer them As caixas de diálogo de arquivo do script precisam de uma pessoa para respondê-las +@msg Script file is not open for writing O arquivo do script não está aberto para gravação +@msg Script file name is already in use O nome do arquivo do script já está em uso +@msg Script file name must be a name without a folder O nome do arquivo do script deve ser um nome sem pasta +@msg Script file permission can be kept only for a script run from a file A permissão de arquivos só pode ser mantida para um script executado a partir de um arquivo +@msg Script file permission could not be saved Não foi possível salvar a permissão de arquivos do script +@msg Script folder is not empty A pasta do script não está vazia +@msg Script files cannot make aliases Os arquivos do script não podem criar aliases +@msg Script file hidden setting cannot be changed A configuração de oculto do arquivo do script não pode ser alterada +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: uma caixa de diálogo de arquivo não pode abrir dentro de um callback de uma função integrada, de um getter, de uma conversão ou de um arquivo que $.evalFile executa; chame-a a partir do próprio código do script +@msg the script wrote more file data than one run may write (32 MiB) o script gravou mais dados de arquivo do que uma execução pode gravar (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` para a caixa de diálogo de arquivo de um script deve ser um destes: once, always, deny, stop +@msg choose a file or folder first, or deny escolha primeiro um arquivo ou uma pasta, ou negue +@msg the script file permissions could not be saved: {e} não foi possível salvar as permissões de arquivos dos scripts: {e} +@msg this script's file access can be allowed only once o acesso a arquivos deste script só pode ser permitido uma vez +@msg Only the person at the keyboard can allow a script's file access Somente a pessoa ao teclado pode permitir o acesso a arquivos de um script +@msg A script is given at most 2,048 files: the files picked after them were left out Um script recebe no máximo 2.048 arquivos: os arquivos escolhidos depois deles foram deixados de fora @msg Copied the link info Informações do link copiadas @msg This shortcut file is in a form VectorCraft can't read. Este arquivo de atalhos está em um formato que o VectorCraft não consegue ler. @msg axis must be "vertical", "horizontal" or an angle in degrees, not `{v}` axis deve ser "vertical", "horizontal" ou um ângulo em graus, não `{v}` @@ -5864,6 +6014,7 @@ liquify-list-end {0}, {1} {0} e {1} Right Diagonal Diagonal Direita Left Diagonal Diagonal Esquerda Linux Display Server Servidor de Exibição do Linux + Low-Latency Drawing Desenho de Baixa Latência X11 (XWayland) When a Pen Is Attached X11 (XWayland) Quando Houver uma Caneta Conectada If a drawing tablet's pen doesn't draw, choose an X11 (XWayland) option. Se a caneta de uma mesa digitalizadora não desenhar, escolha uma opção X11 (XWayland). X11 (XWayland) X11 (XWayland) @@ -6082,6 +6233,7 @@ effect Regular Regular Ascent Ascensão Cap Height Altura das Maiúsculas x Height Altura do x + Em Box Height Altura da Caixa Eme Justify Justificar First Baseline Primeira Linha de Base Vertical Align Alinhamento Vertical @@ -6248,6 +6400,7 @@ mark-style Japanese Japonesas Cove Côncavo Depth Profundidade Front Frente + Side Lateral Isometric Bottom Isométrico Inferior Isometric Left Isométrico Esquerdo Isometric Right Isométrico Direito @@ -6342,7 +6495,7 @@ mark-style Japanese Japonesas @msg each of `{GRAPHICS}` must be an object cada item de `{GRAPHICS}` deve ser um objeto @msg `{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}` as entradas de `{GRAPHICS}` aceitam symbol, face, x, y, scale e rotation, não `{k}` @msg each of `{GRAPHICS}` needs `symbol`, the name of a symbol cada item de `{GRAPHICS}` precisa de `symbol`, o nome de um símbolo -@msg `{GRAPHICS}` face must be front or back face de `{GRAPHICS}` deve ser front ou back +@msg `{GRAPHICS}` face must be front, back or side face de `{GRAPHICS}` deve ser front, back ou side @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} de `{GRAPHICS}` deve ser um número de {lo} a {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` deve ser uma matriz @msg Graphics map onto the Plane, Extrude and Revolve object types Os gráficos são mapeados nos tipos de objeto Plano, Extrusão e Revolver @@ -6466,6 +6619,8 @@ mark-style Japanese Japonesas two points, then move and click to place an aligned, horizontal or vertical dimension | em dois pontos, depois mova e clique para posicionar uma cota alinhada, horizontal ou vertical | Color Panel Options Opções do Painel Cor @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` deve ser grayscale, rgb, hsb, cmyk ou websafe +@msg `view` must be wheel or box `view` deve ser wheel ou box +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` deve ser hue, saturation, brightness, red, green ou blue @msg the image can't be read as a texture a imagem não pode ser lida como textura # User Interface › Accent Color @@ -7293,6 +7448,12 @@ anchor Points: Pontos: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` deve ser "free", "keepAngles" ou "symmetric" @msg `{key}` must be [x, y] `{key}` deve ser [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Conversor de unidades + Unit Converter Panel Painel Conversor de unidades + Copy with Units Copiar com unidades + From Selection Da seleção + # Color Effects add-on: Select by Color Kind. Select by Color Kind Selecionar por tipo de cor Objects with Spot Colors Objetos com cores spot @@ -7636,6 +7797,14 @@ breakText Glyphs Glifos Remove Gaps Remover distâncias @msg that makes too many pieces (at most 100000): make the dashes longer isso gera peças demais (no máximo 100000): aumente os traços @msg select paths, or segments, to divide selecione demarcadores ou segmentos para dividir +# Path Precision Tools add-on: Smooth Bridge. + Smooth Bridge… Ponte suave… + Smooth Bridge Ponte suave + Keep Originals Manter originais +@msg select two circles to bridge selecione dois círculos para unir +@msg one circle is inside the other um círculo está dentro do outro +@msg the circles are too far apart for this radius: raise the radius os círculos estão muito afastados para este raio: aumente o raio +@msg the circles are too far apart for this radius os círculos estão muito afastados para este raio # Path Precision Tools add-on: Common Tangents. Common Tangents… Tangentes comuns… Common Tangents Tangentes comuns @@ -7829,6 +7998,11 @@ swatch Orange Red Vermelho-alaranjado Overlay Edge Sobreposição de bordas Part of ArtCraft. MIT OR Apache-2.0. Fonts: Source Sans 3, Inter, JetBrains Mono, Noto Sans SC (OFL). Icons: Lucide (ISC) + VectorCraft. Parte do ArtCraft. MIT OR Apache-2.0. Fontes: Source Sans 3, Inter, JetBrains Mono, Noto Sans SC (OFL). Ícones: Lucide (ISC) + VectorCraft. Path Length Comprimento do caminho + Grid Size Tamanho da Grade + Grid Colors Cores da Grade + Flattener Preset Predefinido de achatamento + X X + Y Y PDF/X-1a:2001 PDF/X-1a:2001 PDF/X-3:2002 PDF/X-3:2002 PDF/X-4:2010 PDF/X-4:2010 @@ -8216,6 +8390,14 @@ swatch Yellow Green Verde-amarelado @msg `answers` has more than {MAX_ANSWERS} answers `answers` tem mais de {MAX_ANSWERS} respostas @msg `answers` is larger than 1 MiB `answers` tem mais de 1 MiB @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` é só para uma execução sem ninguém a quem perguntar: no app, a pessoa responde a cada caixa de diálogo +@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` deve ser um número inteiro de 1 a {_1} +@msg `args{place}` is nested more than 64 levels deep `args{place}` está aninhado em mais de 64 níveis +@msg `args` must be an object `args` deve ser um objeto +@msg `args` is larger than 1 MiB `args` tem mais de 1 MiB +@msg `path` is empty `path` está vazio +@msg `installed` takes a `path`, not a `source` `installed` aceita um `path`, não um `source` +@msg `path` must name a .js or .jsx file `path` deve indicar um arquivo .js ou .jsx +@msg give exactly one of `path` and `source` informe exatamente um de `path` e `source` @msg `answers` must be a list of answers `answers` deve ser uma lista de respostas @msg `artboard` must be the index of an artboard of the document `artboard` deve ser o índice de uma prancheta do documento @msg `artboardsAt` must be [x, y] `artboardsAt` deve ser [x, y] @@ -8370,7 +8552,7 @@ swatch Yellow Green Verde-amarelado @msg `scale` must be a number from 0.001 to 1000 `scale` deve ser um número de 0.001 a 1000 @msg `scale` must be a number in (0, 100] `scale` deve ser um número em (0, 100] @msg `scope.{key}` must be a non-empty array `scope.{key}` deve ser uma matriz não vazia -@msg `scope` must be "document", {artboards} or {layers} `scope` deve ser "document", {artboards} ou {layers} +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` deve ser "document", {{artboards: [index, …]}} ou {{layers: [id, …]}} @msg `scope` must be "selection" or "document", not {other} `scope` deve ser "selection" ou "document", não {other} @msg `script` must be a string `script` deve ser uma string @msg `seriesIndexes` is a non-empty list of series indexes `seriesIndexes` é uma lista não vazia de índices de séries @@ -8449,6 +8631,8 @@ swatch Yellow Green Verde-amarelado @msg `{f}` is the copy of a document open now `{f}` é a cópia de um documento aberto agora @msg `{id}` is no writable format (see document.formats) `{id}` não é um formato gravável (veja document.formats) @msg `{id}` isn't a loaded library `{id}` não é uma biblioteca carregada +@msg `{file}` has no swatches of its own `{file}` não tem amostras próprias +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` tem amostras de padrão, que um arquivo .vcswatches não pode conter @msg `{key}` has no colours `{key}` não tem cores @msg `{key}` holds more than {MAX_EDIT_WORDS} words `{key}` contém mais de {MAX_EDIT_WORDS} palavras @msg `{key}` is a design name `{key}` é o nome de um projeto @@ -8740,7 +8924,13 @@ swatch Yellow Green Verde-amarelado @msg colorModel must be {own} (the document's mode), grayscale or bitmap colorModel deve ser {own} (o modo do documento), grayscale ou bitmap @msg colour groups can't go into colour groups grupos de cores não podem ficar dentro de grupos de cores @msg colour, mode and spot apply to solid-colour swatches only colour, mode e spot se aplicam somente a amostras de cor sólida -@msg column {column}: `{cell}` is a `%` column of graph data files, which are not read coluna {column}: `{cell}` é uma coluna `%` de arquivos de dados de gráfico, que não são lidos +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path linha {line}, coluna {column}: o arquivo de dados de gráfico `{path}` de `{var}` é um caminho relativo: informe `base` ou um caminho absoluto +@msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} linha {line}, coluna {column}: não é possível ler o arquivo de dados de gráfico de `{var}`: {e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` isn't followed: {r} linha {line}, coluna {column}: o arquivo de dados de gráfico `{path}` de `{var}` não é seguido: {r} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes linha {line}, coluna {column}: o arquivo de dados de gráfico `{path}` de `{var}` tem mais de {MAX_GRAPH_DATA_FILE} bytes +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes linha {line}, coluna {column}: o arquivo de dados de gráfico `{path}` de `{var}` gera um valor de gráfico com mais de {MAX_GRAPH_CSV} bytes +@msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all linha {line}, coluna {column}: os arquivos de dados de gráfico têm mais de {MAX_GRAPH_FILES_TOTAL} bytes no total +@msg `base` is empty `base` está vazio @msg column {column}: `{cell}` names `{name}`, which is a {_1} variable coluna {column}: `{cell}` indica `{name}`, que é uma variável de {_1} @msg column {column}: `{cell}` names no variable coluna {column}: `{cell}` não indica nenhuma variável @msg column {column}: the variable name is longer than {MAX_NAME} characters coluna {column}: o nome da variável tem mais de {MAX_NAME} caracteres @@ -8751,6 +8941,7 @@ swatch Yellow Green Verde-amarelado @msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes formas compostas aceitam caminhos, caminhos compostos, grupos, formas compostas, texto, mesclagens e envelopes @msg compound {_1} must contain exactly one open path to join o composto {_1} deve conter exatamente um caminho aberto para unir @msg connect needs a path other than the one extended connect precisa de um caminho diferente do que foi estendido +@msg connect needs extend connect precisa de extend @msg connect needs id connect precisa de id @msg connect path has no open end o caminho de connect não tem extremidade aberta @msg continuation must be an array of path chunks continuation deve ser uma matriz de trechos de caminho @@ -9262,7 +9453,7 @@ swatch Yellow Green Verde-amarelado @msg nothing to print: every artboard picked is blank nada para imprimir: todas as pranchetas escolhidas estão em branco @msg nothing to print: the document has no art that prints nada para imprimir: o documento não tem arte imprimível @msg nothing to repeat nada para repetir -@msg numbers out of order in {_1} quantifier números fora de ordem no quantificador {_1} +@msg numbers out of order in {{}} quantifier números fora de ordem no quantificador {{}} @msg object is not a path o objeto não é um caminho @msg object transparency cannot be sampled onto highlighted characters; disable Transparency in Eyedropper Options or select the whole object a transparência do objeto não pode ser aplicada aos caracteres destacados; desative Transparência nas Opções do Conta-gotas ou selecione o objeto inteiro @msg object {_1} can't be set as point type o objeto {_1} não pode ser definido como texto de ponto @@ -9622,7 +9813,7 @@ swatch Yellow Green Verde-amarelado @msg the page has no area a página não tem área @msg the page's type in an unread object's box isn't in its page art o texto da página na caixa de um objeto não lido não está na arte da página @msg the paint behind the proxy is not a gradient a pintura por trás do proxy não é um gradiente -@msg the paint is not a freeform gradient (apply one with paint.editGradient {kind}) a pintura não é um gradiente de forma livre (aplique um com paint.editGradient {kind}) +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) a pintura não é um gradiente de forma livre (aplique um com paint.editGradient {{kind: "freeform"}}) @msg the parameters or body do not form one function os parâmetros ou o corpo não formam uma única função @msg the parent must be a layer or sublayer o pai deve ser uma camada ou subcamada @msg the pasted SVG filter {name} draws differently from the document's filter of that name, and no free name fits it o filtro SVG colado {name} desenha de modo diferente do filtro do documento com esse nome, e nenhum nome livre serve para ele @@ -9988,3 +10179,13 @@ swatch Yellow Green Verde-amarelado @msg A panel is not joined to the rest by a crease. Um painel não está unido ao restante por nenhuma linha de vinco. @msg A fold line is on a non-printing layer. Uma linha de dobra está em uma camada não imprimível. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Painéis: {panels}, dobradiças: {hinges}, erros: {errors}, avisos: {warnings} + Fold Preview Visualização da Dobra + Fold Dobra + Show Fold Lines Mostrar Linhas de Dobra + Three-Quarter Três Quartos + Open a document to preview its folded shape. Abra um documento para visualizar sua forma dobrada. +@msg Check the fold lines first. Verifique primeiro as linhas de dobra. +@msg Panels: {panels}, hinges: {hinges} Painéis: {panels}, dobradiças: {hinges} +@msg Other blanks not shown: {count} Outras planificações não exibidas: {count} +@msg A joint does not close by {gap} pt. Uma junção não fecha por {gap} pt. +@msg Two panels pass through each other. Dois painéis se atravessam. diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index d1593508d3..74ea8a881b 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -9,7 +9,7 @@ # Coverage: the whole interface — every menu string and every `tl!` literal (`complete_menus`, # `untranslated_report` lists gaps). Left in English on purpose (`MENU_KEEP_AS_IS` in the tests): the product name, language # names, OpenType, the built-in workspace names and the bracketed perspective grid preset names. -# Photoshop-style raster effects (Effect menu, their dialogs). +# Raster effects (Effect menu, their dialogs). Glowing Edges… Светящиеся края… Glowing Edges Светящиеся края Edge Width Ширина края @@ -117,6 +117,7 @@ Add Anchor Point Добавить опорную точку Add Anchor Point Tool Инструмент «Добавить опорную точку» Add Anchor Points Добавить опорные точки + Add Around Добавить вокруг объекта Add Effect Добавить эффект Add Freeform Line Добавить произвольную линию Add Freeform Point Добавить произвольную точку @@ -138,8 +139,12 @@ Add to Swatches Добавить в образцы Add Used Colors Добавить использованные цвета Additional Plug-ins Folder Папка дополнительных модулей + Plug-in Instruction Budget Бюджет инструкций модулей Additional Fonts Folder Папка дополнительных шрифтов Adjust Adjoining Width Points Настроить смежные точки ширины + Incoming Входящая + Outgoing Исходящая + Single Width Only Только одна ширина Adjust Color Balance… Настроить цветовой баланс… Adjust Colors Настроить цвета Adjust Options: Параметры настройки: @@ -194,6 +199,7 @@ Angle: Угол: Angles Углы Animated Zoom Анимированное масштабирование + Anti Alias Сглаживание Anti-alias Сглаживание Anti-Alias Сглаживание Anti-alias Rasters Сглаживать растровые изображения @@ -301,7 +307,7 @@ font-technology Variable Вариативные Background Contents Содержимое фона Background: Фон: Backspace Backspace - Bar Graph Tool Инструмент «Гистограмма» + Bar Graph Tool Инструмент «Линейчатая диаграмма» Baseline Базовая линия Baseline Shift Смещение базовой линии Basic Latin Основная латиница @@ -359,6 +365,12 @@ font-technology Variable Вариативные Brush Definition Определение кисти Brush Libraries Библиотеки кистей Brush Options… Параметры кисти… + Options of Selected Object… Параметры выделенного объекта… + Options of Selected Object Параметры выделенного объекта +@msg no path painted with a brush is selected не выделен контур, нарисованный кистью +@msg the selected paths are painted with brushes of different types выделенные контуры нарисованы кистями разных типов +@msg give `params` or `reset`, not both укажите `params` или `reset`, но не оба +@msg a bristle brush has no options of its own on a path у щетинной кисти нет собственных параметров на контуре Brush Strokes Мазки кисти Brushes Кисти Built-in Libraries Встроенные библиотеки @@ -415,6 +427,12 @@ font-technology Variable Вариативные Character Alignment Выравнивание символов Character / Paragraph Символ / Абзац Character Rotation Поворот символов + Chinese Big 5 Китайская Big 5 + Cyrillic Кириллица + Greek Греческая + Turkish Турецкая + Baltic Балтийская + Central European Центральноевропейская Character Set: Набор символов: Character Style Стиль символа Character Style Options Параметры стиля символа @@ -477,6 +495,8 @@ font-technology Variable Вариативные Choose a folder Выберите папку Choose… Выбрать… Circle Круг + Circle Tool Инструмент «Круг» + Circle too large Круг слишком большой Classic Defaults Классические значения по умолчанию Clean Up… Очистить… Clear Очистить @@ -552,6 +572,7 @@ font-technology Variable Вариативные Color Mixer (Shift-click the chip) Смеситель цветов (Shift+щелчок по образцу) Color Mode Цветовой режим Color Mode: Цветовой режим: + Color Model Цветовая модель Color Model: Цветовая модель: Color Models Цветовые модели Color Picker Палитра цветов @@ -572,12 +593,18 @@ font-technology Variable Вариативные Saturation and brightness Насыщенность и яркость Color field Цветовое поле {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Вид «Круг» + Box View Вид «Квадрат» + Box Channel Канал квадрата + Color box Цветовой квадрат + Color Wheel Options Параметры цветового круга Color Type: Тип цвета: Color: Цвет: Colorize Тонировать Colors Цвета Colors: Цвета: Column Graph Tool Инструмент «Гистограмма» + Columns Столбцы Columns: Столбцы: Column… Столбец… Combine Slices Объединить фрагменты @@ -788,6 +815,8 @@ font-technology Variable Вариативные Delete Artboard Удалить монтажную область Delete Artboards Удалить монтажные области Delete Brush Удалить кисть + Delete Color Удалить цвет + Restore Generated Table Восстановить созданную таблицу Delete Character Style Удалить стиль символа Delete Empty Artboards Удалить пустые монтажные области Delete Freeform Point Удалить произвольную точку @@ -856,6 +885,7 @@ font-technology Variable Вариативные Direct Selection Tool Инструмент «Прямое выделение» Direction Handles Маркеры направления Disable Auto Add/Delete Отключить авто-добавление/удаление + Interpolate Control Points When Moving Anchors Интерполировать маркеры направления при перемещении опорных точек Disable Opacity Mask Отключить непрозрачную маску Discard Отменить Discard Empty Type Отменить пустой текст @@ -1072,6 +1102,7 @@ font-technology Variable Вариативные Enable text access for screen readers Разрешить доступ к тексту для программ чтения с экрана Enable Touch Gestures Включить сенсорные жесты Switch Selection and Drawing Modes Переключить режимы выделения и рисования + Select Last Selection Tool Выбрать последний инструмент выделения Enable Touch Workspace Включить сенсорную рабочую среду Encoding Кодировка Encoding: Кодировка: @@ -1254,6 +1285,8 @@ font-technology Variable Вариативные Files Файлы Files of a PDF standard can't be password-protected. Файлы стандарта PDF не могут быть защищены паролем. Files of this standard tag their colours with ICC profiles. Файлы этого стандарта помечают свои цвета профилями ICC. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Файлы этого стандарта помечают свои цвета профилями ICC, кроме цветов CMYK в профиле назначения вывода, которые записываются как DeviceCMYK. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. При «Не включать профили» и назначении вывода CMYK каждый цвет CMYK записывается как DeviceCMYK, если он не преобразуется в назначение CMYK с другим профилем. Fill Заливка Fill & Stroke Заливка и обводка Fill (X), double-click for the Color Picker Заливка (X), дважды щёлкните для палитры цветов @@ -1303,6 +1336,8 @@ font-technology Variable Вариативные Reset Tracking and Kerning Сбросить трекинг и кернинг Reset Horizontal Scale Сбросить масштаб по горизонтали Highlight Font Name Выделить имя шрифта + Highlight Font Size Выделить размер шрифта + Other… Другой… Highlight Kerning Выделить кернинг Highlight Tracking Выделить трекинг Spacing Интервал @@ -2011,7 +2046,7 @@ file-filter Templates Шаблоны Line Cut Разрезание линий Line Cut Tool Инструмент «Разрезание линий» Line Endings: Окончания линий: - Line Graph Tool Инструмент «Линейчатая диаграмма» + Line Graph Tool Инструмент «График» Line Segment Отрезок Line Segment Tool Инструмент «Отрезок» Line Segment Tool Options Параметры инструмента «Отрезок» @@ -2057,6 +2092,7 @@ file-filter Templates Шаблоны Load SVG into Clipboard Загрузить SVG в буфер обмена Load Text into Clipboard Загрузить текст в буфер обмена Local Libraries Локальные библиотеки + Locate Layer Найти слой Locate Object Найти объект Locate Selected Objects Находить выделенные объекты Location Расположение @@ -2251,6 +2287,7 @@ file-filter Templates Шаблоны Scatter: Рассеивание: Rotation: Поворот: Rotation relative to: Поворот относительно: + Hue Jitter: Разброс тона: Brush Scale Options Параметры масштабирования кисти Scale Proportionately Масштабировать пропорционально Stretch to Fit Stroke Length Растянуть по длине обводки @@ -2287,6 +2324,7 @@ file-filter Templates Шаблоны Black becomes the stroke color and white stays white. Other colors become tints of the stroke color by their lightness. Чёрный становится цветом обводки, а белый остаётся белым. Остальные цвета становятся оттенками цвета обводки, и чем светлее цвет, тем светлее его оттенок. Black and white stay as they are. Dark colors become shades of the stroke color and light colors become tints of it. Чёрный остаётся чёрным, а белый остаётся белым. Остальные цвета становятся тенями цвета обводки, если они тёмные, и его оттенками, если они светлые. The key color becomes the stroke color. The other colors shift their hue by the same amount and keep their saturation and brightness. Ключевой цвет становится цветом обводки. Остальные цвета сдвигаются по цветовому кругу на столько же, на сколько ключевой цвет, и сохраняют насыщенность и яркость. + Roundness Округлость Roundness: Округлость: Fixed Фиксированный Pressure Нажим @@ -2592,6 +2630,9 @@ file-filter Templates Шаблоны Overprint Наложение Overprint and Transparency Flattener Наложение и объединение прозрачностей Overprint and Transparency Flattener Options Параметры наложения и объединения прозрачностей + Custom… Пользовательские… + Custom Transparency Flattener Options Пользовательские параметры объединения прозрачностей + EPS has no alpha transparency, and Overprints sets whether overprints are kept. В EPS нет альфа-прозрачности, а параметр «Наложения» определяет, сохраняются ли наложения. Overprint Black… Наложение чёрного… Overprint Fill Наложение заливки Overprint Preview Просмотр наложения @@ -2641,6 +2682,11 @@ file-filter Templates Шаблоны Pathfinders: Обработка контуров: Paths Контуры Path Length Длина контуров + Grid Size Размер сетки + Grid Colors Цвета сетки + Flattener Preset Набор объединения + X X + Y Y Paths: {paths} Anchors: {anchors} Colors: {colors} Контуры: {paths} Опорные точки: {anchors} Цвета: {colors} Pattern Узор Pattern Editing Редактирование узора @@ -2700,6 +2746,7 @@ diagnostics ui интерфейс Play Current Selection Воспроизвести текущее выделение Save Actions… Сохранить действия… Load Actions… Загрузить действия… + Replace Actions… Заменить действия… Reset Actions Сбросить действия Replace the current actions with the default set? Заменить текущие действия набором по умолчанию? Append adds the default set after the current sets instead. Кнопка «Добавить» вместо этого добавляет набор по умолчанию после текущих наборов. @@ -2715,6 +2762,10 @@ diagnostics ui интерфейс Polar Grid Tool Инструмент «Полярная сетка» Polygon Многоугольник Polygon Properties: Свойства многоугольника: + Line Properties: Свойства линии: + Line Length: Длина линии: + Line Angle: Угол линии: + Constrain Pie Angle Сохранять угол сектора Polygon Tool Инструмент «Многоугольник» Portrait Книжная Power Saving (integrated) Энергосбережение (встроенная) @@ -2876,6 +2927,9 @@ digits Malayalam Малаялам Real World: Реальный мир: Real-time Drawing and Editing Рисование и редактирование в реальном времени Use Monitor Profile for Canvas Использовать профиль монитора для холста + Refresh Monitor Profile Обновить профиль монитора +@msg turn on Use Monitor Profile for Canvas first сначала включите «Использовать профиль монитора для холста» +@msg this build doesn't read display profiles эта сборка не читает профили дисплеев The canvas is drawn in sRGB. Холст отображается в sRGB. Canvas display profile: Профиль дисплея для холста: The system matches the window to the display's colors. Система согласует цвета окна с дисплеем. @@ -3068,6 +3122,8 @@ digits Malayalam Малаялам Reselect Выделить снова Reset Сбросить Reset Bounding Box Сбросить ограничительную рамку + Rotate Bounding Box Повернуть ограничительную рамку + Rotate Bounding Box… Повернуть ограничительную рамку… Reset Envelope Mesh Сбросить сетку оболочки Reset Envelope Shape Сбросить форму оболочки Reset Essentials Сбросить «Основные» @@ -3109,6 +3165,7 @@ digits Malayalam Малаялам Reshape Segment Изменить форму сегмента Reshape Tool Инструмент «Изменение формы» Reshape Type Area Изменить форму текстовой области + Resolution Разрешение Resolution: Разрешение: Responsive Адаптивный Restore Восстановить @@ -3135,6 +3192,7 @@ digits Malayalam Малаялам The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Колесо мыши с нажатой Cmd/Ctrl прокручивает холст по горизонтали. Dragging sideways on a numeric field's label changes the field's value. Перетаскивание по подписи числового поля в сторону меняет значение поля. A two-finger rotate gesture on a trackpad rotates the canvas view. Жест поворота двумя пальцами на трекпаде поворачивает вид холста. + When you move anchor points, each curve with one moved end keeps its shape relative to its ends. При перемещении опорных точек каждая кривая с одним перемещённым концом сохраняет форму относительно своих концов. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Пока вы удерживаете клавишу инструмента, он остаётся выбранным, а после отпускания снова выбирается предыдущий инструмент. Shows the bounding box while you move the selection or draw a shape. Показывает ограничивающую рамку, пока вы перемещаете выделение или рисуете фигуру. Create Trim Marks draws Japanese-style marks instead of Roman ones. «Создать метки подрезки» рисует метки в японском стиле вместо западных. @@ -3165,6 +3223,29 @@ digits Malayalam Малаялам The unit for East Asian type measurements, which no field uses yet. Единица для размеров восточноазиатского текста, которую пока не использует ни одно поле. When on, a number typed without a unit into a field in picas is read in points. Если включено, число, введённое без единицы в поле в пиках, читается в пунктах. With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options. При XML ID имена объектов показываются как XML ID в «Слоях», «Переменных» и «Параметрах слоя». + The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl. Шаг размера текста и интерлиньяжа: Cmd/Ctrl+Shift+. и Cmd/Ctrl+Shift+, меняют размер на один шаг, а вместе с Alt — на пять; в горизонтальном тексте Alt со стрелкой вверх или вниз меняет интерлиньяж на один шаг, а с Cmd/Ctrl — на пять. + The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl. Шаг трекинга и кернинга в тысячных долях em: в горизонтальном тексте Alt со стрелкой влево или вправо меняет кернинг у курсора или трекинг выделенного текста на один шаг, а с Cmd/Ctrl — на пять. + The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. Шаг смещения базовой линии: в горизонтальном тексте Alt и Shift со стрелкой вверх или вниз сдвигают базовую линию на один шаг, а с Cmd/Ctrl — на пять. + Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. Показывает параметры японского и другого восточноазиатского текста на панелях «Символ», «Абзац», «OpenType» и «Глифы», а также команду «Составные шрифты». + Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. Показывает параметры арабского, еврейского и индийского текста на панелях «Символ» и «Абзац», например направление абзаца, кашиды и цифры. + The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. Инструменты выделения выделяют текст только на его базовой линии, рамке текста в области или его контуре, а не в любом месте внутри его рамки. + Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. Меню шрифтов показывают каждый шрифт под английским названием; если выключено, шрифт, у которого есть название на собственном языке, показывает это название. + New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. Новый текст в области создаётся с включённым авторазмером, поэтому прямоугольная рамка горизонтального текста растёт или уменьшается по высоте под свой текст. + Font lists and the Type › Font menu show a sample of each font beside its name. Списки шрифтов и меню «Шрифт» показывают образец каждого шрифта рядом с его названием. + Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on. Образцы шрифтов рисуются тёмным текстом на белом при любой яркости интерфейса; это действует, только пока включён просмотр шрифтов в меню. + How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is. Высота каждой строки в списках полей шрифта, например на панели «Символ», а значит, и размер каждого образца. + How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first. Сколько последних использованных шрифтов, от 1 до 15, показывают «Последние шрифты» и списки шрифтов, начиная с самого нового. + When you change the font or font style of text, characters the new font has no glyph for keep the font they had. Когда вы меняете шрифт или начертание текста, символы, для которых в новом шрифте нет глифа, сохраняют прежний шрифт. + A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export. Розовая подсветка на холсте отмечает глифы, заменённые функциями OpenType, например лигатуры; она не печатается и не экспортируется. + With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from. С инструментом «Текст» при выделении одного символа рядом с ним на холсте появляется ряд его альтернативных глифов для выбора. + A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export. Розовая подсветка на холсте отмечает текст, нарисованный заменяющим шрифтом из-за отсутствия его шрифта; она не печатается и не экспортируется. + New type made with a Type tool starts with placeholder text, selected, so typing replaces it. Новый текст, созданный текстовым инструментом, начинается с выделенного текста-заполнителя, который заменяется вводом. + Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list. Если в начале абзаца ввести маркер списка, например 1. или *, а затем пробел, абзац становится списком. + Fonts in this folder show in the font menus and can be used without being installed. Шрифты из этой папки появляются в меню шрифтов, и их можно использовать без установки. + Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows. Применение графического стиля к тексту убирает собственную заливку или обводку символов там, где они есть у стиля, чтобы была видна краска стиля. + Align and Distribute measure point type by the ink of its glyphs instead of its em box. «Выровнять» и «Распределить» измеряют текст из точки по краске его глифов, а не по его em-квадрату. + Align and Distribute measure area type by the ink of its glyphs instead of its frame. «Выровнять» и «Распределить» измеряют текст в области по краске его глифов, а не по его рамке. + The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box. Ограничительная рамка и панель «Трансформирование» измеряют текст из точки по краске его глифов, а не по его em-квадрату. Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply. Привязывает рисование, перемещение и масштабирование к делениям сетки, даже когда сетка скрыта; пока параметр включен, «Привязать к пикселю» не действует. The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead. Цвет невыделенных направляющих; монтажная область с «Меткой направляющих» рисует свои направляющие цветом метки. Draws guides as solid lines or as dots, including the guides already in the document. Рисует направляющие сплошными линиями или точками, включая направляющие, которые уже есть в документе. @@ -3246,6 +3327,7 @@ digits Malayalam Малаялам Rounded Rectangle Tool Инструмент «Скруглённый прямоугольник» Rounded Rectangle… Скруглённый прямоугольник… Row Size: Размер строки: + Rows Строки Rows: Строки: Rule: Линейка: Rulers Линейки @@ -3422,6 +3504,9 @@ digits Malayalam Малаялам Search commands, tools, panels and effects… Поиск команд, инструментов, панелей и эффектов… No commands match Нет подходящих команд {pos} of {total}: {name} {pos} из {total}: {name} + No menu item Нет пункта меню + Toolbar Панель инструментов + {toolbar}, in the {tool} group {toolbar}, в группе «{tool}» @plural {n} result|{n} results {n} результат|{n} результата|{n} результатов @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} из {n} результата. Продолжайте вводить, чтобы сузить их.|{shown} из {n} результатов. Продолжайте вводить, чтобы сузить их.|{shown} из {n} результатов. Продолжайте вводить, чтобы сузить их. Recent Commands Недавние команды @@ -3502,6 +3587,7 @@ digits Malayalam Малаялам Set Slice Rectangle Задать прямоугольник фрагмента Set Tab Stops Задать табуляции Set Text Задать текст + Set the current fill or stroke to the selected color Назначить выбранный цвет текущей заливке или обводке Set the selected color to the current color Назначить текущий цвет выбранному цвету Set Zoom Задать масштаб Settings… Параметры… @@ -3625,7 +3711,7 @@ digits Malayalam Малаялам Show Vivid/Muted Показать яркие/приглушённые Show Warm/Cool Показать тёплые/холодные Show {kind} Brushes Показать кисти {kind} - Show/hide plate (Alt-click: only this plate) Показать/скрыть пластину (Alt+щелчок: только эту пластину) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Показать/скрыть пластину (Alt+щелчок: только эту пластину; повторный Alt+щелчок: все пластины) Show: Показать: Shown with the optimised preview. Показано с оптимизированным просмотром. Side 1: Сторона 1: @@ -3767,7 +3853,7 @@ digits Malayalam Малаялам Spread: Разворот: Square Квадрат Squeeze… Сжатие… - Stacked Bar Graph Tool Инструмент «Гистограмма с накоплением» + Stacked Bar Graph Tool Инструмент «Линейчатая диаграмма с накоплением» Stacked Column Graph Tool Инструмент «Гистограмма с накоплением» Stair Step Ступенчатый Standard Ligatures Стандартные лигатуры @@ -3932,7 +4018,7 @@ digits Malayalam Малаялам Composite Fonts Составные шрифты Export Composite Fonts Экспорт составных шрифтов Import Composite Fonts Импорт составных шрифтов -@msg each font must be {name, parts} каждый шрифт должен иметь вид {name, parts} +@msg each font must be {{name, parts}} каждый шрифт должен иметь вид {{name, parts}} @msg unknown key `{k}`; a font takes name and parts неизвестный ключ `{k}`; шрифт принимает name и parts @msg each font needs a name у каждого шрифта должно быть имя @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` не может быть именем составного шрифта (от 1 до {COMPOSITE_NAME_MAX} символов, без управляющих символов) @@ -3945,7 +4031,7 @@ digits Malayalam Малаялам @msg two composite fonts are named `{_1}` два составных шрифта называются `{_1}` @msg `{_1}` is the name of an installed font `{_1}` является именем установленного шрифта @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2} использует `{font}`, а это составной шрифт -@msg give fonts: [{name, parts}…] укажите fonts: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] укажите fonts: [{{name, parts}}…] @msg path is empty path пуст @msg fonts must be a list of composite fonts fonts должен быть списком составных шрифтов @msg names must be strings names должны быть строками @@ -4028,6 +4114,13 @@ digits Malayalam Малаялам Thumbnail View Миниатюры Thumbnails: Миниатюры: Tile Плитка + Tile All Vertically Все плиткой по вертикали + Tile All Horizontally Все плиткой по горизонтали + 2-Up Layout Макет на 2 + 3-Up Layout Макет на 3 + 4-Up Layout Макет на 4 + 6-Up Layout Макет на 6 + Arrange Documents Упорядочить документы Tile Edge Color Цвет края плитки Tile Edge Color… Цвет края плитки… Tile Full Pages Плитка целых страниц @@ -4222,6 +4315,8 @@ digits Malayalam Малаялам V Spacing: Интервал по вертикали: V: В: Variable Width Profile Профиль переменной ширины + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Кисть обводки сохраняет собственный размер, поэтому профиль ширины её не меняет. Чтобы использовать профиль, уберите кисть. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Кисть обводки сохраняет собственный размер, поэтому профиль ширины её не меняет. Чтобы использовать профиль, уберите кисть. Variables Переменные New Variable Новая переменная Delete Variable Удалить переменную @@ -4286,7 +4381,7 @@ digits Malayalam Малаялам Vertical: По вертикали: Very High Очень высокая View Просмотр - View Artboard Only Просмотр только монтажной области + View Artboard Contents Only Просмотр только содержимого монтажной области View Opacity Mask Просмотр непрозрачной маски View PDF after saving Просматривать PDF после сохранения View {n} Вид {n} @@ -4339,7 +4434,7 @@ digits Malayalam Малаялам Zoom In Увеличить Zoom Out Уменьшить Zoom to Selection Масштаб по выделению - Zoom Tool Инструмент «Масштаб» + Zoom Tool Инструмент «Лупа» Zoom with Mouse Wheel Масштабировать колесом мыши Scroll Sideways with Cmd/Ctrl + Wheel Прокручивать по горизонтали колесом с Cmd/Ctrl Scrub Numeric Fields by Dragging Изменять числовые поля перетаскиванием @@ -4505,6 +4600,7 @@ imageTrace Outline Контур Bevel Скос Offset Смещение Axis Ось + Axis Angle Угол оси axis Horizontal Горизонтально axis Vertical Вертикально axis Both Оба @@ -4581,6 +4677,13 @@ axis Both Оба Show External Script Warning Показывать предупреждение о внешних скриптах A Script Is Running Выполняется скрипт Script Alert Сообщение скрипта + Script File Access Доступ скрипта к файлам + The script asks to read a file you choose. Скрипт запрашивает чтение выбранного вами файла. + The script asks to read and write a file you choose. Скрипт запрашивает чтение и запись выбранного вами файла. + The script asks to read and write a folder you choose, with everything in it. Скрипт запрашивает чтение и запись выбранной вами папки со всем её содержимым. + Allow Once Разрешить один раз + Always Allow This Script Всегда разрешать этот скрипт + Deny Запретить A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Скрипт может изменять открытые документы и записывать файлы с помощью выполняемых команд. Запускайте только те скрипты, которым доверяете. Do not show this warning again Больше не показывать это предупреждение Stop the script and undo what it did? Then quit again. Остановить скрипт и отменить его изменения? Затем выйдите ещё раз. @@ -4597,6 +4700,8 @@ axis Both Оба @msg the script is no longer in the Scripts folder скрипт больше не находится в папке Scripts Some scripts were not listed Некоторые сценарии не показаны The Scripts folder cannot be read Не удалось прочитать папку Scripts + Loading scripts… Загрузка сценариев… + The Scripts folder is still being read Папка Scripts ещё читается @msg the script's run is no longer available выполнение скрипта больше недоступно @msg a failed command changed undo steps that could not be put back, so the script was stopped неудавшаяся команда изменила шаги отмены, которые не удалось восстановить, поэтому скрипт остановлен @msg a recovery copy could not be written, so the script was not run не удалось записать копию для восстановления, поэтому скрипт не выполнен @@ -4609,8 +4714,6 @@ axis Both Оба @msg Script file could not be read Не удалось прочитать файл скрипта @msg Script folder has more than 2,048 entries В папке скрипта больше 2048 элементов @msg Script file open mode must be r, w, e or a Режим открытия файла скрипта должен быть r, w, e или a -@msg Script file writing is not available Запись файлов скрипта недоступна -@msg Script file dialogs are not available Диалоговые окна файлов скрипта недоступны @msg Script files cannot be opened in another application Файлы скрипта нельзя открыть в другом приложении @msg Script file access is unavailable on the web Доступ к файлам скрипта в веб-версии недоступен @msg Script has 256 files open У скрипта открыто 256 файлов @@ -4736,8 +4839,37 @@ liquify-list-end {0}, {1} {0} и {1} @msg is a prompt's answer, whose `value` must be a string or null является ответом на prompt, поэтому его `value` должно быть строкой или null @msg must have `kind` alert, confirm or prompt должен иметь `kind` alert, confirm или prompt @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` предназначен только для запуска, в котором некого спросить: в приложении человек сам отвечает на каждое диалоговое окно +@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` должен быть целым числом от 1 до {_1} +@msg `args{place}` is nested more than 64 levels deep `args{place}` вложен глубже 64 уровней +@msg `args` must be an object `args` должен быть объектом +@msg `args` is larger than 1 MiB `args` больше 1 МиБ +@msg `path` is empty параметр `path` пуст +@msg `installed` takes a `path`, not a `source` `installed` принимает `path`, а не `source` +@msg `path` must name a .js or .jsx file `path` должен указывать на файл .js или .jsx +@msg give exactly one of `path` and `source` укажите ровно одно из: `path` и `source` @msg Running a script Выполняется скрипт @msg Copied the script report Отчёт о сценарии скопирован +@msg Script file access denied: {path} Доступ скрипта к файлам запрещён: {path} +@msg Script file access to the app's own folders is not allowed Скрипту не разрешён доступ к собственным папкам приложения +@msg Script file cannot encode the text Файл скрипта не может закодировать текст +@msg Script file could not be written Не удалось записать файл скрипта +@msg Script file dialogs need a person to answer them Для ответа на файловые диалоги скрипта нужен человек +@msg Script file is not open for writing Файл скрипта не открыт для записи +@msg Script file name is already in use Имя файла скрипта уже используется +@msg Script file name must be a name without a folder Имя файла скрипта должно быть именем без папки +@msg Script file permission can be kept only for a script run from a file Разрешение на файлы можно сохранить только для скрипта, запущенного из файла +@msg Script file permission could not be saved Не удалось сохранить разрешение скрипта на файлы +@msg Script folder is not empty Папка скрипта не пуста +@msg Script files cannot make aliases Файлы скрипта не могут создавать псевдонимы +@msg Script file hidden setting cannot be changed Нельзя изменить параметр скрытости файла скрипта +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: файловый диалог нельзя открыть внутри обратного вызова встроенной функции, геттера, преобразования или файла, который выполняет $.evalFile; вызовите его из собственного кода скрипта +@msg the script wrote more file data than one run may write (32 MiB) скрипт записал больше данных файлов, чем может записать один запуск (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` для файлового диалога скрипта должен быть одним из: once, always, deny, stop +@msg choose a file or folder first, or deny сначала выберите файл или папку либо откажите +@msg the script file permissions could not be saved: {e} не удалось сохранить разрешения скриптов на файлы: {e} +@msg this script's file access can be allowed only once доступ этого скрипта к файлам можно разрешить только один раз +@msg Only the person at the keyboard can allow a script's file access Разрешить скрипту доступ к файлам может только человек за клавиатурой +@msg A script is given at most 2,048 files: the files picked after them were left out Скрипт получает не больше 2 048 файлов: файлы, выбранные после них, пропущены @msg Copied the link info Сведения о связи скопированы @msg Corners edits the corners of a path «Углы» редактирует углы контура @msg Couldn't copy to the system clipboard: {e} Не удалось скопировать в системный буфер обмена: {e} @@ -4813,6 +4945,7 @@ liquify-list-end {0}, {1} {0} и {1} @msg Saved {path} Сохранено: {path} @msg Select text or click into text with the Type tool to insert glyphs Выделите текст или щёлкните внутри текста инструментом «Текст», чтобы вставить глифы @msg Shape Builder: no region under the pointer Создание фигур: под указателем нет области +@msg Shape Builder: select all paths you want to merge Создание фигур: выделите все контуры, которые нужно объединить @msg Shape Builder: select paths or compound paths Создание фигур: выделите контуры или составные контуры @msg Show All Hidden Attributes: nothing is hidden Показать все скрытые атрибуты: ничего не скрыто @msg Split Into Grid: select paths large enough for the grid Разделение на сетку: выделите контуры, достаточно большие для сетки @@ -4868,6 +5001,8 @@ liquify-list-end {0}, {1} {0} и {1} @msg `{min_key}` is greater than `{max_key}` `{min_key}` больше, чем `{max_key}` @msg give at least one of `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` укажите хотя бы один из параметров `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` должно быть grayscale, rgb, hsb, cmyk или websafe +@msg `view` must be wheel or box `view` должно быть wheel или box +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` должно быть hue, saturation, brightness, red, green или blue @msg `{k}` must be [x, y] `{k}` должно быть [x, y] @msg `{name}` has no options `{name}` не имеет параметров @msg `{name}` is a built-in workspace; choose another name `{name}` — встроенная рабочая среда; выберите другое имя @@ -4956,6 +5091,7 @@ liquify-list-end {0}, {1} {0} и {1} @msg bad trailer недопустимый трейлер @msg balance must be between 0 and 100 balance должен быть от 0 до 100 @msg batch step {_1} (`{id}`) failed: {e} шаг пакета {_1} (`{id}`) не выполнен: {e} +@msg action step {_1} (`{id}`) failed: {reason} шаг действия {_1} (`{id}`) не выполнен: {reason} @msg brightness must be dark|mediumDark|mediumLight|light brightness должен быть dark|mediumDark|mediumLight|light @msg can't encode the document: {0} не удалось закодировать документ: {0} @msg can't parse shortcut `{c}` не удалось разобрать сочетание `{c}` @@ -4975,6 +5111,7 @@ liquify-list-end {0}, {1} {0} и {1} @msg choose a folder to export to выберите папку для экспорта @msg choose a location for the package выберите расположение для пакета @msg clipboard is empty буфер обмена пуст +@msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: в цветовой таблице должен остаться хотя бы один цвет @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` не является цветом, например "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: не более {MAX_TABLE} цветов @msg command `{0}` is not available right now: {1} команда `{0}` сейчас недоступна: {1} @@ -5042,9 +5179,15 @@ liquify-list-end {0}, {1} {0} и {1} @msg no PNG encoder нет кодера PNG @msg no active document нет активного документа @msg no active perspective plane нет активной плоскости перспективы +@msg the perspective grid is hidden сетка перспективы скрыта +@msg Automatic Plane Positioning is off: turn on anchorPoint or gridlineIntersection (perspective.widget.options) Автоматическое размещение плоскости выключено: включите anchorPoint или gridlineIntersection (perspective.widget.options) +@msg anchorPoint must be true or false anchorPoint должно быть true или false +@msg gridlineIntersection must be true or false gridlineIntersection должно быть true или false +@msg tolerance must be 0 or more tolerance должно быть 0 или больше +@msg give `at` or `clear`, not both укажите `at` или `clear`, но не оба @msg no anchor points selected опорные точки не выделены -@msg `points` must be three [x, y] pairs of numbers `points` должен содержать три пары чисел [x, y] -@msg direct-select three anchor points, or give `points` выделите прямым выделением три опорные точки или задайте `points` +@msg `points` must be two or three [x, y] pairs of numbers `points` должен содержать две или три пары чисел [x, y] +@msg direct-select two or three anchor points, or give `points` выделите прямым выделением две или три опорные точки или задайте `points` @msg no circle passes through these points: two are the same or all three lie on one line через эти точки не проходит ни одна окружность: две точки совпадают или все три лежат на одной прямой @msg no app to open files here здесь нет приложения для открытия файлов @msg no artboard нет монтажной области @@ -5146,6 +5289,9 @@ liquify-list-end {0}, {1} {0} и {1} @msg no such user library такой пользовательской библиотеки нет @msg no such view такого вида нет @msg no such width point такой точки ширины нет +@msg `single` must be `incoming` or `outgoing` `single` должен быть `incoming` или `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` и `outIndex` должны быть двумя половинами одной разрывной точки ширины +@msg a discontinuous width point keeps its place разрывная точка ширины сохраняет своё место @msg no swatch `{name}` нет образца `{name}` @msg no swatch library `{l}` (see swatch.library.list) нет библиотеки образцов `{l}` (см. swatch.library.list) @msg no symbol instances selected экземпляры символов не выделены @@ -5407,6 +5553,13 @@ liquify-list-end {0}, {1} {0} и {1} @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} больше {MAX_CSV_ROWS} наборов данных: «Импортировать наборы данных» читает не более {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} больше {MAX_CSV_COLS} переменных: «Импортировать наборы данных» читает не более {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} переменные, которые не являются текстовыми, пропущены: {kinds} +variable-kind Visibility Видимость +variable-kind Linked File Связанный файл +variable-kind Graph Data Данные диаграммы +variable-kind Unknown Неизвестно +variable-list-two {0}, {1} {0} и {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} и {1} @msg a new document won't read these variables back with their kind: {names} новый документ не прочитает эти переменные обратно с их типом: {names} @msg a new document refuses this file because of these variables: {names} новый документ отклоняет этот файл из-за этих переменных: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them заголовок `{header}` для `{name}` будет прочитан как переменная `{other}`: переименуйте одну из них @@ -5432,6 +5585,8 @@ liquify-list-end {0}, {1} {0} и {1} @msg {label}: lost track of a shape's style {label}: потерян стиль фигуры @msg {label}: select paths {label}: выделите контуры @msg {label}: select paths, compound paths, groups or text {label}: выделите контуры, составные контуры, группы или текст +@msg a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first линия или другой открытый контур, не охватывающий площади, не меняет форму результата; чтобы включить его, сначала примените к нему Объект › Контур › Обвести обводку +@msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first {label} дал пустой результат: линия или другой открытый контур не охватывает площади; чтобы включить его, сначала примените к нему Объект › Контур › Обвести обводку @msg {label}… {label}… @msg {name}: CRC mismatch {name}: несовпадение CRC @msg {name}: no local header {name}: нет локального заголовка @@ -5458,6 +5613,9 @@ liquify-list-end {0}, {1} {0} и {1} @msgplural Discarded {n} recovered document|Discarded {n} recovered documents Отменён {n} восстановленный документ|Отменено {n} восстановленных документа|Отменено {n} восстановленных документов @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them Восстановлен {n} документ: сохраните его, чтобы оставить|Восстановлено {n} документа: сохраните их, чтобы оставить|Восстановлено {n} документов: сохраните их, чтобы оставить @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} Открыто с {n} примечанием: {first}|Открыто с {n} примечаниями: {first}|Открыто с {n} примечаниями: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Скопировано с {n} примечанием: {first}|Скопировано с {n} примечаниями: {first}|Скопировано с {n} примечаниями: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Вырезано с {n} примечанием: {first}|Вырезано с {n} примечаниями: {first}|Вырезано с {n} примечаниями: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Изображение трассировано с {n} примечанием: {first}|Изображение трассировано с {n} примечаниями: {first}|Изображение трассировано с {n} примечаниями: {first} @msgplural {notice}. Opened with {n} note: {first}|{notice}. Opened with {n} notes: {first} {notice}. Открыто с {n} примечанием: {first}|{notice}. Открыто с {n} примечаниями: {first}|{notice}. Открыто с {n} примечаниями: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} Сохранено: {path} с {n} примечанием: {first}|Сохранено: {path} с {n} примечаниями: {first}|Сохранено: {path} с {n} примечаниями: {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first Внедрено {n} изображение; отсутствует {missing}: сначала восстановите связи|Внедрено {n} изображения; отсутствует {missing}: сначала восстановите связи|Внедрено {n} изображений; отсутствует {missing}: сначала восстановите связи @@ -5484,6 +5642,8 @@ liquify-list-end {0}, {1} {0} и {1} @msg All colors are within the CMYK gamut Все цвета входят в цветовой охват CMYK @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} цвет выходит за пределы цветового охвата CMYK|{n} цвета выходят за пределы цветового охвата CMYK|{n} цветов выходят за пределы цветового охвата CMYK @msg Unembedded to {_1} Извлечено в {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} Извлечено {n} изображение в {folder}|Извлечено {n} изображения в {folder}|Извлечено {n} изображений в {folder} +@msg every numbered name for {name} is taken in that folder все нумерованные имена для {name} уже заняты в этой папке @msg Reset {_1} Сброшено: {_1} @msg Sent to {_1} Отправлено в {_1} @msg {_1} files {_1} файлов @@ -5499,6 +5659,8 @@ liquify-list-end {0}, {1} {0} и {1} @msg Reload the page to go on (changes not saved yet may be lost). Перезагрузите страницу, чтобы продолжить (ещё не сохранённые изменения могут быть потеряны). @msg tool (a tool id) is required требуется tool (идентификатор инструмента) @msg {tool} isn't in a toolbar group of several tools {tool} не входит в группу панели инструментов из нескольких инструментов +@msg Presentation Mode hides the toolbars: change the screen mode to show them Режим презентации скрывает панели инструментов: чтобы показать их, смените режим экрана +@msg Tab has hidden the toolbars: press Tab to show them клавиша Tab скрыла панели инструментов: чтобы показать их, нажмите Tab @msg onto must name a panel floating in another group onto должен называть панель, плавающую в другой группе @msg below and above must name a panel floating in another group below и above должны называть панель, плавающую в другой группе @msg give only one of onto, below and above укажите только один из onto, below и above @@ -5615,6 +5777,9 @@ liquify-list-end {0}, {1} {0} и {1} @msg automation path rejected: outside the read root {root}: {path} путь автоматизации отклонён: вне корневой папки для чтения {root}: {path} @msg automation path rejected: outside the read roots {roots}: {path} путь автоматизации отклонён: вне корневых папок для чтения {roots}: {path} @msg a linked JavaScript file is outside the read roots связанный файл JavaScript находится вне корневых папок для чтения +@msg a linked image file is outside the read roots связанный файл изображения находится вне корневых папок для чтения +@msg a linked file's export folder is outside the read roots папка экспорта связанного файла находится вне корневых папок для чтения +@msg a linked file's editing data can't be read to check it against the read roots не удаётся прочитать данные редактирования связанного файла, чтобы сверить их с корневыми папками для чтения @msg automation path rejected: outside the write root {root}: {path} путь автоматизации отклонён: вне корневой папки для записи {root}: {path} @msg automation path rejected: outside the write roots {roots}: {path} путь автоматизации отклонён: вне корневых папок для записи {roots}: {path} @msg automation path rejected: path is empty путь автоматизации отклонён: путь пуст @@ -5842,6 +6007,7 @@ lighting Light Свет @msg missing panel layout Отсутствует расположение панелей @msg unsupported native docking operation Неподдерживаемая собственная операция прикрепления Linux Display Server Дисплейный сервер Linux + Low-Latency Drawing Рисование с низкой задержкой X11 (XWayland) When a Pen Is Attached X11 (XWayland) при подключенном пере If a drawing tablet's pen doesn't draw, choose an X11 (XWayland) option. Если перо графического планшета не рисует, выберите вариант X11 (XWayland). X11 (XWayland) X11 (XWayland) @@ -5896,6 +6062,7 @@ lighting Light Свет Cove Выкружка Depth Глубина Front Спереди + Side Сбоку Isometric Bottom Изометрия снизу Isometric Left Изометрия слева Isometric Right Изометрия справа @@ -5990,7 +6157,7 @@ lighting Light Свет @msg each of `{GRAPHICS}` must be an object каждый элемент `{GRAPHICS}` должен быть объектом @msg `{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}` элементы `{GRAPHICS}` принимают symbol, face, x, y, scale и rotation, а не `{k}` @msg each of `{GRAPHICS}` needs `symbol`, the name of a symbol каждому элементу `{GRAPHICS}` нужен `symbol`, имя символа -@msg `{GRAPHICS}` face must be front or back face в `{GRAPHICS}` должен быть front или back +@msg `{GRAPHICS}` face must be front, back or side face в `{GRAPHICS}` должен быть front, back или side @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} в `{GRAPHICS}` должен быть числом от {lo} до {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` должен быть массивом @msg Graphics map onto the Plane, Extrude and Revolve object types Графика наносится на объекты типов «Плоскость», «Выдавливание» и «Вращение» @@ -7142,6 +7309,7 @@ axis Y Axis Ось Y [Press Quality] [Типографское качество] of из x Height Высота строчных + Em Box Height Высота кегельной площадки ▾ Default Actions ▾ Стандартные действия ⚠ {chord} was already used by {names} — it has been removed there. ⚠ {chord} уже было назначено: {names}; там оно удалено. @plural {n} shortcut is assigned more than once|{n} shortcuts are assigned more than once {n} сочетание клавиш назначено несколько раз|{n} сочетания клавиш назначены несколько раз|{n} сочетаний клавиш назначены несколько раз @@ -7370,6 +7538,12 @@ anchor Points: Точки: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` должно быть "free", "keepAngles" или "symmetric" @msg `{key}` must be [x, y] `{key}` должно быть [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Конвертер единиц + Unit Converter Panel Панель «Конвертер единиц» + Copy with Units Копировать с единицами + From Selection Из выделения + # Color Effects add-on: Select by Color Kind. Select by Color Kind Выделить по типу цвета Objects with Spot Colors Объекты с плашечными цветами @@ -7594,6 +7768,14 @@ breakText Glyphs Глифы Remove Gaps Убрать зазоры @msg that makes too many pieces (at most 100000): make the dashes longer так получится слишком много частей (не более 100000): удлините штрихи @msg select paths, or segments, to divide выделите контуры или сегменты для разделения +# Path Precision Tools add-on: Smooth Bridge. + Smooth Bridge… Плавный мост… + Smooth Bridge Плавный мост + Keep Originals Сохранить оригиналы +@msg select two circles to bridge выделите две окружности для соединения +@msg one circle is inside the other одна окружность находится внутри другой +@msg the circles are too far apart for this radius: raise the radius окружности слишком далеко друг от друга для этого радиуса: увеличьте радиус +@msg the circles are too far apart for this radius окружности слишком далеко друг от друга для этого радиуса # Path Precision Tools add-on: Common Tangents. Common Tangents… Общие касательные… Common Tangents Общие касательные @@ -8291,7 +8473,7 @@ shape Open Открытый @msg `scale` must be a number from 0.001 to 1000 `scale` должно быть числом от 0.001 до 1000 @msg `scale` must be a number in (0, 100] `scale` должно быть числом в диапазоне (0, 100] @msg `scope.{key}` must be a non-empty array `scope.{key}` должно быть непустым массивом -@msg `scope` must be "document", {artboards} or {layers} `scope` должно быть "document", {artboards} или {layers} +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` должно быть "document", {{artboards: [index, …]}} или {{layers: [id, …]}} @msg `scope` must be "selection" or "document", not {other} `scope` должно быть "selection" или "document", а не {other} @msg `script` must be a string `script` должно быть строкой @msg `seriesIndexes` is a non-empty list of series indexes `seriesIndexes` — непустой список индексов рядов @@ -8370,6 +8552,8 @@ shape Open Открытый @msg `{f}` is the copy of a document open now `{f}` — копия документа, открытого сейчас @msg `{id}` is no writable format (see document.formats) `{id}` не является форматом для записи (см. document.formats) @msg `{id}` isn't a loaded library `{id}` не является загруженной библиотекой +@msg `{file}` has no swatches of its own в `{file}` нет собственных образцов +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold в `{_1}` есть образцы узоров, которые файл .vcswatches не может хранить @msg `{key}` has no colours в `{key}` нет цветов @msg `{key}` holds more than {MAX_EDIT_WORDS} words `{key}` содержит больше {MAX_EDIT_WORDS} слов @msg `{key}` is a design name `{key}` — имя дизайна @@ -8676,6 +8860,7 @@ shape Open Открытый @msg compound {_1} must contain exactly one open path to join составной объект {_1} должен содержать ровно один открытый контур для соединения @msg connect end must be "start" or "end" end для connect должно быть "start" или "end" @msg connect needs a path other than the one extended для connect нужен контур, отличный от продлеваемого +@msg connect needs extend для connect нужен extend @msg connect needs id для connect нужен id @msg connect path has no open end у контура для connect нет открытого конца @msg continuation must be an array of path chunks continuation должно быть массивом фрагментов контура @@ -9182,7 +9367,7 @@ shape Open Открытый @msg nothing to print: every artboard picked is blank нечего печатать: все выбранные монтажные области пусты @msg nothing to print: the document has no art that prints нечего печатать: в документе нет печатаемой графики @msg nothing to repeat нечего повторять -@msg numbers out of order in {_1} quantifier числа в квантификаторе {_1} идут в неверном порядке +@msg numbers out of order in {{}} quantifier числа в квантификаторе {{}} идут в неверном порядке @msg object is not a path объект не является контуром @msg object transparency cannot be sampled onto highlighted characters; disable Transparency in Eyedropper Options or select the whole object прозрачность объекта нельзя перенести на выделенные символы; отключите «Прозрачность» в окне «Параметры пипетки» или выделите объект целиком @msg object {_1} can't be set as point type объект {_1} нельзя преобразовать в текст из точки @@ -9541,7 +9726,7 @@ shape Open Открытый @msg the page has no area у страницы нет площади @msg the page's type in an unread object's box isn't in its page art текста страницы в рамке непрочитанного объекта нет в графике этой страницы @msg the paint behind the proxy is not a gradient краска за индикатором не является градиентом -@msg the paint is not a freeform gradient (apply one with paint.editGradient {kind}) краска не является произвольным градиентом (примените его через paint.editGradient {kind}) +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) краска не является произвольным градиентом (примените его через paint.editGradient {{kind: "freeform"}}) @msg the parameters or body do not form one function параметры или тело не образуют одну функцию @msg the parent must be a layer or sublayer родитель должен быть слоем или подслоем @msg the pasted SVG filter {name} draws differently from the document's filter of that name, and no free name fits it вставленный фильтр SVG {name} рисует иначе, чем фильтр документа с тем же именем, и свободного имени для него не нашлось @@ -10009,5 +10194,15 @@ shape Open Открытый @msg A panel is not joined to the rest by a crease. Панель не соединена с остальными ни одной линией биговки. @msg A fold line is on a non-printing layer. Линия сгиба находится на непечатаемом слое. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Панели: {panels}, шарниры: {hinges}, ошибки: {errors}, предупреждения: {warnings} + Fold Preview Предпросмотр сгиба + Fold Сгиб + Show Fold Lines Показать линии сгиба + Three-Quarter Три четверти + Open a document to preview its folded shape. Откройте документ, чтобы просмотреть его в сложенном виде. +@msg Check the fold lines first. Сначала проверьте линии сгиба. +@msg Panels: {panels}, hinges: {hinges} Панели: {panels}, шарниры: {hinges} +@msg Other blanks not shown: {count} Другие развёртки не показаны: {count} +@msg A joint does not close by {gap} pt. Стык не смыкается на {gap} pt. +@msg Two panels pass through each other. Две панели проходят друг сквозь друга. @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} пикселей — слишком большой размер для PSD (не более {MAX_SIDE} пикселей по стороне): уменьшите разрешение @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer должен быть "singleLine", "everyLine", "standardSingleLine" или "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 5c0420fcd3..ed601312a4 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -107,6 +107,7 @@ Add Anchor Point Lägg till ankarpunkt Add Anchor Point Tool Verktyget Lägg till ankarpunkt Add Anchor Points Lägg till ankarpunkter + Add Around Lägg till runt objektet Add Effect Lägg till effekt Add Freeform Line Lägg till fri linje Add Freeform Point Lägg till fri punkt @@ -128,8 +129,12 @@ Add to Swatches Lägg till i färgrutor Add Used Colors Lägg till använda färger Additional Plug-ins Folder Mapp för ytterligare plugins + Plug-in Instruction Budget Instruktionsbudget för plugins Additional Fonts Folder Mapp för ytterligare typsnitt Adjust Adjoining Width Points Justera angränsande breddpunkter + Incoming Inkommande + Outgoing Utgående + Single Width Only Endast en bredd Adjust Color Balance… Justera färgbalans… Adjust Colors Justera färger Adjust Options: Justeringsalternativ: @@ -184,6 +189,7 @@ Angle: Vinkel: Angles Vinklar Animated Zoom Animerad zoom + Anti Alias Kantutjämning Anti-alias Kantutjämning Anti-Alias Kantutjämning Anti-alias Rasters Kantutjämna rasterbilder @@ -214,6 +220,7 @@ font-technology Variable Variabla Apply Last Gradient Använd senaste gradienten Apply Paragraph Style Använd styckestil Apply SVG Filter… Använd SVG-filter… + Apply SVG Filter Använd SVG-filter Apply to All Använd på alla @plural Apply to All ({n} more missing)|Apply to All ({n} more missing) Använd på alla ({n} till saknas)|Använd på alla ({n} till saknas) Arc Båge @@ -292,7 +299,7 @@ font-technology Variable Variabla Background Contents Bakgrundsinnehåll Background: Bakgrund: Backspace Backspace - Bar Graph Tool Stapeldiagramverktyg + Bar Graph Tool Verktyg för liggande stapeldiagram Baseline Baseline Baseline Shift Baslinjeförskjutning Basic Latin Grundläggande latin @@ -350,6 +357,12 @@ font-technology Variable Variabla Brush Definition Penseldefinition Brush Libraries Penselbibliotek Brush Options… Penselalternativ… + Options of Selected Object… Alternativ för markerat objekt… + Options of Selected Object Alternativ för markerat objekt +@msg no path painted with a brush is selected ingen bana målad med en pensel är markerad +@msg the selected paths are painted with brushes of different types de markerade banorna är målade med penslar av olika typer +@msg give `params` or `reset`, not both ange `params` eller `reset`, inte båda +@msg a bristle brush has no options of its own on a path en borstpensel har inga egna alternativ på en bana Brush Strokes Penseldrag Brushes Penslar Built-in Libraries Inbyggda bibliotek @@ -406,6 +419,11 @@ font-technology Variable Variabla Character Alignment Teckenjustering Character / Paragraph Tecken / stycke Character Rotation Teckenrotation + Chinese Big 5 Kinesisk Big 5 + Cyrillic Kyrillisk + Greek Grekisk + Baltic Baltisk + Central European Centraleuropeisk Character Set: Teckenuppsättning: Character Style Teckenstil Character Style Options Alternativ för teckenstil @@ -464,9 +482,12 @@ font-technology Variable Variabla Not a script for the reference app Inte ett skript för referensappen Some lists were cut short at their limit. Vissa listor kortades av vid gränsvärdet. Check Spelling… Kontrollera stavning… + Check Spelling Kontrollera stavning Choose a folder Välj en mapp Choose… Välj… Circle Cirkel + Circle Tool Cirkelverktyg + Circle too large Cirkeln är för stor Classic Defaults Klassiska standardvärden Clean Up… Rensa upp… Clear Rensa @@ -541,6 +562,7 @@ font-technology Variable Variabla Color Mixer (Shift-click the chip) Färgmixer (Shift-klicka på färgrutan) Color Mode Färgläge Color Mode: Färgläge: + Color Model Färgmodell Color Model: Färgmodell: Color Models Färgmodeller Color Picker Färgväljare @@ -561,12 +583,18 @@ font-technology Variable Variabla Saturation and brightness Mättnad och ljusstyrka Color field Färgfält {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Hjulvy + Box View Rutvy + Box Channel Rutans kanal + Color box Färgruta + Color Wheel Options Alternativ för färghjulet Color Type: Färgtyp: Color: Färg: Colorize Färglägg Colors Färger Colors: Färger: Column Graph Tool Stapeldiagramverktyg + Columns Kolumner Columns: Kolumner: Column… Kolumn… Combine Slices Kombinera skivor @@ -777,6 +805,8 @@ font-technology Variable Variabla Delete Artboard Radera rityta Delete Artboards Radera ritytor Delete Brush Radera pensel + Delete Color Radera färg + Restore Generated Table Återställ genererad tabell Delete Character Style Radera teckenstil Delete Empty Artboards Radera tomma ritytor Delete Freeform Point Radera fri punkt @@ -845,6 +875,7 @@ font-technology Variable Variabla Direct Selection Tool Direktmarkeringsverktyg Direction Handles Riktningshandtag Disable Auto Add/Delete Inaktivera Lägg till/radera automatiskt + Interpolate Control Points When Moving Anchors Interpolera riktningshandtag vid flyttning av ankarpunkter Disable Opacity Mask Inaktivera opacitetsmask Discard Släng Discard Empty Type Släng tom text @@ -1049,6 +1080,7 @@ font-technology Variable Variabla Enable text access for screen readers Ge skärmläsare åtkomst till text Enable Touch Gestures Aktivera pekgester Switch Selection and Drawing Modes Växla mellan markerings- och ritläge + Select Last Selection Tool Välj det senaste markeringsverktyget Enable Touch Workspace Aktivera arbetslayout för pekskärm Encoding Kodning Encoding: Kodning: @@ -1226,6 +1258,8 @@ font-technology Variable Variabla Files Filer Files of a PDF standard can't be password-protected. Filer enligt en PDF-standard kan inte lösenordsskyddas. Files of this standard tag their colours with ICC profiles. Filer enligt den här standarden märker sina färger med ICC-profiler. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Filer enligt den här standarden märker sina färger med ICC-profiler, utom CMYK-färger i profilen för utgångsavsikt, som skrivs som DeviceCMYK. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. Med ”Inkludera inte profiler” och en CMYK-utgångsavsikt skrivs varje CMYK-färg som DeviceCMYK, om den inte konverteras till ett CMYK-mål med en annan profil. Fill Fyllning Fill & Stroke Fyllning och kontur Fill (X), double-click for the Color Picker Fyllning (X), dubbelklicka för färgväljaren @@ -1965,6 +1999,7 @@ font-technology Variable Variabla Load SVG into Clipboard Läs in SVG till urklipp Load Text into Clipboard Läs in text till urklipp Local Libraries Lokala bibliotek + Locate Layer Hitta lager Locate Object Hitta objekt Locate Selected Objects Hitta markerade objekt Location Plats @@ -2159,6 +2194,7 @@ font-technology Variable Variabla Scatter: Spridning: Rotation: Rotation: Rotation relative to: Rotation i förhållande till: + Hue Jitter: Nyansvariation: Brush Scale Options Alternativ för penselskala Scale Proportionately Skala proportionellt Stretch to Fit Stroke Length Sträck för att passa konturlängden @@ -2195,6 +2231,7 @@ font-technology Variable Variabla Black becomes the stroke color and white stays white. Other colors become tints of the stroke color by their lightness. Svart blir konturfärgen och vitt förblir vitt. Andra färger blir ljusare toner av konturfärgen, och ju ljusare en färg är, desto ljusare är dess ton. Black and white stay as they are. Dark colors become shades of the stroke color and light colors become tints of it. Svart förblir svart och vitt förblir vitt. Andra färger blir mörkare toner av konturfärgen när de är mörka och ljusare toner av den när de är ljusa. The key color becomes the stroke color. The other colors shift their hue by the same amount and keep their saturation and brightness. Nyckelfärgen blir konturfärgen. De andra färgerna flyttas lika långt runt färghjulet som nyckelfärgen och behåller sin mättnad och ljusstyrka. + Roundness Rundhet Roundness: Rundhet: Fixed Fast Pressure Tryck @@ -2500,6 +2537,9 @@ font-technology Variable Variabla Overprint Övertryck Overprint and Transparency Flattener Övertryck och transparensutplattning Overprint and Transparency Flattener Options Alternativ för övertryck och transparensutplattning + Custom… Anpassad… + Custom Transparency Flattener Options Anpassade alternativ för transparensutplattning + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS har ingen alfatransparens, och Övertryck avgör om övertryck behålls. Overprint Black… Övertryck svart… Overprint Fill Övertryck fyllning Overprint Preview Förhandsgranskning av övertryck @@ -2604,6 +2644,7 @@ font-technology Variable Variabla Play Current Selection Spela upp aktuell markering Save Actions… Spara åtgärder… Load Actions… Läs in åtgärder… + Replace Actions… Ersätt åtgärder… Reset Actions Återställ åtgärder Replace the current actions with the default set? Vill du ersätta de aktuella åtgärderna med standarduppsättningen? Append adds the default set after the current sets instead. Lägg till lägger i stället till standarduppsättningen efter de aktuella uppsättningarna. @@ -2619,6 +2660,10 @@ font-technology Variable Variabla Polar Grid Tool Verktyg för polärt rutnät Polygon Polygon Polygon Properties: Polygonegenskaper: + Line Properties: Linjeegenskaper: + Line Length: Linjelängd: + Line Angle: Linjevinkel: + Constrain Pie Angle Behåll cirkeldiagrammets vinkel Polygon Tool Polygonverktyg Portrait Stående Power Saving (integrated) Energisparläge (integrerad) @@ -2778,6 +2823,9 @@ digits Malayalam Malayalam Real World: Verkligt mått: Real-time Drawing and Editing Ritning och redigering i realtid Use Monitor Profile for Canvas Använd skärmprofil för arbetsytan + Refresh Monitor Profile Uppdatera skärmprofil +@msg turn on Use Monitor Profile for Canvas first slå först på ”Använd skärmprofil för arbetsytan” +@msg this build doesn't read display profiles den här versionen läser inte skärmprofiler The canvas is drawn in sRGB. Arbetsytan ritas i sRGB. Canvas display profile: Arbetsytans skärmprofil: The system matches the window to the display's colors. Systemet anpassar fönstret till skärmens färger. @@ -2969,6 +3017,8 @@ digits Malayalam Malayalam Reselect Markera igen Reset Återställ Reset Bounding Box Återställ begränsningsram + Rotate Bounding Box Rotera begränsningsram + Rotate Bounding Box… Rotera begränsningsram… Reset Envelope Mesh Återställ kuvertnät Reset Envelope Shape Återställ kuvertform Reset Essentials Återställ Grundläggande @@ -3009,6 +3059,7 @@ digits Malayalam Malayalam Reshape Segment Omforma segment Reshape Tool Omformningsverktyg Reshape Type Area Omforma textområde + Resolution Upplösning Resolution: Upplösning: Responsive Responsiv Restore Återställ @@ -3035,6 +3086,7 @@ digits Malayalam Malayalam The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Mushjulet med Cmd/Ctrl nedtryckt rullar arbetsytan i sidled. Dragging sideways on a numeric field's label changes the field's value. Att dra i sidled på ett sifferfälts etikett ändrar fältets värde. A two-finger rotate gesture on a trackpad rotates the canvas view. En rotationsgest med två fingrar på en styrplatta roterar arbetsytans vy. + When you move anchor points, each curve with one moved end keeps its shape relative to its ends. När du flyttar ankarpunkter behåller varje kurva med en flyttad ände sin form i förhållande till sina ändar. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. När du håller ned ett verktygs kortkommando är verktyget valt tills du släpper, och sedan väljs det föregående verktyget igen. Shows the bounding box while you move the selection or draw a shape. Visar avgränsningsramen medan du flyttar markeringen eller ritar en form. Create Trim Marks draws Japanese-style marks instead of Roman ones. Skapa skärmärken ritar märken i japansk stil i stället för romerska. @@ -3065,6 +3117,29 @@ digits Malayalam Malayalam The unit for East Asian type measurements, which no field uses yet. Enheten för mått i östasiatisk text, som inget fält använder ännu. When on, a number typed without a unit into a field in picas is read in points. När det är på läses ett tal som skrivs utan enhet i ett fält i pica i punkter. With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options. Med XML-id visas objektnamn som XML-id:n i Lager, Variabler och Lageralternativ. + The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl. Steget för textstorlek och radavstånd: Cmd/Ctrl+Skift+. och Cmd/Ctrl+Skift+, ändrar storleken ett steg, eller fem med Alt också; i vågrät text ändrar Alt med uppåt- eller nedåtpil radavståndet ett steg, eller fem med Cmd/Ctrl. + The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl. Steget för spärrning och kerning, i tusendels em: i vågrät text ändrar Alt med vänster- eller högerpil kerningen vid markören eller spärrningen av den markerade texten ett steg, eller fem med Cmd/Ctrl. + The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. Steget för baslinjeförskjutning: i vågrät text flyttar Alt och Skift med uppåt- eller nedåtpil baslinjen ett steg, eller fem med Cmd/Ctrl. + Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. Visar alternativen för japansk och annan östasiatisk text i panelerna Tecken, Stycke, OpenType och Glyfer, och kommandot Sammansatta typsnitt. + Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. Visar alternativen för arabisk, hebreisk och indisk text i panelerna Tecken och Stycke, till exempel styckeriktning, kashidor och siffror. + The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. Markeringsverktygen markerar text bara på dess baslinje, ramen för områdestext eller dess bana, inte var som helst inuti dess ruta. + Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. Typsnittsmenyerna visar varje typsnitt med dess engelska namn; avstängt visar ett typsnitt som också har ett namn på sitt eget språk det namnet. + New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. Ny områdestext börjar med Automatisk storlek på, så att en rektangulär ram med vågrät text växer eller krymper på höjden för att rymma texten. + Font lists and the Type › Font menu show a sample of each font beside its name. Typsnittslistor och menyn Typsnitt visar ett prov på varje typsnitt bredvid dess namn. + Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on. Typsnittsprov ritas med mörk text på vitt oavsett gränssnittets ljusstyrka; det gäller bara medan förhandsvisningar av typsnitt i menyer är på. + How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is. Hur hög varje rad är i listorna för typsnittsfält, som det i panelen Tecken, och därmed hur stort varje prov är. + How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first. Hur många av de senast använda typsnitten, från 1 till 15, Senaste typsnitt och typsnittslistorna visar, det nyaste först. + When you change the font or font style of text, characters the new font has no glyph for keep the font they had. När du byter typsnitt eller typsnittsstil för text behåller tecken som det nya typsnittet saknar glyf för det typsnitt de hade. + A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export. En rosa markering på arbetsytan visar glyfer som OpenType-funktioner har ersatt, till exempel ligaturer; den skrivs inte ut och exporteras inte. + With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from. Med textverktyget visar en markering av ett enda tecken en rad med dess alternativa glyfer bredvid det på arbetsytan att välja bland. + A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export. En rosa markering på arbetsytan visar text som ritas med ett ersättningstypsnitt eftersom dess typsnitt saknas; den skrivs inte ut och exporteras inte. + New type made with a Type tool starts with placeholder text, selected, so typing replaces it. Ny text som skapas med ett textverktyg börjar med markerad platshållartext, som det du skriver ersätter. + Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list. Att skriva en listmarkör som 1. eller * och sedan ett blanksteg i början av ett stycke gör stycket till en lista. + Fonts in this folder show in the font menus and can be used without being installed. Typsnitt i den här mappen visas i typsnittsmenyerna och kan användas utan att installeras. + Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows. När en grafikstil tillämpas på text tas teckens egen fyllning eller linje bort där stilen har en, så att stilens färg syns. + Align and Distribute measure point type by the ink of its glyphs instead of its em box. Justera och Fördela mäter punkttext efter glyfernas bläck i stället för dess em-ruta. + Align and Distribute measure area type by the ink of its glyphs instead of its frame. Justera och Fördela mäter områdestext efter glyfernas bläck i stället för dess ram. + The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box. Begränsningsramen och panelen Transformera mäter punkttext efter glyfernas bläck i stället för dess em-ruta. Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply. Fäster ritande, flyttning och skalning mot rutnätets underindelningar, även när rutnätet är dolt; medan det är på gäller inte Fäst mot pixel. The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead. Färgen på stödlinjer som inte är markerade; en rityta med en stödlinjeetikett ritar sina egna stödlinjer i etikettens färg. Draws guides as solid lines or as dots, including the guides already in the document. Ritar stödlinjer som heldragna linjer eller som punkter, även stödlinjer som redan finns i dokumentet. @@ -3146,6 +3221,7 @@ digits Malayalam Malayalam Rounded Rectangle Tool Verktyg för rundad rektangel Rounded Rectangle… Rundad rektangel… Row Size: Radstorlek: + Rows Rader Rows: Rader: Rule: Regel: Rulers Linjaler @@ -3308,6 +3384,9 @@ digits Malayalam Malayalam Search commands, tools, panels and effects… Sök kommandon, verktyg, paneler och effekter… No commands match Inga kommandon matchar {pos} of {total}: {name} {pos} av {total}: {name} + No menu item Inget menyalternativ + Toolbar Verktygsfält + {toolbar}, in the {tool} group {toolbar}, i gruppen {tool} @plural {n} result|{n} results {n} resultat|{n} resultat @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} av {n} resultat. Fortsätt skriva för att begränsa dem.|{shown} av {n} resultat. Fortsätt skriva för att begränsa dem. Recent Commands Senaste kommandon @@ -3388,6 +3467,7 @@ digits Malayalam Malayalam Set Slice Rectangle Ange skivrektangel Set Tab Stops Ange tabbstopp Set Text Ange text + Set the current fill or stroke to the selected color Ersätt den aktuella fyllningen eller konturen med den markerade färgen Set the selected color to the current color Ersätt den markerade färgen med den aktuella färgen Set Zoom Ange zoom Settings… Inställningar… @@ -3509,7 +3589,7 @@ digits Malayalam Malayalam Show Vivid/Muted Visa livfull/dämpad Show Warm/Cool Visa varm/kall Show {kind} Brushes Visa {kind}-penslar - Show/hide plate (Alt-click: only this plate) Visa/dölj plåt (Alt-klick: endast den här plåten) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Visa/dölj plåt (Alt-klick: endast den här plåten; Alt-klick igen: alla plåtar) Show: Visa: Shown with the optimised preview. Visas med den optimerade förhandsgranskningen. Side 1: Sida 1: @@ -3707,6 +3787,7 @@ digits Malayalam Malayalam Superscript (on the roadmap) Upphöjd (planeras) Superscript: Upphöjd: SVG Filters SVG-filter + SVG Filter SVG-filter SVG Interactivity SVG-interaktivitet Event: Händelse: JavaScript: JavaScript: @@ -3818,7 +3899,7 @@ digits Malayalam Malayalam Composite Fonts Sammansatta typsnitt Export Composite Fonts Exportera sammansatta typsnitt Import Composite Fonts Importera sammansatta typsnitt -@msg each font must be {name, parts} varje typsnitt måste vara {name, parts} +@msg each font must be {{name, parts}} varje typsnitt måste vara {{name, parts}} @msg unknown key `{k}`; a font takes name and parts okänd nyckel `{k}`; ett typsnitt tar name och parts @msg each font needs a name varje typsnitt behöver ett namn @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` kan inte vara namnet på ett sammansatt typsnitt (1 till {COMPOSITE_NAME_MAX} tecken, inga styrtecken) @@ -3831,7 +3912,10 @@ digits Malayalam Malayalam @msg two composite fonts are named `{_1}` två sammansatta typsnitt heter `{_1}` @msg `{_1}` is the name of an installed font `{_1}` är namnet på ett installerat typsnitt @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2} använder `{font}`, ett sammansatt typsnitt -@msg give fonts: [{name, parts}…] ange fonts: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] ange fonts: [{{name, parts}}…] +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` måste vara "document", {{artboards: [index, …]}} eller {{layers: [id, …]}} +@msg numbers out of order in {{}} quantifier talen står i fel ordning i kvantifieraren {{}} +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) färgen är inte en fri gradient (använd en med paint.editGradient {{kind: "freeform"}}) @msg path is empty path är tom @msg fonts must be a list of composite fonts fonts måste vara en lista med sammansatta typsnitt @msg names must be strings names måste vara strängar @@ -3914,6 +3998,13 @@ digits Malayalam Malayalam Thumbnail View Miniatyrvy Thumbnails: Miniatyrer: Tile Sida vid sida + Tile All Vertically Alla sida vid sida lodrätt + Tile All Horizontally Alla sida vid sida vågrätt + 2-Up Layout Layout med 2 + 3-Up Layout Layout med 3 + 4-Up Layout Layout med 4 + 6-Up Layout Layout med 6 + Arrange Documents Ordna dokument Tile Edge Color Rutkantsfärg Tile Edge Color… Rutkantsfärg… Tile Full Pages Dela upp i hela sidor @@ -4107,6 +4198,8 @@ digits Malayalam Malayalam V Spacing: V-avstånd: V: V: Variable Width Profile Profil för variabel bredd + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Konturens pensel behåller sin egen storlek, så en breddprofil ändrar inte konturen. Ta bort penseln för att använda en profil. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Konturens pensel behåller sin egen storlek, så en breddprofil ändrar inte konturen. Ta bort penseln för att använda en profil. Variables Variabler New Variable Ny variabel Delete Variable Radera variabel @@ -4171,7 +4264,7 @@ digits Malayalam Malayalam Vertical: Vertikalt: Very High Mycket hög View Visa - View Artboard Only Visa endast rityta + View Artboard Contents Only Visa endast ritytans innehåll View Opacity Mask Visa opacitetsmask View PDF after saving Visa PDF efter sparning View {n} Vy {n} @@ -4380,6 +4473,7 @@ imageTrace Outline Kontur Bevel Fasning Offset Förskjutning Axis Axel + Axis Angle Axelvinkel axis Horizontal Horisontell axis Vertical Vertikal axis Both Båda @@ -4450,6 +4544,13 @@ axis Both Båda Show External Script Warning Visa varning för externa skript A Script Is Running Ett skript körs Script Alert Skriptmeddelande + Script File Access Skriptets filåtkomst + The script asks to read a file you choose. Skriptet ber om att läsa en fil som du väljer. + The script asks to read and write a file you choose. Skriptet ber om att läsa och skriva en fil som du väljer. + The script asks to read and write a folder you choose, with everything in it. Skriptet ber om att läsa och skriva en mapp som du väljer, med allt innehåll. + Allow Once Tillåt en gång + Always Allow This Script Tillåt alltid det här skriptet + Deny Neka A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Ett skript kan ändra de öppna dokumenten och skriva filer genom de kommandon det kör. Kör bara skript du litar på. Do not show this warning again Visa inte den här varningen igen Stop the script and undo what it did? Then quit again. Stoppa skriptet och ångra det det gjort? Avsluta sedan igen. @@ -4466,6 +4567,8 @@ axis Both Båda @msg the script is no longer in the Scripts folder skriptet finns inte längre i mappen Scripts Some scripts were not listed Vissa skript visas inte i listan The Scripts folder cannot be read Mappen Scripts kan inte läsas + Loading scripts… Läser in skript… + The Scripts folder is still being read Mappen Scripts läses fortfarande @msg the script's run is no longer available skriptets körning är inte längre tillgänglig @msg a failed command changed undo steps that could not be put back, so the script was stopped ett misslyckat kommando ändrade ångrasteg som inte kunde återställas, så skriptet stoppades @msg a recovery copy could not be written, so the script was not run en återställningskopia kunde inte skrivas, så skriptet kördes inte @@ -4478,8 +4581,6 @@ axis Both Båda @msg Script file could not be read Skriptfilen kunde inte läsas @msg Script folder has more than 2,048 entries Skriptmappen har fler än 2 048 poster @msg Script file open mode must be r, w, e or a Skriptfilens öppningsläge måste vara r, w, e eller a -@msg Script file writing is not available Skrivning av skriptfiler är inte tillgänglig -@msg Script file dialogs are not available Fildialogrutor för skript är inte tillgängliga @msg Script files cannot be opened in another application Skriptfiler kan inte öppnas i ett annat program @msg Script file access is unavailable on the web Åtkomst till skriptfiler är inte tillgänglig på webben @msg Script has 256 files open Skriptet har 256 filer öppna @@ -4619,8 +4720,37 @@ liquify-list-end {0}, {1} {0} och {1} @msg is a prompt's answer, whose `value` must be a string or null är svaret på en prompt, vars `value` måste vara en sträng eller null @msg must have `kind` alert, confirm or prompt måste ha `kind` alert, confirm eller prompt @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` är bara för en körning utan någon att fråga: i appen svarar personen på varje dialogruta +@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` måste vara ett heltal från 1 till {_1} +@msg `args{place}` is nested more than 64 levels deep `args{place}` är kapslat mer än 64 nivåer djupt +@msg `args` must be an object `args` måste vara ett objekt +@msg `args` is larger than 1 MiB `args` är större än 1 MiB +@msg `path` is empty `path` är tomt +@msg `installed` takes a `path`, not a `source` `installed` tar en `path`, inte en `source` +@msg `path` must name a .js or .jsx file `path` måste ange en .js- eller .jsx-fil +@msg give exactly one of `path` and `source` ange exakt en av `path` och `source` @msg Running a script Kör ett skript @msg Copied the script report Kopierade skriptrapporten +@msg Script file access denied: {path} Skriptets filåtkomst nekades: {path} +@msg Script file access to the app's own folders is not allowed Skript får inte komma åt appens egna mappar +@msg Script file cannot encode the text Skriptets fil kan inte koda texten +@msg Script file could not be written Skriptets fil kunde inte skrivas +@msg Script file dialogs need a person to answer them Skriptets fildialoger behöver en person som svarar på dem +@msg Script file is not open for writing Skriptets fil är inte öppen för skrivning +@msg Script file name is already in use Namnet på skriptets fil används redan +@msg Script file name must be a name without a folder Namnet på skriptets fil måste vara ett namn utan mapp +@msg Script file permission can be kept only for a script run from a file Filbehörighet kan bara behållas för ett skript som körs från en fil +@msg Script file permission could not be saved Skriptets filbehörighet kunde inte sparas +@msg Script folder is not empty Skriptets mapp är inte tom +@msg Script files cannot make aliases Skriptets filer kan inte skapa alias +@msg Script file hidden setting cannot be changed Inställningen för dold för skriptets fil kan inte ändras +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: en fildialog kan inte öppnas i ett återanrop från en inbyggd funktion, en getter, en konvertering eller en fil som $.evalFile kör; anropa den från skriptets egen kod +@msg the script wrote more file data than one run may write (32 MiB) skriptet skrev mer fildata än en körning får skriva (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` för ett skripts fildialog måste vara ett av: once, always, deny, stop +@msg choose a file or folder first, or deny välj först en fil eller mapp, eller neka +@msg the script file permissions could not be saved: {e} skriptens filbehörigheter kunde inte sparas: {e} +@msg this script's file access can be allowed only once det här skriptets filåtkomst kan bara tillåtas en gång +@msg Only the person at the keyboard can allow a script's file access Bara personen vid tangentbordet kan tillåta ett skripts filåtkomst +@msg A script is given at most 2,048 files: the files picked after them were left out Ett skript får högst 2 048 filer: filerna som valdes efter dem utelämnades @msg Copied the link info Kopierade länkinfo @msg Corners edits the corners of a path Hörn redigerar hörnen på en bana @msg Couldn't copy to the system clipboard: {e} Kunde inte kopiera till systemets urklipp: {e} @@ -4695,6 +4825,7 @@ liquify-list-end {0}, {1} {0} och {1} @msg Saved {path} Sparade {path} @msg Select text or click into text with the Type tool to insert glyphs Markera text eller klicka i text med textverktyget för att infoga glyfer @msg Shape Builder: no region under the pointer Formbyggare: inget område under pekaren +@msg Shape Builder: select all paths you want to merge Formbyggare: markera alla banor du vill sammanfoga @msg Shape Builder: select paths or compound paths Formbyggare: markera banor eller sammansatta banor @msg Show All Hidden Attributes: nothing is hidden Visa alla dolda attribut: ingenting är dolt @msg Split Into Grid: select paths large enough for the grid Dela upp i rutnät: markera banor som är tillräckligt stora för rutnätet @@ -4829,6 +4960,7 @@ liquify-list-end {0}, {1} {0} och {1} @msg bad trailer ogiltig trailer @msg balance must be between 0 and 100 balance måste vara mellan 0 och 100 @msg batch step {_1} (`{id}`) failed: {e} batchsteg {_1} (`{id}`) misslyckades: {e} +@msg action step {_1} (`{id}`) failed: {reason} åtgärdssteg {_1} (`{id}`) misslyckades: {reason} @msg brightness must be dark|mediumDark|mediumLight|light brightness måste vara dark|mediumDark|mediumLight|light @msg can't encode the document: {0} kan inte koda dokumentet: {0} @msg can't parse shortcut `{c}` kan inte tolka kortkommandot `{c}` @@ -4848,6 +4980,7 @@ liquify-list-end {0}, {1} {0} och {1} @msg choose a folder to export to välj en mapp att exportera till @msg choose a location for the package välj en plats för paketet @msg clipboard is empty urklippet är tomt +@msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: minst en färg måste finnas kvar i färgtabellen @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` är inte en färg som "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: högst {MAX_TABLE} färger @msg command `{0}` is not available right now: {1} kommandot `{0}` är inte tillgängligt just nu: {1} @@ -4915,9 +5048,15 @@ liquify-list-end {0}, {1} {0} och {1} @msg no PNG encoder ingen PNG-kodare @msg no active document inget aktivt dokument @msg no active perspective plane inget aktivt perspektivplan +@msg the perspective grid is hidden perspektivrutnätet är dolt +@msg Automatic Plane Positioning is off: turn on anchorPoint or gridlineIntersection (perspective.widget.options) Automatisk planplacering är avstängd: slå på anchorPoint eller gridlineIntersection (perspective.widget.options) +@msg anchorPoint must be true or false anchorPoint måste vara true eller false +@msg gridlineIntersection must be true or false gridlineIntersection måste vara true eller false +@msg tolerance must be 0 or more tolerance måste vara 0 eller mer +@msg give `at` or `clear`, not both ange `at` eller `clear`, inte båda @msg no anchor points selected inga ankarpunkter är markerade -@msg `points` must be three [x, y] pairs of numbers `points` måste vara tre talpar [x, y] -@msg direct-select three anchor points, or give `points` direktmarkera tre ankarpunkter eller ange `points` +@msg `points` must be two or three [x, y] pairs of numbers `points` måste vara två eller tre talpar [x, y] +@msg direct-select two or three anchor points, or give `points` direktmarkera två eller tre ankarpunkter eller ange `points` @msg no circle passes through these points: two are the same or all three lie on one line ingen cirkel går genom de här punkterna: två är samma punkt eller så ligger alla tre på en linje @msg no app to open files here det finns ingen app för att öppna filer här @msg no artboard ingen rityta @@ -5019,6 +5158,9 @@ liquify-list-end {0}, {1} {0} och {1} @msg no such user library användarbiblioteket finns inte @msg no such view vyn finns inte @msg no such width point breddpunkten finns inte +@msg `single` must be `incoming` or `outgoing` `single` måste vara `incoming` eller `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` och `outIndex` måste vara de två halvorna av en och samma diskontinuerliga breddpunkt +@msg a discontinuous width point keeps its place en diskontinuerlig breddpunkt behåller sin plats @msg no swatch `{name}` ingen färgruta `{name}` @msg no swatch library `{l}` (see swatch.library.list) inget färgrutebibliotek `{l}` (se swatch.library.list) @msg no symbol instances selected inga symbolinstanser är markerade @@ -5271,6 +5413,13 @@ liquify-list-end {0}, {1} {0} och {1} @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} fler än {MAX_CSV_ROWS} datauppsättningar: Importera datauppsättningar läser högst {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} fler än {MAX_CSV_COLS} variabler: Importera datauppsättningar läser högst {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} variabler som inte är text utelämnades: {kinds} +variable-kind Visibility Synlighet +variable-kind Linked File Länkad fil +variable-kind Graph Data Diagramdata +variable-kind Unknown Okänd +variable-list-two {0}, {1} {0} och {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} och {1} @msg a new document won't read these variables back with their kind: {names} ett nytt dokument läser inte tillbaka dessa variabler med deras typ: {names} @msg a new document refuses this file because of these variables: {names} ett nytt dokument avvisar den här filen på grund av dessa variabler: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them rubriken `{header}` för `{name}` skulle läsas som variabeln `{other}`: byt namn på en av dem @@ -5296,6 +5445,8 @@ liquify-list-end {0}, {1} {0} och {1} @msg {label}: lost track of a shape's style {label}: tappade bort en forms stil @msg {label}: select paths {label}: markera banor @msg {label}: select paths, compound paths, groups or text {label}: markera banor, sammansatta banor, grupper eller text +@msg a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first en linje eller annan öppen bana som inte omsluter någon yta ändrar inte resultatets form; för att ta med den, använd först Objekt › Bana › Konvertera kontur till form på den +@msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first {label} gav ett tomt resultat: en linje eller annan öppen bana omsluter ingen yta; för att ta med den, använd först Objekt › Bana › Konvertera kontur till form på den @msg {label}… {label}… @msg {name}: CRC mismatch {name}: CRC stämmer inte @msg {name}: no local header {name}: lokalt huvud saknas @@ -5322,6 +5473,9 @@ liquify-list-end {0}, {1} {0} och {1} @msgplural Discarded {n} recovered document|Discarded {n} recovered documents Kastade {n} återställt dokument|Kastade {n} återställda dokument @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them Återställde {n} återskapat dokument: spara det för att behålla det|Återställde {n} återskapade dokument: spara dem för att behålla dem @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} Öppnad med {n} anteckning: {first}|Öppnad med {n} anteckningar: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Kopierade med {n} anteckning: {first}|Kopierade med {n} anteckningar: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Klippte ut med {n} anteckning: {first}|Klippte ut med {n} anteckningar: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Kalkerade bilden med {n} anteckning: {first}|Kalkerade bilden med {n} anteckningar: {first} @msgplural {notice}. Opened with {n} note: {first}|{notice}. Opened with {n} notes: {first} {notice}. Öppnad med {n} anteckning: {first}|{notice}. Öppnad med {n} anteckningar: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} Sparade {path} med {n} anteckning: {first}|Sparade {path} med {n} anteckningar: {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first Bäddade in {n} bild; {missing} saknas: länka om dem först|Bäddade in {n} bilder; {missing} saknas: länka om dem först @@ -5348,6 +5502,8 @@ liquify-list-end {0}, {1} {0} och {1} @msg All colors are within the CMYK gamut Alla färger ligger inom CMYK-färgomfånget @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} färg ligger utanför CMYK-färgomfånget|{n} färger ligger utanför CMYK-färgomfånget @msg Unembedded to {_1} Extraherad till {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} Extraherade {n} bild till {folder}|Extraherade {n} bilder till {folder} +@msg every numbered name for {name} is taken in that folder alla numrerade namn för {name} är upptagna i den mappen @msg Reset {_1} Återställ {_1} @msg Sent to {_1} Skickat till {_1} @msg {_1} files {_1}-filer @@ -5363,6 +5519,8 @@ liquify-list-end {0}, {1} {0} och {1} @msg Reload the page to go on (changes not saved yet may be lost). Läs in sidan igen för att fortsätta (ändringar som inte sparats än kan gå förlorade). @msg tool (a tool id) is required tool (ett verktygs-id) krävs @msg {tool} isn't in a toolbar group of several tools {tool} ingår inte i en verktygsgrupp med flera verktyg +@msg Presentation Mode hides the toolbars: change the screen mode to show them Presentationsläge döljer verktygsfälten: byt skärmläge för att visa dem +@msg Tab has hidden the toolbars: press Tab to show them Tab har dolt verktygsfälten: tryck på Tab för att visa dem @msg onto must name a panel floating in another group onto måste ange en panel som flyter i en annan grupp @msg below and above must name a panel floating in another group below och above måste ange en panel som flyter i en annan grupp @msg give only one of onto, below and above ange bara en av onto, below och above @@ -5497,6 +5655,9 @@ liquify-list-end {0}, {1} {0} och {1} @msg automation filesystem access is not granted: write authority is absent: {path} automatiseringen har inte fått åtkomst till filsystemet: skrivbehörighet saknas: {path} @msg automation path rejected: outside the read root {root}: {path} automatiseringssökvägen avvisades: utanför läsroten {root}: {path} @msg automation path rejected: outside the read roots {roots}: {path} automatiseringssökvägen avvisades: utanför läsrötterna {roots}: {path} +@msg a linked image file is outside the read roots en länkad bildfil ligger utanför läsrötterna +@msg a linked file's export folder is outside the read roots exportmappen för en länkad fil ligger utanför läsrötterna +@msg a linked file's editing data can't be read to check it against the read roots redigeringsdata för en länkad fil kan inte läsas för att kontrolleras mot läsrötterna @msg automation path rejected: outside the write root {root}: {path} automatiseringssökvägen avvisades: utanför skrivroten {root}: {path} @msg automation path rejected: outside the write roots {roots}: {path} automatiseringssökvägen avvisades: utanför skrivrötterna {roots}: {path} @msg automation path rejected: path is empty automatiseringssökvägen avvisades: sökvägen är tom @@ -5720,6 +5881,7 @@ lighting Light Ljus @msg missing panel layout panellayout saknas @msg unsupported native docking operation inbyggd dockningsåtgärd som inte stöds Linux Display Server Linux-skärmserver + Low-Latency Drawing Ritning med låg latens X11 (XWayland) When a Pen Is Attached X11 (XWayland) när en penna är ansluten If a drawing tablet's pen doesn't draw, choose an X11 (XWayland) option. Om ritplattans penna inte ritar väljer du ett X11 (XWayland)-alternativ. X11 (XWayland) X11 (XWayland) @@ -5772,6 +5934,7 @@ lighting Light Ljus Cove Hålkäl Depth Djup Front Framifrån + Side Från sidan Isometric Bottom Isometrisk underifrån Isometric Left Isometrisk vänster Isometric Right Isometrisk höger @@ -5867,10 +6030,11 @@ lighting Light Ljus @msg each of `{GRAPHICS}` must be an object varje post i `{GRAPHICS}` måste vara ett objekt @msg `{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}` posterna i `{GRAPHICS}` tar symbol, face, x, y, scale och rotation, inte `{k}` @msg each of `{GRAPHICS}` needs `symbol`, the name of a symbol varje post i `{GRAPHICS}` behöver `symbol`, namnet på en symbol -@msg `{GRAPHICS}` face must be front or back face i `{GRAPHICS}` måste vara front eller back +@msg `{GRAPHICS}` face must be front, back or side face i `{GRAPHICS}` måste vara front, back eller side @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} i `{GRAPHICS}` måste vara ett tal från {lo} till {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` måste vara en matris @msg Graphics map onto the Plane, Extrude and Revolve object types Grafik placeras på objekttyperna Plan, Extrudera och Rotera runt axel + Graphics map onto the Plane, Extrude and Revolve object types. Grafik placeras på objekttyperna Plan, Extrudera och Rotera runt axel. @msg Revolve maps graphics onto its side: map them onto the front Rotera runt axel placerar grafik på sin mantelyta: placera den på framsidan @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Grafiken är för komplex för den här ytan: förenkla symbolernas teckning eller minska Segment @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` tar högst {MAX_GRAPHICS} grafiker @@ -6305,6 +6469,7 @@ lighting Light Ljus of av sRGB IEC61966-2.1 sRGB IEC61966-2.1 x Height x-höjd + Em Box Height Em-rutans höjd ▾ Default Actions ▾ Standardåtgärder ⚠ {chord} was already used by {names} — it has been removed there. Obs! {chord} användes redan av {names} – det har tagits bort där. @id file.close Stäng @@ -6450,6 +6615,8 @@ theme Appearance Utseende Reset Horizontal Scale Återställ horisontell skala Reset Tracking and Kerning Återställ spärrning och kerning Highlight Font Name Framhäv typsnittsnamn + Highlight Font Size Framhäv teckenstorlek + Other… Annan… Highlight Kerning Framhäv kerning Highlight Tracking Framhäv spärrning Sample Color from Screen Hämta färg från skärmen @@ -6491,6 +6658,8 @@ theme Appearance Utseende @msg Unknown dimension option {k} Okänt måttalternativ {k} @msg Unknown dimension orientation Okänd måttriktning @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` måste vara grayscale, rgb, hsb, cmyk eller websafe +@msg `view` must be wheel or box `view` måste vara wheel eller box +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` måste vara hue, saturation, brightness, red, green eller blue @msg `{key}` must be an array of these names: {_1} `{key}` måste vara en lista med dessa namn: {_1} @msg choose a destination folder välj en målmapp @msg choose a source folder välj en källmapp @@ -6581,6 +6750,11 @@ theme Appearance Utseende Override Action "Open" Commands Ändra åtgärdens "Öppna"-kommandon lokalt Override Action "Save" Commands Ändra åtgärdens "Spara"-kommandon lokalt Path Length Banlängd + Grid Size Rutnätsstorlek + Grid Colors Rutnätsfärger + Flattener Preset Förinställning för tillplattning + X X + Y Y Play: Spela upp: Save and Close Spara och stäng Stop on Errors Stoppa vid fel @@ -7409,6 +7583,12 @@ anchor Points: Punkter: @msg not an RTF file: it doesn't start with {{\\rtf inte en RTF-fil: den börjar inte med {{\\rtf shape Open Öppen +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Enhetsomvandlare + Unit Converter Panel Panelen Enhetsomvandlare + Copy with Units Kopiera med enheter + From Selection Från markering + # Color Effects add-on: Select by Color Kind. Select by Color Kind Markera efter färgtyp Objects with Spot Colors Objekt med dekorfärger @@ -7632,6 +7812,14 @@ breakText Glyphs Glyfer Remove Gaps Ta bort mellanrum @msg that makes too many pieces (at most 100000): make the dashes longer det blir för många delar (högst 100000): gör strecken längre @msg select paths, or segments, to divide markera banor eller segment att dela upp +# Path Precision Tools add-on: Smooth Bridge. + Smooth Bridge… Mjuk brygga… + Smooth Bridge Mjuk brygga + Keep Originals Behåll original +@msg select two circles to bridge markera två cirklar att förbinda +@msg one circle is inside the other den ena cirkeln ligger inuti den andra +@msg the circles are too far apart for this radius: raise the radius cirklarna ligger för långt ifrån varandra för den här radien: öka radien +@msg the circles are too far apart for this radius cirklarna ligger för långt ifrån varandra för den här radien # Path Precision Tools add-on: Common Tangents. Common Tangents… Gemensamma tangenter… Common Tangents Gemensamma tangenter @@ -7944,6 +8132,8 @@ digits Hindi Hindi @msg `{file}` is over {_1} MB `{file}` är större än {_1} MB @msg `{id}` is no writable format (see document.formats) `{id}` är inget skrivbart format (se document.formats) @msg `{id}` isn't a loaded library `{id}` är inte ett inläst bibliotek +@msg `{file}` has no swatches of its own `{file}` har inga egna färgrutor +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` har mönsterprover, som en .vcswatches-fil inte kan innehålla @msg `{k}.family` is required `{k}.family` är obligatoriskt @msg `{k}` is a number 0..1 `{k}` är ett tal 0..1 @msg `{k}` is true or false `{k}` är true eller false @@ -8319,7 +8509,13 @@ digits Hindi Hindi @msg colorModel must be {own} (the document's mode), grayscale or bitmap colorModel måste vara {own} (dokumentets läge), grayscale eller bitmap @msg colour groups can't go into colour groups färggrupper kan inte läggas i färggrupper @msg colour, mode and spot apply to solid-colour swatches only färg, läge och dekor gäller endast enfärgade färgrutor -@msg column {column}: `{cell}` is a `%` column of graph data files, which are not read kolumn {column}: `{cell}` är en `%`-kolumn i diagramdatafiler, som inte läses +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path rad {line}, kolumn {column}: diagramdatafilen `{path}` för `{var}` är en relativ sökväg: ange `base` eller en absolut sökväg +@msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} rad {line}, kolumn {column}: diagramdatafilen för `{var}` kan inte läsas: {e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` isn't followed: {r} rad {line}, kolumn {column}: diagramdatafilen `{path}` för `{var}` följs inte: {r} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes rad {line}, kolumn {column}: diagramdatafilen `{path}` för `{var}` är större än {MAX_GRAPH_DATA_FILE} byte +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes rad {line}, kolumn {column}: diagramdatafilen `{path}` för `{var}` ger ett diagramvärde som är längre än {MAX_GRAPH_CSV} byte +@msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all rad {line}, kolumn {column}: diagramdatafilerna innehåller sammanlagt mer än {MAX_GRAPH_FILES_TOTAL} byte +@msg `base` is empty `base` är tom @msg column {column}: `{cell}` names `{name}`, which is a {_1} variable kolumn {column}: `{cell}` anger `{name}`, som är en {_1}-variabel @msg column {column}: `{cell}` names no variable kolumn {column}: `{cell}` anger ingen variabel @msg column {column}: the variable name is longer than {MAX_NAME} characters kolumn {column}: variabelnamnet är längre än {MAX_NAME} tecken @@ -8331,6 +8527,7 @@ digits Hindi Hindi @msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes sammansatta former tar banor, sammansatta banor, grupper, sammansatta former, text, övergångar och kuvert @msg connect end must be "start" or "end" connect end måste vara "start" eller "end" @msg connect needs a path other than the one extended connect behöver en annan bana än den som förlängs +@msg connect needs extend connect behöver extend @msg connect needs id connect behöver id @msg connect path has no open end connect-banan har ingen öppen ände @msg Contour: select paths or shapes Kontur: markera banor eller former @@ -9600,4 +9797,14 @@ digits Hindi Hindi @msg A panel is not joined to the rest by a crease. En panel är inte förbunden med resten av någon biglinje. @msg A fold line is on a non-printing layer. En falslinje ligger på ett lager som inte skrivs ut. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneler: {panels}, gångjärn: {hinges}, fel: {errors}, varningar: {warnings} + Fold Preview Förhandsgranskning av falsning + Fold Falsning + Show Fold Lines Visa falslinjer + Three-Quarter Trekvarts + Open a document to preview its folded shape. Öppna ett dokument för att förhandsgranska dess falsade form. +@msg Check the fold lines first. Kontrollera falslinjerna först. +@msg Panels: {panels}, hinges: {hinges} Paneler: {panels}, gångjärn: {hinges} +@msg Other blanks not shown: {count} Andra ämnen visas inte: {count} +@msg A joint does not close by {gap} pt. En fog sluter inte med {gap} pt. +@msg Two panels pass through each other. Två paneler går igenom varandra. @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} pixlar är för stort för PSD (högst {MAX_SIDE} pixlar per sida): sänk upplösningen diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 97fccd9167..1ef955c627 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -373,6 +373,33 @@ fn turkish_draw_labels_use_the_drawing_verb() { assert_eq!(message(tr_lang, "Scale must be drawing:real, for example 1:10"), "Ölçek çizim:gerçek biçiminde olmalıdır, örneğin 1:10"); } +/// Turkish rows that name the Revolve or Extrude & Bevel effect use the catalog's label for that +/// effect, so a message about Revolve does not read as Rotate. `Revolve angle` names a control, +/// not the effect, and keeps its own wording. +#[test] +fn turkish_three_d_rows_use_the_effect_labels() { + let tr_lang = Lang::from_code("tr").expect("tr registered"); + let revolve = message(tr_lang, "Revolve"); + let extrude = message(tr_lang, "Extrude & Bevel"); + assert_eq!(revolve, "Eksen Etrafında Döndür"); + assert_eq!(extrude, "Ekstrüzyon ve Eğim"); + let (entries, _) = parse_entries(tr_lang.0.source); + let mut wrong = Vec::new(); + for (_, src, t) in &entries { + let names_revolve = src.split(|c: char| !c.is_alphanumeric()).any(|w| w == "Revolve") && src != "Revolve angle"; + if (names_revolve && (!t.contains(revolve.as_str()) || t.contains("Revolve"))) + || (src.contains("Extrude & Bevel") && !t.contains(extrude.as_str())) + { + wrong.push(format!("{src:?} -> {t:?}")); + } + } + assert!(wrong.is_empty(), "Turkish rows that do not use the effect label:\n{}", wrong.join("\n")); + assert_eq!( + message(tr_lang, "the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate)"), + "nesnenin 3 boyutlu efekti yok (Ekstrüzyon ve Eğim, Eksen Etrafında Döndür, Şişir veya Döndür)" + ); +} + /// The Catalan catalog registers under `ca`, claims complete menus and messages, and passes /// locale resolution, vocabulary and count formatting checks. #[test] @@ -402,6 +429,22 @@ fn catalan_reads_as_catalan() { assert_eq!(message(ca, nested), "l’ordre `object.group` no està disponible ara mateix: no hi ha res seleccionat"); } +/// The Swedish catalog names the SVG Filter and Check Spelling commands without their ellipsis, +/// the SVG Filter undo step, and the 3D and Materials panel's note with its period. +#[test] +fn swedish_svg_filter_spelling_and_3d_labels_are_complete() { + let sv = Lang::from_code("sv").expect("sv registered"); + for (en, want) in [ + ("Apply SVG Filter", "Använd SVG-filter"), + ("Check Spelling", "Kontrollera stavning"), + ("SVG Filter", "SVG-filter"), + ("Graphics map onto the Plane, Extrude and Revolve object types.", "Grafik placeras på objekttyperna Plan, Extrudera och Rotera runt axel."), + ] { + assert_eq!(sv.catalog().plain(en), Some(want), "{en}"); + } + assert_eq!(crate::panels::history::step_name(sv, "SVG Filter").as_deref(), Some("SVG-filter")); +} + /// Brazilian Portuguese spells Relink "Revincular", and no row calls a process color a /// selection color ("cor de seleção"). #[test] @@ -423,6 +466,27 @@ fn brazilian_portuguese_spells_relink_and_process_color() { assert!(message(pt, "`{name}` is a process colour: tints apply to global and spot colours").to_lowercase().contains("cor de processo")); } +/// Every Greek row that names a knockout says διάτρηση, never αποκοπή, which stays for clipping +/// and cutting. +#[test] +fn greek_rows_use_one_term_for_knockout() { + let el = Lang::from_code("el").expect("el registered"); + let (entries, _) = parse_entries(el.0.source); + let mut wrong = Vec::new(); + for (_, src, translation) in &entries { + let greek = translation.to_lowercase(); + let knockout_term = greek.contains("διάτρη") || greek.contains("διατρ"); + if src.to_lowercase().contains("knockout") && (greek.contains("αποκοπ") || !knockout_term) { + wrong.push(format!("knockout in {src:?} -> {translation:?}")); + } + } + assert!(wrong.is_empty(), "{} Greek rows use the wrong term:\n{}", wrong.len(), wrong.join("\n")); + assert_eq!(tr(el, "Knockout Group"), "Ομάδα διάτρησης"); + assert_eq!(tr(el, "Page Knockout Group"), "Ομάδα διάτρησης σελίδας"); + assert_eq!(tr(el, "Opacity & Mask Define Knockout Shape"), "Η αδιαφάνεια και η μάσκα καθορίζουν το σχήμα διάτρησης"); + assert_eq!(tr(el, "Clip Group"), "Ομάδα αποκοπής"); +} + #[test] fn font_height_reference_labels_are_in_complete_catalogs() { for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { @@ -434,6 +498,21 @@ fn font_height_reference_labels_are_in_complete_catalogs() { } } +/// Area Type Options › First Baseline's choices (the dropdown reads them in the "effect" context, +/// falling back to the plain row). +#[test] +fn first_baseline_choices_are_in_complete_catalogs() { + let mut missing = vec![]; + for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { + for label in ["Ascent", "Cap Height", "x Height", "Leading", "Em Box Height", "Fixed"] { + if lang.catalog().plain(label).is_none() && lang.catalog().contextual("effect", label).is_none() { + missing.push(format!("{} {label}", lang.code)); + } + } + } + assert!(missing.is_empty(), "{missing:?}"); +} + /// Each catalog's Saved View N and Saved Selection N rows carry the number N, and no two of a /// catalog's saved views or saved selections show one name, whatever digits the language uses. #[test] @@ -475,6 +554,21 @@ fn objects_on_path_detach_strings_are_in_complete_catalogs() { } } +/// The status messages the Shape Builder tool gives when a gesture builds nothing come from the +/// tools crate, which [`message_literals`] does not scan, so every complete catalog is checked for +/// them here. +#[test] +fn shape_builder_status_messages_are_in_complete_catalogs() { + use vectorcraft_tools::builder::SHAPE_BUILDER_STATUS; + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + for s in SHAPE_BUILDER_STATUS { + assert_ne!(message(lang, s), s, "{code}: {s}"); + } + } + assert_eq!(message(de(), SHAPE_BUILDER_STATUS[1]), "Formerstellung: Wählen Sie alle Pfade aus, die Sie zusammenfügen möchten"); +} + /// The Window › Brush Libraries menu, built from the built-in library table, names each library. #[test] fn built_in_brush_library_names_are_in_complete_catalogs() { @@ -513,6 +607,17 @@ fn built_in_library_brush_names_are_in_complete_catalogs() { assert!(bad.is_empty(), "{}", bad.join("\n")); } +/// Window › Arrange's Tile layouts and the application bar's Arrange Documents button. +#[test] +fn tile_layout_labels_are_in_complete_catalogs() { + for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { + for label in ["Tile All Vertically", "Tile All Horizontally", "2-Up Layout", "3-Up Layout", "4-Up Layout", "6-Up Layout", "Arrange Documents"] + { + assert!(lang.catalog().plain(label).is_some(), "{} is missing {label}", lang.code); + } + } +} + /// Preference choices and the marquee's E hint share the same translated labels. #[test] fn marquee_selection_labels_are_in_complete_catalogs() { @@ -529,6 +634,7 @@ fn monitor_profile_labels_are_in_complete_catalogs() { for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { for label in [ "Use Monitor Profile for Canvas", + "Refresh Monitor Profile", "The canvas is drawn in sRGB.", "Canvas display profile:", "The system matches the window to the display's colors.", @@ -539,6 +645,22 @@ fn monitor_profile_labels_are_in_complete_catalogs() { } } +/// Text Import Options' Character Set choices that name a script or a region (Shift JIS, GB2312 +/// and GB18030 are names of their own), and the error for an unknown character set. +#[test] +fn text_import_character_sets_are_in_complete_catalogs() { + for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { + for label in ["Chinese Big 5", "Cyrillic", "Greek", "Turkish", "Baltic", "Central European"] { + assert!(lang.catalog().plain(label).is_some(), "{} is missing {label}", lang.code); + } + } + let unknown = r#"text.characterSet `x`: use "unicode", "ansi", "shiftJis", "gb2312", "chineseBig5", "cyrillic", "gb18030", "greek", "turkish", "baltic" or "centralEuropean""#; + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + assert_ne!(message(lang, unknown), unknown, "{code}"); + } +} + /// The Control bar panel menu's items, its groups of options and the edges, and the label of the /// command that turns a group on or off. #[test] @@ -570,14 +692,30 @@ fn control_bar_panel_menu_labels_are_in_complete_catalogs() { } } +/// The Navigator panel menu's items are in every complete catalog, and no catalog keeps the +/// item's earlier name, View Artboard Only. +#[test] +fn navigator_panel_menu_labels_are_in_complete_catalogs() { + for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { + for label in ["View Artboard Contents Only", "Panel Options…"] { + assert!(lang.catalog().plain(label).is_some(), "{} is missing {label}", lang.code); + } + } + for lang in LANGUAGES.iter() { + assert!(lang.catalog().plain("View Artboard Only").is_none(), "{} keeps View Artboard Only", lang.code); + } +} + /// Document Info's labels: every category title, which the panel and its menu show, every count -/// label of the Objects category, and the Document category's fixed row labels (the artboard rows -/// show artboard names and are left out). +/// label of the Objects category, and the Document category's fixed row labels, those of the +/// artboard the Artboard tool has selected included (the artboard rows show artboard names and are +/// left out). #[test] fn document_info_labels_are_in_complete_catalogs() { let mut session = vectorcraft_engine::Session::new(); session.execute("file.new", &serde_json::json!({"width": 100, "height": 100})).unwrap(); session.execute("shape.rectangle", &serde_json::json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + session.select_tool("artboard", vectorcraft_engine::ViewInfo::default()).unwrap(); let info = session.execute("document.info", &serde_json::json!({})).unwrap(); let sections = info["sections"].as_array().unwrap(); let titles: Vec<&str> = sections.iter().filter_map(|s| s["title"].as_str()).collect(); @@ -592,7 +730,7 @@ fn document_info_labels_are_in_complete_catalogs() { let artboards = document.iter().position(|r| r[0] == "Artboards").unwrap(); let names = artboards + 1..=artboards + document[artboards][1].as_str().unwrap().parse::().unwrap(); let fixed: Vec<&str> = document.iter().enumerate().filter(|(k, _)| !names.contains(k)).filter_map(|(_, r)| r[0].as_str()).collect(); - assert_eq!(fixed.len(), 9, "{fixed:?}"); + assert_eq!(fixed.len(), 18, "{fixed:?}"); labels.extend(fixed); for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { for label in &labels { @@ -603,7 +741,8 @@ fn document_info_labels_are_in_complete_catalogs() { /// The values Document Info makes and shows in the interface language: the font states and /// embedding permissions, the templates of the font, image, raster effects and Repeat object -/// values, the names of gradients named by their kind, and the counted instances, rows and columns. +/// values, the names of gradients named by their kind, the counted instances, rows and columns, and +/// the transparency settings' values. #[test] fn document_info_values_are_in_complete_catalogs() { const VALUES: [&str; 20] = [ @@ -629,6 +768,17 @@ fn document_info_values_are_in_complete_catalogs() { "Freeform gradient", ]; const COUNTED: [(&str, &str); 3] = [("{n} instance", "{n} instances"), ("{n} row", "{n} rows"), ("{n} column", "{n} columns")]; + // The transparency settings' values: the grid's sizes and color presets, on and off, and the + // built-in flattener presets. + let transparency = ["Small", "Medium", "Large", "On", "Off", "High Resolution", "Medium Resolution", "Low Resolution"] + .into_iter() + .chain(vectorcraft_doc::setup::GRID_COLOR_PRESETS.iter().map(|(name, _)| *name)); + let transparency: Vec<&str> = transparency.collect(); + for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { + for value in &transparency { + assert!(lang.catalog().plain(value).is_some(), "{} is missing {value}", lang.code); + } + } let gradient_kinds: Vec = vectorcraft_color::GradientKind::ALL.iter().map(|k| format!("{} gradient", k.label())).collect(); assert!(gradient_kinds.iter().all(|k| VALUES.contains(&k.as_str())), "{gradient_kinds:?}"); for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { @@ -654,6 +804,21 @@ fn anti_aliasing_method_labels_are_in_complete_catalogs() { } } +/// Each row in the `search` context, which adds a language's words to a group of words with the same +/// meaning for the command palette, names a group and adds single words of no other group. No +/// catalog has to have these rows. +#[test] +fn search_rows_name_a_group_and_add_single_words() { + let mut bad = Vec::new(); + for l in LANGUAGES.iter().filter(|l| !l.source.is_empty()) { + let (entries, _) = parse_entries(l.source); + for (_, src, tr) in entries.iter().filter(|(ctx, _, _)| ctx == crate::palette::words::CONTEXT) { + bad.extend(crate::palette::words::row_problems(src, tr).into_iter().map(|p| format!("{}: {p}", l.code))); + } + } + assert!(bad.is_empty(), "{bad:#?}"); +} + /// The Painted and Sketched graphic style library's name and its styles' names have a row in every /// bundled catalog. #[test] @@ -1018,6 +1183,36 @@ fn bundled_fonts_cover_the_catalogs() { assert!(missing.is_empty(), "characters without a glyph: {missing:#?}"); } +/// The faces the web build fetches on demand (`web-fonts.txt`: NanumGothic for Korean, Noto Sans +/// Devanagari for Hindi) cover every character of their scripts that a catalog or a language name +/// uses. Checked where the craft-fonts checkout has them (the desktop build embeds every face). +#[test] +fn web_demand_fonts_cover_the_catalogs() { + use vectorcraft_text::craft_fonts::demand_script; + let demand: Vec<_> = vectorcraft_text::WEB_FONTS.iter().filter(|w| w.demand).collect(); + if demand.is_empty() { + eprintln!("skipped: built without craft-fonts, or one without NanumGothic and Noto Sans Devanagari"); + return; + } + let mut chars: std::collections::BTreeSet = LANGUAGES.iter().flat_map(|l| l.name.chars()).collect(); + for l in LANGUAGES.iter().filter(|l| !l.source.is_empty()) { + let (entries, _) = parse_entries(l.source); + chars.extend(entries.iter().flat_map(|(_, _, tr)| tr.chars())); + } + let mut missing = std::collections::BTreeMap::new(); + for w in demand { + let Some(f) = vectorcraft_text::CRAFT_FONTS.iter().find(|f| f.family == w.family && f.style == w.style) else { continue }; + let db = vectorcraft_text::FontDb::with_font_dirs(vec![]); + db.add_font(f.bytes.to_vec()); + let face = db.face(f.family, f.style).expect("the craft-fonts face loads"); + let gone: String = chars.iter().filter(|c| demand_script(**c).is_some_and(|s| w.scripts.contains(&s)) && !face.covers(**c)).collect(); + if !gone.is_empty() { + missing.insert(w.family, gone); + } + } + assert!(missing.is_empty(), "characters the web's demand faces lack: {missing:#?}"); +} + /// The Traditional Chinese catalog holds no Simplified-only characters (a translation written /// in the wrong script would read as a typo to every user). #[test] @@ -1146,6 +1341,26 @@ fn leading_term_agrees_within_each_catalog() { assert!(bad.is_empty(), "rows that name leading differently from the Leading field:\n{}", bad.join("\n")); } +/// A plain row whose English ends with a number, such as "Saved View 10", has that number in its +/// translation as a number of its own, so the rows of a numbered list do not swap or repeat names. +/// Messages are left out: "index must be ≥ 0" can be translated as "index must not be negative". +#[test] +fn numbered_rows_keep_their_number() { + let mut bad = Vec::new(); + for l in LANGUAGES.iter().filter(|l| !l.source.is_empty()) { + let (entries, _) = parse_entries(l.source); + for (_, src, tr) in entries.into_iter().filter(|(ctx, _, _)| ctx.is_empty()) { + let Some((_, n)) = src.rsplit_once(' ').filter(|(_, n)| !n.is_empty() && n.chars().all(|c| c.is_ascii_digit())) else { + continue; + }; + if !tr.split(|c: char| !c.is_ascii_digit()).any(|run| run == n) { + bad.push(format!("{}: {src:?} → {tr:?}", l.code)); + } + } + } + assert!(bad.is_empty(), "numbered rows without their number:\n{}", bad.join("\n")); +} + /// No translated word mixes Latin, Cyrillic and Greek letters, such as a Latin "A" typed in place /// of a Cyrillic "А". A word written in one script, such as "PDF" or "X" in a Russian row, is /// allowed. @@ -1783,6 +1998,26 @@ fn menu_items_side_by_side_have_different_labels() { assert!(same.is_empty(), "{} pairs of menu items look alike:\n{}", same.len(), same.join("\n")); } +/// Whether a menu label shows an id: a dotted command id, inside backticks or outside them, or +/// `key`, the command or effect id of its item, on its own. +fn label_shows_an_id(label: &str, key: &str) -> bool { + let plain = label.replace('`', " "); + !command_ids(&plain).is_empty() || plain.trim() == key +} + +#[test] +fn label_shows_an_id_finds_ids_in_backticks_and_bare_keys() { + let key = "type.convertListToText"; + assert!(label_shows_an_id("type.convertListToText", key)); + assert!(label_shows_an_id("`type.convertListToText`", key)); + assert!(label_shows_an_id("`type.convertListToText", key)); + assert!(label_shows_an_id("Convert (`slice.list`)", key)); + assert!(label_shows_an_id("roughen", "roughen")); + assert!(label_shows_an_id("`roughen`", "roughen")); + assert!(!label_shows_an_id("Convert to Text", key)); + assert!(!label_shows_an_id("Roughen…", "roughen")); +} + /// Menu items show words, never the command or effect id their catalog row is keyed by. #[test] fn menu_items_never_show_an_id() { @@ -1791,7 +2026,7 @@ fn menu_items_never_show_an_id() { if let crate::menus::Item::Cmd(l, id, p) = item { let key = menu_item_effect(id, p).unwrap_or(id); let shown = shown_menu_label(lang, item).unwrap_or_default(); - if !command_ids(shown).is_empty() && command_ids(l).is_empty() { + if label_shows_an_id(shown, key) && !label_shows_an_id(l, key) { out.push(format!("{}: {l:?} ({key}) shows {shown:?}", lang.0.code)); } } @@ -2040,6 +2275,17 @@ fn georgian_rows_have_no_mtavruli() { assert!(caps.is_empty(), "Mtavruli in ka.tsv: {caps:?}"); } +/// A field label's colon follows the catalog's ":" row: French puts a no-break space before it, +/// Chinese and Japanese write a full-width colon, and English and German write a plain colon. +#[test] +fn label_colons_follow_the_language() { + for (code, want) in [("fr", "X\u{a0}:"), ("zh-hans", "X:"), ("zh-hant", "X:"), ("ja", "X:"), ("de", "X:"), ("en", "X:")] { + set_current(Lang::from_code(code).expect("registered")); + assert_eq!(colon("X"), want, "{code}"); + } + set_current(Lang::EN); +} + /// French rows follow the typography fr.tsv's header sets: a no-break space before : ; ? ! and inside /// « », and the typographic apostrophe ’ in elisions. Text in backticks is code and is not checked, and /// a straight apostrophe inside double quotes is a literal value. @@ -2347,6 +2593,68 @@ fn recolor_notes_on_objects_left_unchanged_translate_with_their_counts() { } } +/// The errors a script's `File` and `Folder` objects and file dialogs give, and those of the +/// commands that answer the dialogs and keep their permissions, have a translated row in every +/// complete-message language. Each one in the first list is still a message the source gives; the +/// second list holds the note the file dialog shows when it left out picked files, and texts a +/// script reads only from a File or Folder object's `error`. +#[test] +fn script_file_messages_translate_in_every_complete_message_language() { + const SCANNED: &[&str] = &[ + "Script file access denied", + "Script file access denied: {path}", + "Script file access is unavailable on the web", + "Script file access to the app's own folders is not allowed", + "Script file cannot be decoded", + "Script file cannot encode the text", + "Script file could not be read", + "Script file could not be written", + "Script file dialogs need a person to answer them", + "Script file does not exist", + "Script file exceeds 8 MiB", + "Script file is not a regular file", + "Script file is not open", + "Script file is not open for writing", + "Script file name is already in use", + "Script file name must be a name without a folder", + "Script file path exceeds 32,767 characters", + "Script file permission can be kept only for a script run from a file", + "Script file permission could not be saved", + "Script files cannot be opened in another application", + "Script folder has more than 2,048 entries", + "Script folder mask takes too many steps to match", + "{name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code", + "the script opened more file data than one run may open (32 MiB)", + "the script wrote more file data than one run may write (32 MiB)", + "`answer` for a script's file dialog must be one of: once, always, deny, stop", + "choose a file or folder first, or deny", + "the script file permissions could not be saved: {e}", + "this script's file access can be allowed only once", + "Only the person at the keyboard can allow a script's file access", + ]; + const ERROR_ONLY: &[&str] = &[ + "A script is given at most 2,048 files: the files picked after them were left out", + "Script file open mode must be r, w, e or a", + "Script has 256 files open", + "Script folder is not empty", + "Script files cannot make aliases", + "Script file hidden setting cannot be changed", + ]; + let messages = message_literals(); + let gone: Vec<&&str> = SCANNED.iter().filter(|m| !messages.contains(**m)).collect(); + assert!(gone.is_empty(), "no longer messages in the source: {gone:?}"); + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + let (entries, _) = parse_entries(lang.0.source); + for m in SCANNED.iter().chain(ERROR_ONLY) { + let row = entries.iter().find(|(ctx, src, _)| ctx == "@msg" && src == m); + assert!(row.is_some_and(|(_, src, tr)| tr != src), "{code}: no translated row for {m:?}"); + } + } + let de = Lang::from_code("de").expect("de registered"); + assert_eq!(message(de, "Script file access denied: C:/x/a.txt"), "Dateizugriff des Skripts verweigert: C:/x/a.txt"); +} + /// The error that `text.setFormat` and the paragraph style commands give when a justification /// setting's Minimum, Desired and Maximum are out of order is translated in every /// complete-message language, with the setting's name kept. @@ -2517,6 +2825,70 @@ fn file_info_control_character_refusals_translate_in_every_complete_catalog() { } } +/// The warning about an SVG's variables that aren't text shows each kind VectorCraft names in the +/// interface language and each `trait` the file names, in backticks, as the warning writes it, the +/// entries in their order with their counts and joined as the language joins a list, in every +/// complete-message language. +#[test] +fn svg_variable_kinds_left_out_translate_in_every_complete_catalog() { + const KINDS: [&str; 4] = ["Visibility", "Linked File", "Graph Data", "Unknown"]; + let warning = |kinds: &str| format!("variables that aren't text were left out: {kinds}"); + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + let cat = lang.catalog(); + for ctx in ["variable-list-two", "variable-list-middle", "variable-list-end"] { + assert!(cat.contextual(ctx, "{0}, {1}").is_some(), "{code} has no {ctx} row"); + } + let kind = |k: &str| cat.contextual("variable-kind", k).unwrap_or_else(|| panic!("{code} has no variable-kind row for {k}")); + let template = message(lang, &warning("{kinds}")); + assert!(template.contains("{kinds}"), "{code}: {template}"); + let shown_with = |list: &str| template.replace("{kinds}", list); + let join = |ctx: &str, a: &str, b: &str| cat.contextual(ctx, "{0}, {1}").unwrap_or("{0}, {1}").replace("{0}", a).replace("{1}", b); + for k in KINDS { + // One kind, with its count. + let shown = message(lang, &warning(&format!("{k} (3)"))); + assert_eq!(shown, shown_with(&format!("{} (3)", kind(k))), "{code}"); + assert_ne!(kind(k), k, "{code}: {k} stays English"); + } + // Two entries, one a `trait` that holds a backtick, a list separator and a count. + let shown = message(lang, &warning("Unknown (1), `a``b (1), c` (2)")); + assert_eq!(shown, shown_with(&join("variable-list-two", &format!("{} (1)", kind("Unknown")), "`a``b (1), c` (2)")), "{code}"); + // Every kind, in the engine's order and in reverse, then a `trait` that is a kind's name. + for kinds in [KINDS.to_vec(), KINDS.iter().rev().copied().collect()] { + let list = kinds.iter().enumerate().map(|(i, k)| format!("{k} ({})", i + 1)).collect::>().join(", "); + let shown = message(lang, &warning(&format!("{list}, `Visibility` (12)"))); + let entries: Vec = + kinds.iter().enumerate().map(|(i, k)| format!("{} ({})", kind(k), i + 1)).chain(["`Visibility` (12)".to_string()]).collect(); + let head = entries[1..entries.len() - 1].iter().fold(entries[0].clone(), |acc, e| join("variable-list-middle", &acc, e)); + assert_eq!(shown, shown_with(&join("variable-list-end", &head, &entries[entries.len() - 1])), "{code}"); + } + } + let de = Lang::from_code("de").expect("registered"); + assert_eq!( + message(de, &warning("Visibility (2), Linked File (1), Graph Data (4), Unknown (1)")), + "die Variablen, die kein Text sind, wurden ausgelassen: Sichtbarkeit (2), Verknüpfte Datei (1), Diagrammdaten (4) und Unbekannt (1)" + ); + assert_eq!( + message(de, &warning("Unknown (1), `a``b (1), c` (2)")), + "die Variablen, die kein Text sind, wurden ausgelassen: Unbekannt (1) und `a``b (1), c` (2)" + ); + assert_eq!(message(de, &warning("`Visibility` (1)")), "die Variablen, die kein Text sind, wurden ausgelassen: `Visibility` (1)"); + let fr = Lang::from_code("fr").expect("registered"); + assert_eq!(message(fr, &warning("Visibility (1)")), "les variables qui ne sont pas du texte ont été ignorées\u{a0}: Visibilité (1)"); + let ja = Lang::from_code("ja").expect("registered"); + assert_eq!( + message(ja, &warning("Visibility (1), Linked File (2), Unknown (1)")), + "テキスト以外の変数は除外されました: 表示状態 (1)、リンクファイル (2)、不明 (1)" + ); + // A list not in the warning's form, and a `trait` whose backticks don't close, stay as written. + for kinds in ["fileref (1)", "`abc (1)", "Visibility (x)", "Visibility (1),Linked File (2)"] { + assert_eq!(message(de, &warning(kinds)), format!("die Variablen, die kein Text sind, wurden ausgelassen: {kinds}")); + } + // English shows the warning as the engine wrote it. + let english = warning("Visibility (2), `a``b (1), c` (1)"); + assert_eq!(message(Lang::EN, &english), english); +} + /// Every complete-message catalog has a row for each error that `type.compositeFonts.set`, /// `.export` and `.import`, the composite font checks behind them and the Composite Fonts dialog /// give, and translates them with the font name, the key and the class key kept, and the reason @@ -2524,7 +2896,7 @@ fn file_info_control_character_refusals_translate_in_every_complete_catalog() { #[test] fn composite_font_errors_translate_in_complete_languages() { const SOURCES: &[&str] = &[ - "each font must be {name, parts}", + "each font must be {{name, parts}}", "unknown key `{k}`; a font takes name and parts", "each font needs a name", "`{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters)", @@ -2537,7 +2909,7 @@ fn composite_font_errors_translate_in_complete_languages() { "two composite fonts are named `{_1}`", "`{_1}` is the name of an installed font", "`{_1}`: {_2} is set in `{font}`, a composite font", - "give fonts: [{name, parts}…]", + "give fonts: [{{name, parts}}…]", "path is empty", "fonts must be a list of composite fonts", "names must be strings", @@ -2926,6 +3298,53 @@ fn literal_brace_rows_match_only_their_message() { assert_eq!(message(de(), "plug-in output: expected value at line 1 column 1"), "Plug-in-Ausgabe: expected value at line 1 column 1"); } +/// Every complete-message catalog translates the messages that print braces as text through an +/// exact row with doubled braces, keeps each literal example whole, and has no row with a +/// placeholder in their place: such a row also translates other text with the same start and end. +#[test] +fn literal_brace_messages_have_exact_rows_in_complete_languages() { + // A row's source, the message as shown, and the text its translation keeps. + let cases: &[(&str, &str, &[&str])] = &[ + ("each font must be {{name, parts}}", "each font must be {name, parts}", &["{name, parts}"]), + ("give fonts: [{{name, parts}}…]", "give fonts: [{name, parts}…]", &["fonts", "[{name, parts}…]"]), + ( + r#"`scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}}"#, + r#"`scope` must be "document", {artboards: [index, …]} or {layers: [id, …]}"#, + &["`scope`", r#""document""#, "{artboards: [index, …]}", "{layers: [id, …]}"], + ), + ("numbers out of order in {{}} quantifier", "numbers out of order in {} quantifier", &["{}"]), + ( + r#"the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}})"#, + r#"the paint is not a freeform gradient (apply one with paint.editGradient {kind: "freeform"})"#, + &["paint.editGradient", r#"{kind: "freeform"}"#], + ), + ]; + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + let (entries, _) = parse_entries(lang.0.source); + let rows: Vec<(&str, &str)> = entries.iter().filter(|(ctx, _, _)| ctx == "@msg").map(|(_, src, tr)| (src.as_str(), tr.as_str())).collect(); + for (source, shown, kept) in cases { + let Some((_, tr)) = rows.iter().find(|(src, _)| src == source) else { panic!("{code} has no row for {source:?}") }; + let out = message(lang, shown); + assert_eq!(out, fill_once(tr, &[]), "{code}: {shown}"); + assert_ne!(out, *shown, "{code} leaves {shown:?} in English"); + for k in *kept { + assert!(out.contains(k), "{code}: {k} in {out}"); + } + // The text before the first brace and after the last one, which an older row with a + // placeholder in place of the braced example also starts and ends with. + let head = source.find('{').map_or("", |at| &source[..at]); + let tail = source.rfind('}').map_or("", |at| &source[at + 1..]); + let broad: Vec<&str> = rows + .iter() + .map(|(src, _)| *src) + .filter(|src| src != source && src.contains('{') && src.starts_with(head) && src.ends_with(tail)) + .collect(); + assert!(broad.is_empty(), "{code} keeps placeholder rows in place of {source:?}: {broad:?}"); + } + } +} + /// `plugin.run` of an importer, an exporter or a live effect names the command that runs it with /// the JSON that picks it, and every complete-message catalog translates that error with the /// plug-in's id and the JSON kept. @@ -3143,9 +3562,9 @@ fn three_d_refusals_are_translated_in_every_complete_catalog() { assert!(missing.is_empty(), "{} 3D messages have no @msg row:\n{}", missing.len(), missing.join("\n")); } -/// The Eraser's range refusals (`path.eraseRegion` `angle` and `roundness`) and the Scissors' (`path.split` -/// `t`) show in every complete-message language with the key and the range numbers as given; the -/// error the command returns stays English. +/// The Eraser's range refusals (`path.eraseRegion` `angle` and `roundness`), the Path Eraser's +/// (`path.eraseSegments` `width`) and the Scissors' (`path.split` `t`) show in every complete-message +/// language with the key and the range numbers as given; the error the command returns stays English. #[test] fn eraser_and_scissors_range_refusals_translate_with_their_values() { use serde_json::json; @@ -3155,6 +3574,7 @@ fn eraser_and_scissors_range_refusals_translate_with_their_values() { let refusals = [ ("path.eraseRegion", json!({"points": [[10, 10], [60, 10]], "angle": 200}), "`angle`", ["-180", "180"]), ("path.eraseRegion", json!({"points": [[10, 10], [60, 10]], "roundness": 0}), "`roundness`", ["1", "100"]), + ("path.eraseSegments", json!({"points": [[30, 0], [30, 70]], "width": 2000}), "`width`", ["0.001", "1000"]), ("path.split", json!({"id": id, "segment": 0, "t": 1.5}), "`t`", ["0", "1"]), ]; for (cmd, p, key, numbers) in &refusals { @@ -3200,9 +3620,9 @@ fn three_d_refusals_translate_with_their_values() { vec!["0", "100"], ), ( - refuse(vectorcraft_effects::validate_three_d(&rect, EXTRUDE, &json!({"graphics": [{"symbol": "S", "face": "side"}]}))), - "must be front or back", - vec!["`graphics`", "front", "back"], + refuse(vectorcraft_effects::validate_three_d(&rect, EXTRUDE, &json!({"graphics": [{"symbol": "S", "face": "top"}]}))), + "must be front, back or side", + vec!["`graphics`", "front", "back", "side"], ), (refuse(vectorcraft_effects::validate_three_d(&rect, CLASSIC_EXTRUDE, &json!({"depth": "deep"}))), "must be a number", vec!["`depth`"]), (refuse(vectorcraft_effects::validate_three_d(&instance, EXTRUDE, &json!({}))), "the symbol's art isn't available", vec!["Mine 7"]), @@ -3441,23 +3861,42 @@ const COUNTED_STATUS_MESSAGES: &[(&str, &str)] = &[ ("Downloaded 1 file", "Downloaded 2 files"), ("Exported 1 file to /out", "Exported 2 files to /out"), ("Loaded “Tidy”: 1 step was left out", "Loaded “Tidy”: 2 steps were left out"), + ("Copied with 1 note: a note", "Copied with 2 notes: a note"), + ("Cut with 1 note: a note", "Cut with 2 notes: a note"), + ("Traced with 1 note: a note", "Traced with 2 notes: a note"), ( "Loaded “Tidy”: 1 step has an unknown command and was kept: “Export”, step 4, `example.finish`", "Loaded “Tidy”: 2 steps have unknown commands and were kept; the first: “Export”, step 4.2, `example.finish`", ), ]; -/// The link, font, export and action set status messages name a count of 1 in the singular and other counts in -/// the plural, and every complete catalog translates both, in the form its plural rule picks. +/// The link, font, export, action set, clipboard and Image Trace status messages name a count of 1 in the singular +/// and other counts in the plural, and every complete catalog translates both, in the form its plural rule picks. #[test] fn counted_status_messages_take_the_plural_form() { use crate::panels::links::{relinked_status, updated_status}; + use crate::sysclip::copied_with_notes; + use crate::trace_runs::traced_with_notes; assert_eq!((relinked_status(1), relinked_status(2)), ("Relinked 1 image".to_string(), "Relinked 2 images".to_string())); assert_eq!((updated_status(1), updated_status(2)), ("Updated 1 image".to_string(), "Updated 2 images".to_string())); assert_eq!(crate::dialogs::missing_links::changed_on_disk_status(1), COUNTED_STATUS_MESSAGES[2].0); assert_eq!(crate::dialogs::missing_links::changed_on_disk_status(2), COUNTED_STATUS_MESSAGES[2].1); assert_eq!(crate::io::exported_with_notes("/out/a.svg", 1, "a note"), COUNTED_STATUS_MESSAGES[4].0); assert_eq!(crate::io::exported_with_notes("/out/a.svg", 2, "a note"), COUNTED_STATUS_MESSAGES[4].1); + // Each pair is found in the list by its text. + let listed = |got: (String, String), want: (&str, &str)| { + assert_eq!((got.0.as_str(), got.1.as_str()), want); + assert!(COUNTED_STATUS_MESSAGES.contains(&want), "{want:?} is not in COUNTED_STATUS_MESSAGES"); + }; + let copied = (copied_with_notes(false, 1, "a note"), copied_with_notes(false, 2, "a note")); + listed(copied, ("Copied with 1 note: a note", "Copied with 2 notes: a note")); + let cut = (copied_with_notes(true, 1, "a note"), copied_with_notes(true, 2, "a note")); + listed(cut, ("Cut with 1 note: a note", "Cut with 2 notes: a note")); + let traced = (traced_with_notes(1, "a note"), traced_with_notes(2, "a note")); + listed(traced, ("Traced with 1 note: a note", "Traced with 2 notes: a note")); + // A note that holds placeholder text is not filled in again. + assert_eq!(copied_with_notes(true, 3, "{n} {first}"), "Cut with 3 notes: {n} {first}"); + assert_eq!(message(de(), &traced_with_notes(2, "{n}")), "Mit 2 Hinweisen nachgezeichnet: {n}"); // A value that holds placeholder text is not filled in again. assert_eq!(crate::io::exported_with_notes("/out/{first}.svg", 1, "{n}"), "Exported /out/{first}.svg with 1 note: {n}"); for code in COMPLETE_MESSAGES { @@ -3672,6 +4111,21 @@ fn run() -> Result<()> { assert!(source_messages(code, &[], &Default::default()).is_empty()); } +/// A message split over lines with a `\` at the end of a line is read as Rust reads it: the line +/// break and the next line's leading whitespace are dropped, with LF and CRLF line endings, in a +/// constant and in a literal an error takes. +#[test] +fn message_scan_joins_a_literal_continued_on_the_next_line() { + for eol in ["\n", "\r\n"] { + let declared = format!("const LONG: &str = \"too many elements: \\{eol} drawn as a plain group\";{eol}"); + let consts = std::collections::BTreeMap::from_iter(str_consts(&declared).into_iter().map(|(name, value)| (name, vec![value]))); + assert_eq!(consts.get("LONG"), Some(&vec!["too many elements: drawn as a plain group".to_string()]), "{eol:?}"); + let code = format!("fn run() {{ let _ = Err(\"the file \\{eol}\t\t is too large\"); let _ = Err(LONG); }}{eol}"); + let found: std::collections::BTreeSet = source_messages(&code, &[], &consts).into_iter().collect(); + assert_eq!(found.iter().collect::>(), ["the file is too large", "too many elements: drawn as a plain group"], "{eol:?}"); + } +} + /// The scan reads the message of each of the plug-in host's [`ERROR_HELPERS`]: a literal, a /// `format!` string with or without a `&` before it, after the location of `out_err` (a /// `format!` string too), the number and range of `in_range`, the number and location of `unit`, @@ -4010,6 +4464,23 @@ fn selected_path_reason_is_translated() { } } +/// The error of a played action step is translated in every language of [`COMPLETE_MESSAGES`], with +/// its reason; the step's number and command id stay as they are. +#[test] +fn action_step_errors_are_translated() { + let template = "action step {_1} (`{id}`) failed: {reason}"; + assert!(message_literals().contains(template)); + let reason = "select a path"; + let error = format!("action step 4 (`path.reverse`) failed: {reason}"); + assert_eq!(message(Lang::EN, &error), error); + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + let shown = message(lang, &error); + assert!(!shown.starts_with("action step") && shown.contains('4') && shown.contains("`path.reverse`"), "{code}: {shown}"); + assert!(shown.contains(&message(lang, reason)) && !shown.contains(reason), "{code}: {shown}"); + } +} + /// The refusals of a linked JavaScript file or a library's file outside the read roots, of a file /// name that fits more than one linked JavaScript file, and of an appearance edit of the art a /// graph design draws in a graph series have translated rows in languages that translate every @@ -4070,8 +4541,8 @@ fn script_errors_are_translated() { "Script file could not be read", "Script folder has more than 2,048 entries", "Script file open mode must be r, w, e or a", - "Script file writing is not available", - "Script file dialogs are not available", + "Script file is not open for writing", + "Script file dialogs need a person to answer them", "Script files cannot be opened in another application", "Script file access is unavailable on the web", "Script has 256 files open", @@ -4681,6 +5152,55 @@ fn dataset_import_repeated_column_error_is_translated() { } } +/// The errors of Automatic Plane Positioning (`perspective.plane.infer`) and of its two options +/// (`perspective.widget.options`) have their own row in every language that translates every +/// message, and the status bar shows them translated with the parameter names kept. +#[test] +fn automatic_plane_positioning_errors_are_translated() { + use serde_json::json; + use vectorcraft_engine::{EngineError, Session}; + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let mut errors = vec![]; + for (cmd, p, want, kept) in [ + ("perspective.plane.infer", json!({"at": [0, 0], "tolerance": -1}), "tolerance must be 0 or more", &["tolerance"][..]), + ("perspective.plane.infer", json!({"at": [0, 0], "clear": true}), "give `at` or `clear`, not both", &["`at`", "`clear`"][..]), + ("perspective.widget.options", json!({"anchorPoint": "yes"}), "anchorPoint must be true or false", &["anchorPoint"][..]), + ( + "perspective.widget.options", + json!({"gridlineIntersection": 1}), + "gridlineIntersection must be true or false", + &["gridlineIntersection"][..], + ), + ] { + let e = s.execute(cmd, &p).unwrap_err(); + assert!(matches!(&e, EngineError::BadParams { msg, .. } if msg == want), "{cmd} {p}: {e}"); + errors.push((e.to_string(), want, kept)); + } + s.execute("perspective.grid.show", &json!({"visible": false})).unwrap(); + let hidden = "the perspective grid is hidden"; + let e = s.execute("perspective.plane.infer", &json!({"at": [0, 0]})).unwrap_err(); + assert!(matches!(&e, EngineError::Other(msg) if msg == hidden), "{e}"); + errors.push((e.to_string(), hidden, &[][..])); + s.execute("perspective.grid.show", &json!({"visible": true})).unwrap(); + s.execute("perspective.plane.set", &json!({"plane": "ground"})).unwrap(); + s.execute("perspective.widget.options", &json!({"anchorPoint": false, "gridlineIntersection": false})).unwrap(); + let off = "Automatic Plane Positioning is off: turn on anchorPoint or gridlineIntersection (perspective.widget.options)"; + let e = s.execute("perspective.plane.infer", &json!({"at": [0, 0]})).unwrap_err(); + assert!(matches!(&e, EngineError::Other(msg) if msg == off), "{e}"); + errors.push((e.to_string(), off, &["anchorPoint", "gridlineIntersection", "(perspective.widget.options)"][..])); + let literals = message_literals(); + for (e, want, kept) in &errors { + assert!(literals.contains(*want), "{want}"); + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + assert!(lang.catalog().exact_message(want).is_some(), "{code} has no row for {want}"); + let shown = message(lang, e); + assert!(!shown.contains(want) && kept.iter().all(|k| shown.contains(k)), "{code}: {shown}"); + } + } +} + /// The scan reads the refusals `script.run`'s `param(msg)` gives, and not the arguments of a type's /// own function of that name. #[test] @@ -4771,6 +5291,85 @@ fn script_answers_errors_are_translated() { } } +/// `script.run`'s other refusals of its parameters (`maxFuel`, `args`, `path`, `source`, +/// `installed`, `name`) and its errors for a script it cannot read are translated in every language +/// that translates every message, with the code names, the place in `args`, the file suffixes, the +/// limits and the file's path kept. The command's error stays in English. +#[test] +fn script_run_param_errors_are_translated() { + use serde_json::{Value, json}; + use vectorcraft_engine::{EngineError, Session}; + let refusals = [ + "`maxFuel` must be a whole number from 1 to {_1}", + "`args{place}` is nested more than 64 levels deep", + "`args` must be an object", + "`args` is larger than 1 MiB", + "`path` is empty", + "`installed` takes a `path`, not a `source`", + "`path` must name a .js or .jsx file", + "give exactly one of `path` and `source`", + ]; + let scanned = message_literals(); + for template in refusals { + assert!(scanned.contains(template), "{template}"); + } + let dir = vectorcraft_testkit::TempDir::new("i18n-script-run-params"); + let not_text = dir.join("not-text.js"); + std::fs::write(¬_text, [0x66, 0xff, 0xfe]).expect("write"); + let folder = dir.join("folder.js"); + std::fs::create_dir(&folder).expect("folder"); + let (not_text, folder) = (not_text.to_string_lossy().into_owned(), folder.to_string_lossy().into_owned()); + let mut deep = json!(1); + for _ in 0..70 { + deep = json!([deep]); + } + let fuel = vectorcraft_engine::script::MAX_FUEL; + // Each call, with the English message its parameter refusal gives, or `None` for an error that + // is not one. + let bad: Vec<(Value, Option)> = vec![ + (json!({"source": "1", "maxFuel": 0}), Some(format!("`maxFuel` must be a whole number from 1 to {fuel}"))), + (json!({"source": "1", "maxFuel": fuel + 1}), Some(format!("`maxFuel` must be a whole number from 1 to {fuel}"))), + (json!({"source": "1", "args": {"a": deep}}), Some(format!("`args.a{}` is nested more than 64 levels deep", "[0]".repeat(64)))), + (json!({"source": "1", "args": [1]}), Some("`args` must be an object".into())), + (json!({"source": "1", "args": {"x": "x".repeat(1 << 20)}}), Some("`args` is larger than 1 MiB".into())), + (json!({"path": ""}), Some("`path` is empty".into())), + (json!({"source": "1", "installed": true}), Some("`installed` takes a `path`, not a `source`".into())), + (json!({"path": "notes.txt"}), Some("`path` must name a .js or .jsx file".into())), + (json!({}), Some("give exactly one of `path` and `source`".into())), + (json!({"path": "a.js", "source": "1"}), Some("give exactly one of `path` and `source`".into())), + (json!({"path": 1}), Some("`path` must be a string".into())), + (json!({"source": "1", "name": false}), Some("`name` must be a string".into())), + (json!({"source": "1", "installed": "yes"}), Some("`installed` must be true or false".into())), + (json!({"path": "built.jsxbin"}), None), + (json!({"source": "x".repeat(vectorcraft_engine::script::MAX_SOURCE_BYTES + 1)}), None), + (json!({"path": "listed.js", "installed": true}), None), + (json!({"path": not_text}), None), + (json!({"path": folder}), None), + ]; + let mut s = Session::new(); + for (params, want) in bad { + let e = s.execute("script.run", ¶ms).unwrap_err(); + let line = e.to_string(); + let inner = match (&e, &want) { + (EngineError::BadParams { cmd, msg }, Some(want)) if cmd == "script.run" && msg == want => want.clone(), + (EngineError::Other(msg), None) => msg.clone(), + _ => panic!("{params:.80}: {e}"), + }; + // The code names and the place in `args`, the numbers, the file suffixes and the path. + let mut kept: Vec<&str> = inner.split('`').skip(1).step_by(2).collect(); + kept.extend(inner.split(|c: char| !c.is_ascii_digit()).filter(|n| !n.is_empty())); + kept.extend([".jsx", ".js", not_text.as_str(), folder.as_str()].into_iter().filter(|k| inner.contains(*k))); + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + let shown = message(lang, &line); + let translated = message(lang, &inner); + assert_ne!(translated, inner, "{code}"); + assert!(shown.contains(&translated) && !shown.contains("invalid parameters"), "{code}: {shown}"); + assert!(kept.iter().all(|k| shown.contains(k)), "{code}: {shown}"); + } + } +} + /// The errors of a command's parameter schema are translated in every language that translates /// every message, with the parameter's path and the refused value kept. #[test] @@ -5017,6 +5616,27 @@ fn pdfx_bleed_warning_is_translated() { } } +/// The Shape Mode commands' warning for a selected line that encloses no area, which the status bar +/// shows and the message scan doesn't read, and Intersect's error when such a line leaves nothing, +/// are translated in each language of [`COMPLETE_MESSAGES`]. +#[test] +fn shape_mode_open_path_warning_is_translated() { + let warning = vectorcraft_engine::cmd::SHAPE_MODE_OPEN_PATH_NO_AREA; + let mut s = vectorcraft_engine::Session::new(); + let run = |s: &mut vectorcraft_engine::Session, id: &str, p: serde_json::Value| s.execute(id, &p); + run(&mut s, "file.new", serde_json::json!({"width": 200, "height": 200})).unwrap(); + let square = run(&mut s, "shape.rectangle", serde_json::json!({"x": 0, "y": 0, "width": 100, "height": 100})).unwrap()["id"].clone(); + let line = run(&mut s, "shape.line", serde_json::json!({"x1": 20, "y1": 50, "x2": 80, "y2": 50})).unwrap()["id"].clone(); + run(&mut s, "select.set", serde_json::json!({"ids": [square, line]})).unwrap(); + let error = run(&mut s, "object.pathfinder.intersect", serde_json::json!({})).unwrap_err().to_string(); + assert!(error.contains("Outline Stroke"), "{error}"); + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + assert_ne!(message(lang, warning), warning, "{code}"); + assert!(!message(lang, &error).contains("encloses no area"), "{code}: {error}"); + } +} + /// The errors of saving, renaming and deleting a tracing preset are translated in every language /// that translates every message. #[test] @@ -5442,9 +6062,9 @@ const NAMED_KEYS: &[(&str, &[&str])] = &[ ("dataBase64 is not base64", &["dataBase64"]), ("decimals must be {_1}–{_2} (got {_3})", &["decimals"]), ("detect must be true or false", &["detect"]), - ("each font must be {name, parts}", &["name", "parts"]), + ("each font must be {{name, parts}}", &["name", "parts"]), ("fonts must be a list of composite fonts", &["fonts"]), - ("give fonts: [{name, parts}…]", &["fonts", "name", "parts"]), + ("give fonts: [{{name, parts}}…]", &["fonts", "name", "parts"]), ("give one of path, data or dataBase64", &["path", "data", "dataBase64"]), ("give origin: [x, y], or reset: true", &["origin", "reset"]), ("global must be true or false", &["global"]), @@ -5501,7 +6121,7 @@ const NAMED_KEYS: &[(&str, &[&str])] = &[ ("`dither` applies to gradient fills (stroke: false)", &["stroke"]), ("`strokeMode` applies to strokes (stroke: true)", &["stroke"]), ("`{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}`", &["symbol", "face", "x", "y", "scale", "rotation"]), - ("`{GRAPHICS}` face must be front or back", &["face", "front", "back"]), + ("`{GRAPHICS}` face must be front, back or side", &["face", "front", "back", "side"]), ("`{name}`: give the kanji part", &["kanji"]), ("`{name}`: parts must be an object", &["parts"]), ( @@ -5707,7 +6327,8 @@ const MESSAGE_MARKERS: &[&str] = &[".status(", "ui.status = ", "status = ", "Oth /// a plug-in returned), and the script interpreter's methods that throw an error at a script: /// `.type_error(msg)`, `.throw(kind, msg)` and the XPath evaluator's `.error(msg)`, with the reasons /// it gives for a property it cannot define or assign (`.reject_bool(throw, key, why)` and -/// `.reject(throw, key, why)`). A helper that starts with `.` is a method of any receiver; any other +/// `.reject(throw, key, why)`), and the interface's `unavailable(tool, reason)` (a tool's place that +/// no toolbar can show, which Help puts in the status bar). A helper that starts with `.` is a method of any receiver; any other /// is a function, not a type's own function of the same name (`Grays::param(C, p)`). const ERROR_HELPERS: &[(&str, &str, usize)] = &[ ("engine", "bad(", 1), @@ -5730,6 +6351,7 @@ const ERROR_HELPERS: &[(&str, &str, usize)] = &[ ("js", ".error(", 0), ("js", ".reject_bool(", 2), ("js", ".reject(", 2), + ("ui-egui", "unavailable(", 1), ]; /// Error variants whose first argument is a name, not a message: a command id @@ -6182,7 +6804,8 @@ fn without_test_module(text: &str) -> &str { text } -/// The text of a string literal whose opening quote was just read, escapes resolved. +/// The text of a string literal whose opening quote was just read, escapes resolved. A `\` at the +/// end of a line drops the line break and the whitespace that starts the next line, as Rust does. fn string_literal(s: &str) -> Option { let mut out = String::new(); let mut it = s.chars(); @@ -6192,6 +6815,7 @@ fn string_literal(s: &str) -> Option { '\\' => match it.next()? { 'n' => out.push('\n'), 't' => out.push('\t'), + '\n' | '\r' => it = it.as_str().trim_start_matches([' ', '\t', '\n', '\r']).chars(), c => out.push(c), }, c => out.push(c), @@ -6291,6 +6915,20 @@ fn pl() -> Lang { Lang::from_code("pl").expect("pl registered") } +/// Polish translates the dimension commands' errors. +#[test] +fn polish_translates_dimension_messages() { + for english in [ + "Choose original artwork, not a dimension's generated paths", + "Dimension is locked or hidden", + "Dimension mode does not match its source", + "Invalid dimension offset", + "Invalid point", + ] { + assert_ne!(message(pl(), english), english); + } +} + #[test] fn polish_plurals_have_three_forms() { let forms: Vec = [0, 1, 2, 4, 5, 11, 12, 14, 21, 22, 25, 101, 112, 122].into_iter().map(plural_polish).collect(); @@ -6313,6 +6951,40 @@ fn polish_plurals_have_three_forms() { assert!(count >= 13, "Polish plural rows missing"); } +/// Every Polish row whose English names art or artwork calls it kompozycja, the catalog's term, and +/// never grafika (kept for what the English calls a graphic) or rysunek. An artboard's obszar +/// kompozycji does not count as the term. Line art, the art brush and its class, Art Ribbons, +/// Art & Illustration, Art Optimized and the literal values `art` and `artwork` are other terms. +#[test] +fn polish_rows_call_artwork_kompozycja() { + let (entries, _) = parse_entries(pl().0.source); + let mut wrong = Vec::new(); + for (_, src, translation) in &entries { + let english = src.to_lowercase(); + let words: Vec<&str> = english.split(|c: char| !c.is_ascii_alphabetic()).collect(); + let names = |list: &[&str]| words.iter().any(|w| list.contains(w)); + let polish = translation.to_lowercase(); + let polish_words: Vec<&str> = polish.split(|c: char| !c.is_alphabetic()).filter(|w| !w.is_empty()).collect(); + let other_term = ["line art", "art brush", "art ribbons", "art & illustration", "art optimized"].iter().any(|t| english.contains(t)); + let literal = polish_words.iter().any(|w| ["art", "artwork"].contains(w)); + if !names(&["art", "artwork"]) || other_term || literal || english == "art" { + continue; + } + let term = polish_words.iter().enumerate().any(|(i, w)| w.starts_with("kompozyc") && !(i > 0 && polish_words[i - 1].starts_with("obszar"))); + let graphic = polish.contains("graf") && !names(&["graphic", "graphics"]); + if !term || graphic || polish.contains("rysun") { + wrong.push(format!("{src:?} -> {translation:?}")); + } + } + assert!(wrong.is_empty(), "{} Polish rows name artwork with another word:\n{}", wrong.len(), wrong.join("\n")); + assert_eq!(tr(pl(), "Artwork"), "Kompozycja"); + assert_eq!(tr(pl(), "Off-Artboard Art"), "Kompozycja poza obszarami kompozycji"); + assert_eq!(message(pl(), "select the art to export first"), "najpierw zaznacz kompozycję do eksportu"); + assert_eq!(message(pl(), "the selected art has no width"), "zaznaczona kompozycja nie ma szerokości"); + assert_eq!(tr(pl(), "Line Art and Text Resolution:"), "Rozdzielczość grafiki liniowej i tekstu:"); + assert_eq!(tr(pl(), "Art Brush"), "Pędzel artystyczny"); +} + /// Every catalog names each numeral system of Character panel menu › Digits, in the `digits` /// context (where the language's name would read wrong) or with its plain row (#4942). #[test] diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 910a7fc5b1..99be17c885 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -104,6 +104,7 @@ Add Anchor Point Bağlantı Noktası Ekle Add Anchor Point Tool Bağlantı Noktası Ekleme Aracı Add Anchor Points Bağlantı Noktaları Ekle + Add Around Nesnenin Etrafına Ekle Add Effect Efekt Ekle Add Freeform Line Serbest Biçimli Çizgi Ekle Add Freeform Point Serbest Biçim Noktası Ekle @@ -125,8 +126,12 @@ Add to Swatches Renk Örneklerine Ekle Add Used Colors Kullanılan Renkleri Ekle Additional Plug-ins Folder Ek Eklentiler Klasörü + Plug-in Instruction Budget Eklenti Talimat Bütçesi Additional Fonts Folder Ek Yazı Tipleri Klasörü Adjust Adjoining Width Points Bitişik Genişlik Noktalarını Ayarlayın + Incoming Gelen + Outgoing Giden + Single Width Only Yalnızca Tek Genişlik Adjust Color Balance… Renk Dengesini Ayarlayın… Adjust Colors Renkleri Ayarla Adjust Options: Seçenekleri Ayarlayın: @@ -181,6 +186,7 @@ Angle: Açı: Angles Açılar Animated Zoom Animasyonlu Yakınlaştırma + Anti Alias Kenar yumuşatma Anti-alias Kenar yumuşatma Anti-Alias Kenar Yumuşatma Anti-alias Rasters Kenar Yumuşatma Rasterleri @@ -345,6 +351,12 @@ font-technology Variable Değişken Brush Definition Fırça Tanımı Brush Libraries Fırça Kitaplıkları Brush Options… Fırça Seçenekleri… + Options of Selected Object… Seçili Nesnenin Seçenekleri… + Options of Selected Object Seçili Nesnenin Seçenekleri +@msg no path painted with a brush is selected fırçayla boyanmış yol seçilmedi +@msg the selected paths are painted with brushes of different types seçili yollar farklı türde fırçalarla boyanmış +@msg give `params` or `reset`, not both `params` veya `reset` verin, ikisini birden değil +@msg a bristle brush has no options of its own on a path kıl fırçanın bir yolda kendine ait seçenekleri yoktur Brush Strokes Fırça Darbeleri Brushes Fırçalar Built-in Libraries Yerleşik Kütüphaneler @@ -400,6 +412,12 @@ font-technology Variable Değişken Character Alignment Karakter Hizalaması Character / Paragraph Karakter / Paragraf Character Rotation Karakter Rotasyonu + Chinese Big 5 Çince Big 5 + Cyrillic Kiril + Greek Yunanca + Turkish Türkçe + Baltic Baltık + Central European Orta Avrupa Character Set: Karakter Seti: Character Style Karakter Stili Character Style Options Karakter Stili Seçenekleri @@ -461,6 +479,8 @@ font-technology Variable Değişken Choose a folder Bir klasör seçin Choose… Seç… Circle daire + Circle Tool Daire Aracı + Circle too large Daire çok büyük Classic Defaults Klasik Varsayılanlar Clean Up… Temizleme… Clear Temizle @@ -536,6 +556,7 @@ font-technology Variable Değişken Color Mixer (Shift-click the chip) Renk Karıştırıcı (Çipe Shift tuşuna basarak tıklayın) Color Mode Renk Modu Color Mode: Renk Modu: + Color Model Renk Modeli Color Model: Renk Modeli: Color Models Renkli Modeller Color Picker Renk Seçici @@ -555,12 +576,18 @@ font-technology Variable Değişken Saturation and brightness Doygunluk ve parlaklık Color field Renk seçim alanı {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Tekerlek Görünümü + Box View Kutu Görünümü + Box Channel Kutu Kanalı + Color box Renk kutusu + Color Wheel Options Renk Tekerleği Seçenekleri Color Type: Renk Türü: Color: Renk: Colorize Renklendir Colors Renkler Colors: Renkler: Column Graph Tool Sütun Grafiği Aracı + Columns Sütunlar Columns: Sütunlar: Column… Sütun… Combine Slices Dilimleri Birleştir @@ -769,6 +796,8 @@ font-technology Variable Değişken Delete Artboard Çalışma Yüzeyini Sil Delete Artboards Çalışma Yüzeylerini Sil Delete Brush Fırçayı Sil + Delete Color Rengi Sil + Restore Generated Table Oluşturulan Tabloyu Geri Yükle Delete Character Style Karakter Stilini Sil Delete Empty Artboards Boş Çalışma Yüzeylerini Sil Delete Freeform Point Serbest Biçim Noktasını Sil @@ -837,6 +866,7 @@ font-technology Variable Değişken Direct Selection Tool Doğrudan Seçim Aracı Direction Handles Yön Kolları Disable Auto Add/Delete Otomatik Ekleme/Silmeyi Devre Dışı Bırak + Interpolate Control Points When Moving Anchors Bağlantı Noktalarını Taşırken Yön Kollarını Enterpole Et Disable Opacity Mask Opaklık Maskesini Devre Dışı Bırak Discard At Discard Empty Type Boş Türü At @@ -1041,6 +1071,7 @@ font-technology Variable Değişken Enable text access for screen readers Ekran okuyucular için metin erişimini etkinleştirin Enable Touch Gestures Dokunma Hareketlerini Etkinleştir Switch Selection and Drawing Modes Seçim ve Çizim Modları Arasında Geçiş Yap + Select Last Selection Tool Son Kullanılan Seçim Aracını Seç Enable Touch Workspace Dokunmatik Çalışma Alanını Etkinleştir Encoding Kodlama Encoding: Kodlama: @@ -1217,6 +1248,8 @@ font-technology Variable Değişken Files Dosyalar Files of a PDF standard can't be password-protected. PDF standardının dosyaları parola korumalı olamaz. Files of this standard tag their colours with ICC profiles. Bu standardın dosyaları renklerini ICC profilleriyle etiketler. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Bu standardın dosyaları renklerini ICC profilleriyle etiketler, ancak çıkış amacı profilindeki CMYK renkleri DeviceCMYK olarak yazılır. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. “Profilleri ekleme” ve bir CMYK çıkış amacıyla, başka bir profilin CMYK hedefine dönüştürülmedikçe her CMYK rengi DeviceCMYK olarak yazılır. Fill Dolgu Fill & Stroke Doldur ve Konturla Fill (X), double-click for the Color Picker Doldur (X), Renk Seçici için çift tıklayın @@ -1254,6 +1287,8 @@ font-technology Variable Değişken Reset Tracking and Kerning Takip ve Karakter Aralığını Sıfırla Reset Horizontal Scale Yatay Ölçeği Sıfırla Highlight Font Name Yazı Tipi Adını Vurgula + Highlight Font Size Yazı Tipi Boyutunu Vurgula + Other… Diğer… Highlight Kerning Karakter Aralığını Vurgula Highlight Tracking Takibi Vurgula Spacing Aralık @@ -1851,6 +1886,7 @@ font-technology Variable Değişken Load SVG into Clipboard SVG'yi Panoya yükleyin Load Text into Clipboard Metni Panoya Yükle Local Libraries Yerel Kütüphaneler + Locate Layer Katmanı Bul Locate Object Nesneyi Bul Location Konum Location: Konum: @@ -2039,6 +2075,7 @@ font-technology Variable Değişken Scatter: Dağılım: Rotation: Rotasyon: Rotation relative to: Şuna göre rotasyon: + Hue Jitter: Renk tonu değişimi: Brush Scale Options Fırça Ölçeği Seçenekleri Scale Proportionately Orantılı Olarak Ölçeklendirin Stretch to Fit Stroke Length Kontur Uzunluğuna Sığacak Şekilde Esnetin @@ -2068,6 +2105,7 @@ font-technology Variable Değişken Tints and Shades Renk Tonları ve Gölgeler Hue Shift Ton Değiştirme Key Color: Anahtar Rengi: + Roundness Yuvarlaklık Roundness: Yuvarlaklık: Fixed Sabit Pressure Basınç @@ -2339,6 +2377,9 @@ shape Open Açık Overprint Üst Baskı Overprint and Transparency Flattener Üst Baskı ve Asetat Düzleştirici Overprint and Transparency Flattener Options Üst Baskı ve Asetat Düzleştirici Seçenekleri + Custom… Özel… + Custom Transparency Flattener Options Özel Şeffaflık Düzleştirici Seçenekleri + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS'de alfa şeffaflığı yoktur ve Üst baskılar, üst baskıların korunup korunmayacağını belirler. Overprint Black… Üst Baskı Siyah… Overprint Fill Üst Baskı Dolgusu Overprint Preview Üst Baskı Önizleme @@ -2388,6 +2429,11 @@ shape Open Açık Pathfinders: Yol Bulucular: Paths Yollar Path Length Yol Uzunluğu + Grid Size Izgara Boyutu + Grid Colors Izgara Renkleri + Flattener Preset Düzleştirici ön ayarı + X X + Y Y Paths: {paths} Anchors: {anchors} Colors: {colors} Yollar: {paths} Bağlantılar: {anchors} Renkler: {colors} Pattern Desen Pattern Editing Desen Düzenleme @@ -2445,6 +2491,7 @@ shape Open Açık Play Current Selection Geçerli Seçimi Oynat Save Actions… Eylemleri Kaydet… Load Actions… Eylemleri Yükle… + Replace Actions… Eylemleri Değiştir… Reset Actions Eylemleri Sıfırla Replace the current actions with the default set? Geçerli eylemler varsayılan setle değiştirilsin mi? Append adds the default set after the current sets instead. Ekle bunun yerine varsayılan seti geçerli setlerin sonuna ekler. @@ -2460,6 +2507,10 @@ shape Open Açık Polar Grid Tool Yuvarlak Izgara Aracı Polygon Çokgen Polygon Properties: Poligon Özellikleri: + Line Properties: Çizgi Özellikleri: + Line Length: Çizgi Uzunluğu: + Line Angle: Çizgi Açısı: + Constrain Pie Angle Pasta Açısını Sınırla Polygon Tool Çokgen Aracı Portrait Portre Power Saving (integrated) Güç Tasarrufu (entegre) @@ -2618,6 +2669,9 @@ digits Malayalam Malayalam Real World: Gerçek Dünya: Real-time Drawing and Editing Gerçek Zamanlı Çizim ve Düzenleme Use Monitor Profile for Canvas Tuval için Monitör Profilini Kullan + Refresh Monitor Profile Monitör Profilini Yenile +@msg turn on Use Monitor Profile for Canvas first önce "Tuval için Monitör Profilini Kullan" seçeneğini açın +@msg this build doesn't read display profiles bu sürüm ekran profillerini okumaz The canvas is drawn in sRGB. Tuval sRGB olarak çizilir. Canvas display profile: Tuvalin ekran profili: The system matches the window to the display's colors. Sistem pencereyi ekranın renklerine uyarlar. @@ -2806,6 +2860,8 @@ digits Malayalam Malayalam Reselect Yeniden seç Reset Sıfırla Reset Bounding Box Sınırlayıcı Kutuyu Sıfırla + Rotate Bounding Box Sınırlayıcı Kutuyu Döndür + Rotate Bounding Box… Sınırlayıcı Kutuyu Döndür… Reset Envelope Mesh Zarf Ağını Sıfırla Reset Envelope Shape Zarf Şeklini Sıfırla Reset Essentials Essentials'ı sıfırla @@ -2846,6 +2902,7 @@ digits Malayalam Malayalam Reshape Segment Segmenti Yeniden Şekillendir Reshape Tool Yeniden Şekillendir Aracı Reshape Type Area Yazı Alanını Yeniden Şekillendir + Resolution Çözünürlük Resolution: Çözünürlük: Responsive duyarlı Restore Geri yükle @@ -2872,6 +2929,7 @@ digits Malayalam Malayalam The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Cmd/Ctrl basılıyken fare tekerleği tuvali yana kaydırır. Dragging sideways on a numeric field's label changes the field's value. Sayısal bir alanın etiketi üzerinde yana sürüklemek alanın değerini değiştirir. A two-finger rotate gesture on a trackpad rotates the canvas view. İzleme dörtgeninde iki parmakla döndürme hareketi tuvalin görünümünü döndürür. + When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Bağlantı noktalarını taşıdığınızda, bir ucu taşınan her eğri uçlarına göre şeklini korur. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Bir aracın kısayol tuşunu basılı tutmak, tuşu bırakana kadar o aracı seçer, ardından önceki araç yeniden seçilir. Shows the bounding box while you move the selection or draw a shape. Seçimi taşırken veya bir şekil çizerken sınırlayıcı kutuyu gösterir. Create Trim Marks draws Japanese-style marks instead of Roman ones. Kesim İşaretleri Oluşturun, Roma tarzı yerine Japon tarzı işaretler çizer. @@ -2902,6 +2960,29 @@ digits Malayalam Malayalam The unit for East Asian type measurements, which no field uses yet. Doğu Asya metni ölçüleri için henüz hiçbir alanın kullanmadığı birim. When on, a number typed without a unit into a field in picas is read in points. Açıkken, pika cinsinden bir alana birimsiz yazılan sayı punto olarak okunur. With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options. XML kimliği seçiliyken nesne adları Katmanlar, Değişkenler ve Katman Seçenekleri'nde XML kimliği olarak gösterilir. + The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl. Yazı boyutu ve satır aralığı adımı: Cmd/Ctrl+Shift+. ve Cmd/Ctrl+Shift+, boyutu bir adım, Alt ile birlikte beş adım değiştirir; yatay yazıda Alt ile yukarı veya aşağı ok satır aralığını bir adım, Cmd/Ctrl ile beş adım değiştirir. + The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl. İzleme ve karakter çifti aralığı adımı, em'in binde biri olarak: yatay yazıda Alt ile sol veya sağ ok imleçteki karakter çifti aralığını ya da seçili metnin izlemesini bir adım, Cmd/Ctrl ile beş adım değiştirir. + The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. Taban çizgisi kaydırma adımı: yatay yazıda Alt ve Shift ile yukarı veya aşağı ok taban çizgisini bir adım, Cmd/Ctrl ile beş adım taşır. + Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. Karakter, Paragraf, OpenType ve Glifler panellerinde Japonca ve diğer Doğu Asya dillerindeki yazı seçeneklerini ve Bileşik Fontlar komutunu gösterir. + Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. Karakter ve Paragraf panellerinde Arapça, İbranice ve Hint dillerindeki yazı seçeneklerini gösterir; örneğin paragraf yönü, keşideler ve rakamlar. + The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. Seçim araçları yazıyı yalnızca taban çizgisinde, alan yazısının çerçevesinde veya yolunda seçer, kutusunun içinde herhangi bir yerde değil. + Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. Yazı tipi menüleri her yazı tipini İngilizce adıyla listeler; kapalıyken kendi dilinde de adı olan bir yazı tipi o adı gösterir. + New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. Yeni alan yazısı Otomatik Boyut açık başlar; böylece yatay yazının dikdörtgen çerçevesi metnine sığacak şekilde yükseklikte büyür veya küçülür. + Font lists and the Type › Font menu show a sample of each font beside its name. Yazı tipi listeleri ve Yazı tipi menüsü her yazı tipinin adının yanında bir örneğini gösterir. + Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on. Yazı tipi örnekleri, arayüzün parlaklığı ne olursa olsun beyaz üzerine koyu yazıyla çizilir; bu yalnızca menülerdeki yazı tipi önizlemeleri açıkken geçerlidir. + How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is. Karakter panelindeki gibi yazı tipi alanlarının listelerinde her satırın ne kadar yüksek olduğu ve dolayısıyla her örneğin ne kadar büyük olduğu. + How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first. Son Yazı Tipleri ve yazı tipi listelerinin en yeniden başlayarak gösterdiği, son kullanılan yazı tiplerinin sayısı, 1 ile 15 arası. + When you change the font or font style of text, characters the new font has no glyph for keep the font they had. Bir metnin yazı tipini veya yazı tipi stilini değiştirdiğinizde, yeni yazı tipinde glifi olmayan karakterler önceki yazı tiplerini korur. + A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export. Tuvaldeki pembe vurgu, OpenType özelliklerinin değiştirdiği glifleri, örneğin bitişik harfleri işaretler; yazdırılmaz ve dışa aktarılmaz. + With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from. Yazım Aracı ile tek bir karakter seçildiğinde tuvalde yanında seçmeniz için alternatif gliflerinden oluşan bir sıra görünür. + A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export. Tuvaldeki pembe vurgu, kendi yazı tipi eksik olduğu için yedek bir yazı tipiyle çizilen metni işaretler; yazdırılmaz ve dışa aktarılmaz. + New type made with a Type tool starts with placeholder text, selected, so typing replaces it. Bir yazı aracıyla oluşturulan yeni yazı, seçili yer tutucu metinle başlar; yazdığınız metin onun yerini alır. + Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list. Paragrafın başına 1. veya * gibi bir liste işareti ve ardından boşluk yazmak paragrafı bir listeye dönüştürür. + Fonts in this folder show in the font menus and can be used without being installed. Bu klasördeki yazı tipleri yazı tipi menülerinde görünür ve yüklenmeden kullanılabilir. + Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows. Yazıya grafik stili uygulamak, stilin dolgusu veya konturu olan yerlerde karakterlerin kendi dolgusunu veya konturunu kaldırır, böylece stilin boyası görünür. + Align and Distribute measure point type by the ink of its glyphs instead of its em box. Hizala ve Dağıt nokta yazısını em kutusu yerine gliflerinin mürekkebine göre ölçer. + Align and Distribute measure area type by the ink of its glyphs instead of its frame. Hizala ve Dağıt alan yazısını çerçevesi yerine gliflerinin mürekkebine göre ölçer. + The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box. Sınırlayıcı kutu ve Dönüştür paneli nokta yazısını em kutusu yerine gliflerinin mürekkebine göre ölçer. Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply. Izgara gizliyken bile çizmeyi, taşımayı ve ölçeklemeyi ızgaranın alt bölümlerine yaslar; açık olduğu sürece Piksel'e Yapış uygulanmaz. The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead. Seçili olmayan kılavuzların rengi; Kılavuz Etiketi olan bir çalışma yüzeyi kendi kılavuzlarını etiketin renginde çizer. Draws guides as solid lines or as dots, including the guides already in the document. Belgede zaten bulunan kılavuzlar da dahil olmak üzere kılavuzları düz çizgi ya da nokta olarak çizer. @@ -2978,6 +3059,7 @@ digits Malayalam Malayalam Rounded Rectangle Tool Yuvarlak Köşeli Dikdörtgen Aracı Rounded Rectangle… Yuvarlatılmış Dikdörtgen… Row Size: Satır Boyutu: + Rows Satırlar Rows: Satırlar: Rule: Kural: Rulers Cetveller @@ -3180,6 +3262,9 @@ digits Malayalam Malayalam Search commands, tools, panels and effects… Komutları, araçları, panelleri ve efektleri arayın… No commands match Eşleşen komut yok {pos} of {total}: {name} {pos}/{total}: {name} + No menu item Menü öğesi yok + Toolbar Araç Çubuğu + {toolbar}, in the {tool} group {toolbar}, {tool} grubunda @plural {n} result|{n} results {n} sonuç @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {n} sonuçtan {shown} tanesi. Daraltmak için yazmaya devam edin. Recent Commands Son komutlar @@ -3260,6 +3345,7 @@ digits Malayalam Malayalam Set Slice Rectangle Dilim Dikdörtgenini Ayarla Set Tab Stops Sekme Duraklarını Ayarla Set Text Metni Ayarla + Set the current fill or stroke to the selected color Geçerli dolguyu veya konturu seçilen renge ayarla Set the selected color to the current color Seçilen rengi geçerli renge ayarla Set Zoom Yakınlaştırmayı Ayarla Settings… Ayarlar… @@ -3380,7 +3466,7 @@ digits Malayalam Malayalam Show Vivid/Muted Canlı/Sessiz Göster Show Warm/Cool Sıcak/Soğuk Göster Show {kind} Brushes {kind} Fırçalarını Göster - Show/hide plate (Alt-click: only this plate) Plakayı göster/gizle (Alt tuşuyla tıklayın: yalnızca bu plaka) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Plakayı göster/gizle (Alt tuşuyla tıklayın: yalnızca bu plaka; yeniden Alt tuşuyla tıklayın: tüm plakalar) Show: Göster: Shown with the optimised preview. Optimize edilmiş önizlemeyle gösterilir. Side 1: 1. Taraf: @@ -3675,7 +3761,7 @@ digits Malayalam Malayalam Composite Fonts Bileşik Fontlar Export Composite Fonts Bileşik Fontları Dışa Aktar Import Composite Fonts Bileşik Fontları İçe Aktar -@msg each font must be {name, parts} her font {name, parts} biçiminde olmalı +@msg each font must be {{name, parts}} her font {{name, parts}} biçiminde olmalı @msg unknown key `{k}`; a font takes name and parts bilinmeyen anahtar `{k}`; bir font name ve parts alır @msg each font needs a name her fontun bir adı olmalı @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` bir bileşik fontun adı olamaz (1 ile {COMPOSITE_NAME_MAX} karakter arası, denetim karakteri olmadan) @@ -3688,7 +3774,7 @@ digits Malayalam Malayalam @msg two composite fonts are named `{_1}` iki bileşik fontun adı `{_1}` @msg `{_1}` is the name of an installed font `{_1}` yüklü bir fontun adı @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2}, bir bileşik font olan `{font}` ile ayarlı -@msg give fonts: [{name, parts}…] fonts verin: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] fonts verin: [{{name, parts}}…] @msg path is empty path boş @msg fonts must be a list of composite fonts fonts bir bileşik font listesi olmalı @msg names must be strings names dizeler olmalı @@ -3770,6 +3856,13 @@ digits Malayalam Malayalam Thumbnail View Küçük Resim Görünümü Thumbnails: Küçük resimler: Tile Fayans + Tile All Vertically Tümünü Dikey Fayans + Tile All Horizontally Tümünü Yatay Fayans + 2-Up Layout 2'li Düzen + 3-Up Layout 3'lü Düzen + 4-Up Layout 4'lü Düzen + 6-Up Layout 6'lı Düzen + Arrange Documents Belgeleri Düzenle Tile Edge Color Döşeme Kenar Rengi Tile Edge Color… Döşeme Kenar Rengi… Tile Full Pages Tam Sayfaları Döşe @@ -3961,6 +4054,8 @@ digits Malayalam Malayalam V Spacing: V Aralığı: V: V: Variable Width Profile Değişken Genişlik Profili + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Konturun fırçası kendi boyutunu korur, bu yüzden genişlik profili konturu değiştirmez. Profil kullanmak için fırçayı kaldırın. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Konturun fırçası kendi boyutunu korur, bu yüzden genişlik profili konturu değiştirmez. Profil kullanmak için fırçayı kaldırın. Variables Değişkenler New Variable Yeni Değişken Delete Variable Değişkeni Sil @@ -4023,7 +4118,7 @@ digits Malayalam Malayalam Vertical: Dikey: Very High Çok Yüksek View Görünüm - View Artboard Only Yalnızca Çalışma Yüzeyini Görüntüle + View Artboard Contents Only Yalnızca Çalışma Yüzeyi İçeriğini Görüntüle View Opacity Mask Opaklık Maskesini Görüntüle View PDF after saving Kaydettikten sonra PDF'yi görüntüle View {n} {n}'yi görüntüle @@ -4232,6 +4327,7 @@ imageTrace Outline Kontur Bevel Eğim Offset Ofset Axis Eksen + Axis Angle Eksen açısı axis Horizontal Yatay axis Vertical Dikey axis Both Her İkisi @@ -4298,6 +4394,13 @@ axis Both Her İkisi Show External Script Warning Harici Betik Uyarısını Göster A Script Is Running Bir Betik Çalışıyor Script Alert Betik Uyarısı + Script File Access Betik Dosya Erişimi + The script asks to read a file you choose. Betik, seçtiğiniz bir dosyayı okumak için izin istiyor. + The script asks to read and write a file you choose. Betik, seçtiğiniz bir dosyayı okumak ve yazmak için izin istiyor. + The script asks to read and write a folder you choose, with everything in it. Betik, seçtiğiniz bir klasörü içindeki her şeyle birlikte okumak ve yazmak için izin istiyor. + Allow Once Bir Kez İzin Ver + Always Allow This Script Bu Betiğe Her Zaman İzin Ver + Deny Reddet A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Bir betik açık belgeleri değiştirebilir ve çalıştırdığı komutlarla dosya yazabilir. Yalnızca güvendiğiniz betikleri çalıştırın. Do not show this warning again Bu uyarıyı bir daha gösterme Stop the script and undo what it did? Then quit again. Betik durdurulsun ve yaptıkları geri alınsın mı? Ardından yeniden çıkın. @@ -4322,6 +4425,8 @@ axis Both Her İkisi @msg the script is no longer in the Scripts folder betik artık Scripts klasöründe değil Some scripts were not listed Bazı komut dosyaları listelenmedi The Scripts folder cannot be read Scripts klasörü okunamıyor + Loading scripts… Betikler yükleniyor… + The Scripts folder is still being read Scripts klasörü hâlâ okunuyor @msg the script's run is no longer available betiğin çalıştırması artık kullanılamıyor @msg a failed command changed undo steps that could not be put back, so the script was stopped başarısız bir komut geri yüklenemeyen geri alma adımlarını değiştirdi, bu yüzden betik durduruldu @msg a recovery copy could not be written, so the script was not run kurtarma kopyası yazılamadı, bu nedenle betik çalıştırılmadı @@ -4334,8 +4439,6 @@ axis Both Her İkisi @msg Script file could not be read Betik dosyası okunamadı @msg Script folder has more than 2,048 entries Betik klasöründe 2.048'den fazla öğe var @msg Script file open mode must be r, w, e or a Betik dosyası açma modu r, w, e veya a olmalıdır -@msg Script file writing is not available Betik dosyası yazma kullanılamıyor -@msg Script file dialogs are not available Betik dosyası iletişim kutuları kullanılamıyor @msg Script files cannot be opened in another application Betik dosyaları başka bir uygulamada açılamaz @msg Script file access is unavailable on the web Betik dosyası erişimi web'de kullanılamıyor @msg Script has 256 files open Betiğin 256 açık dosyası var @@ -4451,8 +4554,37 @@ liquify-list-end {0}, {1} {0} ve {1} @msg the main script engine is new for each run and is never kept, so it cannot be dropped ana betik motoru her çalıştırmada yenidir ve hiç saklanmaz, bu yüzden bırakılamaz @msg there is no script engine named {name} {name} adlı bir betik motoru yok @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` yalnızca sorulacak kimsenin olmadığı bir çalıştırma içindir: uygulamada her iletişim kutusunu kişi yanıtlar +@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` 1 ile {_1} arasında bir tam sayı olmalıdır +@msg `args{place}` is nested more than 64 levels deep `args{place}` 64 düzeyden daha derin iç içe geçmiş +@msg `args` must be an object `args` bir nesne olmalıdır +@msg `args` is larger than 1 MiB `args` 1 MiB'tan büyük +@msg `path` is empty `path` boş +@msg `installed` takes a `path`, not a `source` `installed` bir `path` alır, `source` almaz +@msg `path` must name a .js or .jsx file `path` bir .js veya .jsx dosyasını adlandırmalıdır +@msg give exactly one of `path` and `source` `path` ve `source` değerlerinden tam olarak birini verin @msg Running a script Betik çalıştırılıyor @msg Copied the script report Komut dosyası raporu kopyalandı +@msg Script file access denied: {path} Betiğin dosya erişimi reddedildi: {path} +@msg Script file access to the app's own folders is not allowed Betiklerin uygulamanın kendi klasörlerine erişmesine izin verilmez +@msg Script file cannot encode the text Betiğin dosyası metni kodlayamıyor +@msg Script file could not be written Betiğin dosyası yazılamadı +@msg Script file dialogs need a person to answer them Betiğin dosya iletişim kutularının yanıtlanması için bir kişi gerekir +@msg Script file is not open for writing Betiğin dosyası yazmak için açık değil +@msg Script file name is already in use Betiğin dosya adı zaten kullanılıyor +@msg Script file name must be a name without a folder Betiğin dosya adı klasör içermeyen bir ad olmalıdır +@msg Script file permission can be kept only for a script run from a file Dosya izni yalnızca bir dosyadan çalıştırılan betik için saklanabilir +@msg Script file permission could not be saved Betiğin dosya izni kaydedilemedi +@msg Script folder is not empty Betiğin klasörü boş değil +@msg Script files cannot make aliases Betiğin dosyaları takma ad oluşturamaz +@msg Script file hidden setting cannot be changed Betiğin dosyasının gizli ayarı değiştirilemez +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: dosya iletişim kutusu yerleşik bir işlevin, bir getter'ın, bir dönüştürmenin veya $.evalFile'ın çalıştırdığı bir dosyanın geri çağrısı içinde açılamaz; onu betiğin kendi kodundan çağırın +@msg the script wrote more file data than one run may write (32 MiB) betik, bir çalıştırmanın yazabileceğinden fazla dosya verisi yazdı (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop bir betiğin dosya iletişim kutusu için `answer` şunlardan biri olmalıdır: once, always, deny, stop +@msg choose a file or folder first, or deny önce bir dosya veya klasör seçin ya da reddedin +@msg the script file permissions could not be saved: {e} betiklerin dosya izinleri kaydedilemedi: {e} +@msg this script's file access can be allowed only once bu betiğin dosya erişimine yalnızca bir kez izin verilebilir +@msg Only the person at the keyboard can allow a script's file access Bir betiğin dosya erişimine yalnızca klavye başındaki kişi izin verebilir +@msg A script is given at most 2,048 files: the files picked after them were left out Bir betiğe en fazla 2.048 dosya verilir: bunlardan sonra seçilen dosyalar dışarıda bırakıldı @msg Copied the link info Bağlantı bilgisi kopyalandı @msg Corners edits the corners of a path Köşeler bir yolun köşelerini düzenler @msg Couldn't copy to the system clipboard: {e} Sistem panosuna kopyalanamadı: {e} @@ -4526,6 +4658,7 @@ liquify-list-end {0}, {1} {0} ve {1} @msg Saved {path} {path} kaydedildi @msg Select text or click into text with the Type tool to insert glyphs Glif eklemek için metni seçin veya Yazım aracıyla metne tıklayın @msg Shape Builder: no region under the pointer Şekil Oluşturucu: işaretçinin altında bölge yok +@msg Shape Builder: select all paths you want to merge Şekil Oluşturucu: birleştirmek istediğiniz tüm yolları seçin @msg Shape Builder: select paths or compound paths Şekil Oluşturucu: yolları veya bileşik yolları seçin @msg Show All Hidden Attributes: nothing is hidden Tüm Gizli Özellikleri Göster: hiçbir şey gizli değildir @msg Split Into Grid: select paths large enough for the grid Izgaraya Böl: ızgara için yeterince büyük yollar seçin @@ -4576,6 +4709,8 @@ liquify-list-end {0}, {1} {0} ve {1} @msg `{min_key}` is greater than `{max_key}` `{min_key}`, `{max_key}` değerinden büyük @msg give at least one of `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` şunlardan en az birini verin: `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` grayscale, rgb, hsb, cmyk veya websafe olmalıdır +@msg `view` must be wheel or box `view` wheel veya box olmalıdır +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` hue, saturation, brightness, red, green veya blue olmalıdır @msg `{k}` must be [x, y] `{k}` [x, y] olmalıdır @msg `{name}` has no options `{name}`nin seçeneği yok @msg `{name}` is a built-in workspace; choose another name `{name}` yerleşik bir çalışma alanıdır; başka bir isim seç @@ -4642,6 +4777,7 @@ liquify-list-end {0}, {1} {0} ve {1} @msg bad trailer kötü römork @msg balance must be between 0 and 100 balance 0 ile 100 arasında olmalıdır @msg batch step {_1} (`{id}`) failed: {e} toplu adım {_1} (`{id}`) başarısız oldu: {e} +@msg action step {_1} (`{id}`) failed: {reason} eylem adımı {_1} (`{id}`) başarısız oldu: {reason} @msg brightness must be dark|mediumDark|mediumLight|light brightness dark|mediumDark|mediumLight|light olmalıdır @msg can't encode the document: {0} belge kodlanamıyor: {0} @msg can't parse shortcut `{c}` `{c}` kısayolu ayrıştırılamıyor @@ -4661,6 +4797,7 @@ liquify-list-end {0}, {1} {0} ve {1} @msg choose a folder to export to dışa aktarılacak bir klasör seçin @msg choose a location for the package paket için bir yer seçin @msg clipboard is empty pano boş +@msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: renk tablosunda en az bir renk kalmalı @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}`, "#ff8800" gibi bir renk değil @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: en fazla {MAX_TABLE} renginde @msg command `{0}` is not available right now: {1} `{0}` komutu şu anda kullanılamıyor: {1} @@ -4735,9 +4872,15 @@ liquify-list-end {0}, {1} {0} ve {1} @msg no PNG encoder PNG kodlayıcı yok @msg no active document etkin belge yok @msg no active perspective plane aktif perspektif düzlemi yok +@msg the perspective grid is hidden perspektif ızgarası gizli +@msg Automatic Plane Positioning is off: turn on anchorPoint or gridlineIntersection (perspective.widget.options) Otomatik düzlem konumlandırma kapalı: anchorPoint veya gridlineIntersection seçeneğini açın (perspective.widget.options) +@msg anchorPoint must be true or false anchorPoint true veya false olmalıdır +@msg gridlineIntersection must be true or false gridlineIntersection true veya false olmalıdır +@msg tolerance must be 0 or more tolerance 0 veya daha büyük olmalıdır +@msg give `at` or `clear`, not both `at` veya `clear` verin, ikisini birden değil @msg no anchor points selected bağlantı noktası seçilmedi -@msg `points` must be three [x, y] pairs of numbers `points` üç [x, y] sayı çifti olmalıdır -@msg direct-select three anchor points, or give `points` üç bağlantı noktasını doğrudan seçin veya `points` verin +@msg `points` must be two or three [x, y] pairs of numbers `points` iki veya üç [x, y] sayı çifti olmalıdır +@msg direct-select two or three anchor points, or give `points` iki veya üç bağlantı noktasını doğrudan seçin veya `points` verin @msg no circle passes through these points: two are the same or all three lie on one line bu noktalardan geçen bir çember yok: ikisi aynı ya da üçü de aynı doğru üzerinde @msg no app to open files here burada dosyaları açacak uygulama yok @msg no artboard çalışma yüzeyi yok @@ -4833,6 +4976,9 @@ liquify-list-end {0}, {1} {0} ve {1} @msg no such user library böyle bir kullanıcı kütüphanesi yok @msg no such view öyle bir görüş yok @msg no such width point böyle bir genişlik noktası yok +@msg `single` must be `incoming` or `outgoing` `single`, `incoming` veya `outgoing` olmalıdır +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` ve `outIndex`, tek bir süreksiz genişlik noktasının iki yarısı olmalıdır +@msg a discontinuous width point keeps its place süreksiz genişlik noktası yerini korur @msg no swatch `{name}` renk örneği yok `{name}` @msg no swatch library `{l}` (see swatch.library.list) renk örneği kitaplığı yok `{l}` (bkz. swatch.library.list) @msg no symbol instances selected sembol örneği seçilmedi @@ -5125,6 +5271,8 @@ liquify-list-end {0}, {1} {0} ve {1} @msg {label}: lost track of a shape's style {label}: şeklin stilinin izini kaybettirdi @msg {label}: select paths {label}: yolları seç @msg {label}: select paths, compound paths, groups or text {label}: yolları, bileşik yolları, grupları veya metni seçin +@msg a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first alan çevrelemeyen bir çizgi veya başka bir açık yol sonucun şeklini değiştirmez; dahil etmek için önce ona Nesne › Yol › Anahat Konturu uygulayın +@msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first {label} boş bir sonuç üretti: bir çizgi veya başka bir açık yol alan çevrelemiyor; dahil etmek için önce ona Nesne › Yol › Anahat Konturu uygulayın @msg {label}… {label}… @msg {name}: CRC mismatch {name}: CRC uyumsuzluğu @msg {name}: no local header {name}: yerel başlık yok @@ -5151,6 +5299,9 @@ liquify-list-end {0}, {1} {0} ve {1} @msgplural Discarded {n} recovered document|Discarded {n} recovered documents Kurtarılan {n} belge atıldı @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them Kurtarılan {n} belge geri yüklendi: saklamak için kaydedin @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} {n} notla açıldı: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} {n} notla kopyalandı: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} {n} notla kesildi: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Görüntü {n} notla izlendi: {first} @msgplural {notice}. Opened with {n} note: {first}|{notice}. Opened with {n} notes: {first} {notice}. {n} notla açıldı: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} {path}, {n} notla kaydedildi: {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first {n} görsel gömüldü; {missing} eksik: önce onları yeniden bağlayın @@ -5177,6 +5328,8 @@ liquify-list-end {0}, {1} {0} ve {1} @msg All colors are within the CMYK gamut Tüm renkler CMYK gamındadır @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} renk CMYK gamının dışında @msg Unembedded to {_1} {_1}'ye gömülü değil +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} {n} görselin gömülmesi kaldırıldı: {folder} +@msg every numbered name for {name} is taken in that folder {name} için numaralandırılmış her ad o klasörde zaten kullanılıyor @msg Reset {_1} {_1}'yi sıfırla @msg Sent to {_1} {_1}'ye gönderildi @msg {_1} files {_1} dosyaları @@ -5192,6 +5345,8 @@ liquify-list-end {0}, {1} {0} ve {1} @msg Reload the page to go on (changes not saved yet may be lost). Devam etmek için sayfayı yeniden yükleyin (henüz kaydedilmemiş değişiklikler kaybolabilir). @msg tool (a tool id) is required tool (bir araç kimliği) gerekli @msg {tool} isn't in a toolbar group of several tools {tool} çeşitli araçlardan oluşan bir araç çubuğu grubunda değil +@msg Presentation Mode hides the toolbars: change the screen mode to show them Sunum Modu araç çubuklarını gizler: göstermek için ekran modunu değiştirin +@msg Tab has hidden the toolbars: press Tab to show them Tab araç çubuklarını gizledi: göstermek için Tab tuşuna basın @msg onto must name a panel floating in another group onto başka bir grupta yüzen bir paneli adlandırmalıdır @msg below and above must name a panel floating in another group below ve above başka bir grupta yüzen bir paneli adlandırmalıdır @msg give only one of onto, below and above onto, below ve above değerlerinden yalnızca birini verin @@ -5534,7 +5689,7 @@ effect Soft Yumuşak Show axis Ekseni göster Reset all Tümünü sıfırla Reset to default Varsayılana sıfırla - Reset all Revolve settings to their defaults. Tüm Revolve ayarlarını varsayılan değerlerine sıfırlayın. + Reset all Revolve settings to their defaults. Tüm Eksen Etrafında Döndür ayarlarını varsayılan değerlerine sıfırlayın. Drag values or labels. Double-click a value to type. Değerleri veya etiketleri sürükleyin. Yazmak için bir değeri çift tıklayın. Drag rings to rotate. Shift snaps to 15°. Döndürmek için halkaları sürükleyin. Kaydırma 15°'ye sabitlenir. Track cube Döndürme küpü @@ -5580,6 +5735,7 @@ lighting Light Işık @msg missing panel layout eksik panel düzeni @msg unsupported native docking operation desteklenmeyen yerel yerleştirme işlemi Linux Display Server Linux Görüntü Sunucusu + Low-Latency Drawing Düşük Gecikmeli Çizim X11 (XWayland) X11 (XWayland) Ruler Origin Cetvelin Kökeni Reset Ruler Origin Cetvel Başlangıç Noktasını Sıfırla @@ -5604,6 +5760,7 @@ lighting Light Işık Cove Koy Depth Derinlik Front Ön + Side Yan Isometric Bottom İzometrik Alt Isometric Left İzometrik Sol Isometric Right İzometrik Sağ @@ -5672,7 +5829,7 @@ lighting Light Işık @msg the SVG filter can't be drawn: check its primitives and their inputs SVG filtresi çizilemiyor: temel öğelerini ve bunların girdilerini denetle @msg an SVG filter's elements nest at most {MAX_DEPTH} deep bir SVG filtresinin öğeleri en fazla {MAX_DEPTH} düzey iç içe geçer @msg an SVG filter is at most {_1} KB bir SVG filtresi en fazla {_1} KB olur -@msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) nesnenin 3 boyutlu efekti yok (Ekstrüzyon ve Eğim, Döndür, Şişir veya Döndür) +@msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) nesnenin 3 boyutlu efekti yok (Ekstrüzyon ve Eğim, Eksen Etrafında Döndür, Şişir veya Döndür) @msg `render` must be an object holding only `mode`, set to shaded or wireframe `render`, yalnızca değeri shaded veya wireframe olan `mode` içeren bir nesne olmalıdır @msg its 3D effect builds no solid 3 boyutlu efekti hiçbir katı oluşturmuyor @msg bevel must be none or one of {_1} bevel, none veya {_1} değerlerinden biri olmalıdır @@ -5698,7 +5855,7 @@ lighting Light Işık @msg each of `{GRAPHICS}` must be an object `{GRAPHICS}` içindeki her öğe bir nesne olmalıdır @msg `{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}` `{GRAPHICS}` girdileri symbol, face, x, y, scale ve rotation alır, `{k}` almaz @msg each of `{GRAPHICS}` needs `symbol`, the name of a symbol `{GRAPHICS}` içindeki her öğe, bir sembolün adı olan `symbol` gerektirir -@msg `{GRAPHICS}` face must be front or back `{GRAPHICS}` face değeri front veya back olmalıdır +@msg `{GRAPHICS}` face must be front, back or side `{GRAPHICS}` face değeri front, back veya side olmalıdır @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} `{GRAPHICS}` {key} değeri {lo} ile {hi} arasında bir sayı olmalıdır @msg `{GRAPHICS}` must be an array `{GRAPHICS}` bir dizi olmalıdır @msg Graphics map onto the Plane, Extrude and Revolve object types Grafikler Düzlem, Ekstrüzyon ve Eksen Etrafında Döndür nesne türlerine eşlenir @@ -5721,22 +5878,22 @@ lighting Light Işık @msg The 3D projection is not finite 3D izdüşümü sonlu değil @msg The 3D shadow is too complex; turn Shadows off or simplify the art 3D gölgesi çok karmaşık; Gölgeler'i kapatın veya resmi basitleştirin @msg The shape contains invalid coordinates Şekil geçersiz koordinatlar içeriyor -@msg Revolve profile contains invalid coordinates Döndür profili geçersiz koordinatlar içeriyor -@msg Revolve profile is too complex Döndür profili çok karmaşık -@msg Revolve projection is not finite Döndür izdüşümü sonlu değil -@msg Revolve requires finite profile coordinates within 100 million points Döndür, 100 milyon pt sınırı içinde sonlu profil koordinatları gerektirir -@msg Revolve surface is too complex; reduce Segments or simplify the profile Döndür yüzeyi çok karmaşık; Segmentler değerini azaltın veya profili basitleştirin -@msg Revolve surface is too complex; simplify the profile Döndür yüzeyi çok karmaşık; profili basitleştirin -@msg Revolve visibility cannot split the projected boundary Döndür görünürlüğü izdüşümü alınan sınırı bölemiyor -@msg Revolve visibility creates too many fragments Döndür görünürlüğü çok fazla parça oluşturuyor -@msg Revolve visibility creates too many vector anchors Döndür görünürlüğü çok fazla vektör bağlantı noktası oluşturuyor -@msg Revolve visibility exceeds its geometry work limit Döndür görünürlüğü geometri işlem sınırını aşıyor -@msg Revolve visibility exceeds its spatial index limit Döndür görünürlüğü uzamsal dizin sınırını aşıyor -@msg Revolve visibility has too many boundary crossings Döndür görünürlüğünde çok fazla sınır kesişimi var -@msg Revolve visibility has too many input anchors Döndür görünürlüğünde çok fazla girdi bağlantı noktası var -@msg Revolve visibility requires convex cap sectors Döndür görünürlüğü dışbükey kapak dilimleri gerektirir -@msg Revolve visibility requires finite projected faces Döndür görünürlüğü sonlu izdüşüm yüzleri gerektirir -@msg Too many Revolve faces for visibility evaluation Görünürlük değerlendirmesi için çok fazla Döndür yüzü var +@msg Revolve profile contains invalid coordinates Eksen Etrafında Döndür profili geçersiz koordinatlar içeriyor +@msg Revolve profile is too complex Eksen Etrafında Döndür profili çok karmaşık +@msg Revolve projection is not finite Eksen Etrafında Döndür izdüşümü sonlu değil +@msg Revolve requires finite profile coordinates within 100 million points Eksen Etrafında Döndür, 100 milyon pt sınırı içinde sonlu profil koordinatları gerektirir +@msg Revolve surface is too complex; reduce Segments or simplify the profile Eksen Etrafında Döndür yüzeyi çok karmaşık; Segmentler değerini azaltın veya profili basitleştirin +@msg Revolve surface is too complex; simplify the profile Eksen Etrafında Döndür yüzeyi çok karmaşık; profili basitleştirin +@msg Revolve visibility cannot split the projected boundary Eksen Etrafında Döndür görünürlüğü izdüşümü alınan sınırı bölemiyor +@msg Revolve visibility creates too many fragments Eksen Etrafında Döndür görünürlüğü çok fazla parça oluşturuyor +@msg Revolve visibility creates too many vector anchors Eksen Etrafında Döndür görünürlüğü çok fazla vektör bağlantı noktası oluşturuyor +@msg Revolve visibility exceeds its geometry work limit Eksen Etrafında Döndür görünürlüğü geometri işlem sınırını aşıyor +@msg Revolve visibility exceeds its spatial index limit Eksen Etrafında Döndür görünürlüğü uzamsal dizin sınırını aşıyor +@msg Revolve visibility has too many boundary crossings Eksen Etrafında Döndür görünürlüğünde çok fazla sınır kesişimi var +@msg Revolve visibility has too many input anchors Eksen Etrafında Döndür görünürlüğünde çok fazla girdi bağlantı noktası var +@msg Revolve visibility requires convex cap sectors Eksen Etrafında Döndür görünürlüğü dışbükey kapak dilimleri gerektirir +@msg Revolve visibility requires finite projected faces Eksen Etrafında Döndür görünürlüğü sonlu izdüşüm yüzleri gerektirir +@msg Too many Revolve faces for visibility evaluation Görünürlük değerlendirmesi için çok fazla Eksen Etrafında Döndür yüzü var @msg input contains NaN or infinite coordinates girdi NaN veya sonsuz koordinatlar içeriyor @msg input path could not be closed girdi yolu kapatılamadı @msg the shapes are too degenerate to combine şekiller birleştirilemeyecek kadar yozlaşmış @@ -6162,6 +6319,7 @@ lighting Light Işık of arasında sRGB IEC61966-2.1 sRGB IEC61966-2.1 x Height x Yükseklik + Em Box Height Em Kutusu Yüksekliği ▾ Default Actions ▾ Varsayılan Eylemler ⚠ {chord} was already used by {names} — it has been removed there. ⚠ {chord} zaten {names} tarafından kullanılmıştı — oradan kaldırıldı. @id file.close Kapat @@ -6726,6 +6884,13 @@ theme Appearance Görünüm @msg an image has no pixels and was left out piksel içermeyen bir görüntü dışarıda bırakıldı @msg thumbnail: no page {n} (the file has 1) thumbnail: {n}. sayfa yok (dosyada 1 sayfa var) @msg variables that aren't text were left out: {kinds} metin olmayan değişkenler dışarıda bırakıldı: {kinds} +variable-kind Visibility Görünürlük +variable-kind Linked File Bağlantılı Dosya +variable-kind Graph Data Grafik Verileri +variable-kind Unknown Bilinmiyor +variable-list-two {0}, {1} {0} ve {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} ve {1} @msg a new document won't read these variables back with their kind: {names} yeni bir belge bu değişkenleri türleriyle geri okumaz: {names} @msg a new document refuses this file because of these variables: {names} yeni bir belge bu değişkenler nedeniyle bu dosyayı reddeder: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them `{name}` için `{header}` başlığı `{other}` değişkeni olarak okunur: birini yeniden adlandırın @@ -7181,7 +7346,7 @@ axis Y Axis Y ekseni @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 `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` "document", {{artboards: [index, …]}} veya {{layers: [id, …]}} 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 @@ -7366,9 +7531,9 @@ axis Y Axis Y ekseni @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 numbers out of order in {{}} quantifier {{}} 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}: a hollow Extrude & Bevel has no caps: turn on Cap to map a graphic nesne {_1}: içi boş bir Ekstrüzyon 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} @@ -7435,9 +7600,12 @@ axis Y Axis Y ekseni @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 a linked image file is outside the read roots bağlantılı bir görüntü dosyası okuma köklerinin dışında +@msg a linked file's export folder is outside the read roots bağlantılı bir dosyanın dışa aktarma klasörü okuma köklerinin dışında +@msg a linked file's editing data can't be read to check it against the read roots bağlantılı bir dosyanın düzenleme verileri okuma köklerine göre denetlemek için okunamıyor @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 paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) boya bir serbest biçimli degrade değil (paint.editGradient {{kind: "freeform"}} 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 @@ -7507,7 +7675,7 @@ axis Y Axis Y ekseni @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 A profile supports one Revolve effect. Edit the existing effect's options instead. Bir profil tek bir Eksen Etrafında Döndür 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 @@ -7724,6 +7892,8 @@ axis Y Axis Y ekseni @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 `{file}` has no swatches of its own `{file}` dosyasının kendi renk örnekleri yok +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` desen örnekleri içeriyor ve bir .vcswatches dosyası bunları tutamaz @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 @@ -7947,7 +8117,13 @@ axis Y Axis Y ekseni @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 line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path satır {line}, sütun {column}: `{var}` için `{path}` grafik veri dosyası göreli bir yoldur: `base` ya da mutlak bir yol verin +@msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} satır {line}, sütun {column}: `{var}` için grafik veri dosyası okunamıyor: {e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` isn't followed: {r} satır {line}, sütun {column}: `{var}` için `{path}` grafik veri dosyası izlenmiyor: {r} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes satır {line}, sütun {column}: `{var}` için `{path}` grafik veri dosyası {MAX_GRAPH_DATA_FILE} bayttan büyük +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes satır {line}, sütun {column}: `{var}` için `{path}` grafik veri dosyası {MAX_GRAPH_CSV} bayttan uzun bir grafik değeri veriyor +@msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all satır {line}, sütun {column}: grafik veri dosyaları toplamda {MAX_GRAPH_FILES_TOTAL} bayttan fazla +@msg `base` is empty `base` boş @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 @@ -7958,6 +8134,7 @@ axis Y Axis Y ekseni @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 extend connect için extend 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 @@ -9261,6 +9438,12 @@ anchor Points: Noktalar: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` "free", "keepAngles" veya "symmetric" olmalıdır @msg `{key}` must be [x, y] `{key}` [x, y] olmalıdır +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Birim Dönüştürücü + Unit Converter Panel Birim Dönüştürücü Paneli + Copy with Units Birimlerle Kopyala + From Selection Seçimden + # Color Effects add-on: Select by Color Kind. Select by Color Kind Renk Türüne Göre Seç Objects with Spot Colors Spot Renkli Nesneler @@ -9485,6 +9668,14 @@ breakText Glyphs Glifler Remove Gaps Boşlukları Kaldır @msg that makes too many pieces (at most 100000): make the dashes longer bu çok fazla parça oluşturur (en fazla 100000): tireleri uzatın @msg select paths, or segments, to divide bölünecek yolları veya bölümleri seçin +# Path Precision Tools add-on: Smooth Bridge. + Smooth Bridge… Yumuşak Köprü… + Smooth Bridge Yumuşak Köprü + Keep Originals Orijinalleri Koru +@msg select two circles to bridge köprüyle birleştirilecek iki daire seçin +@msg one circle is inside the other bir daire diğerinin içinde +@msg the circles are too far apart for this radius: raise the radius daireler bu yarıçap için birbirinden çok uzak: yarıçapı artırın +@msg the circles are too far apart for this radius daireler bu yarıçap için birbirinden çok uzak # Path Precision Tools add-on: Common Tangents. Common Tangents… Ortak Teğetler… Common Tangents Ortak Teğetler @@ -9875,3 +10066,13 @@ breakText Glyphs Glifler @msg A panel is not joined to the rest by a crease. Bir panel geri kalanlara hiçbir pilyaj çizgisiyle bağlı değil. @msg A fold line is on a non-printing layer. Bir katlama çizgisi yazdırılmayan bir katmanda. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneller: {panels}, menteşeler: {hinges}, hatalar: {errors}, uyarılar: {warnings} + Fold Preview Katlama Önizlemesi + Fold Katlama + Show Fold Lines Katlama Çizgilerini Göster + Three-Quarter Dörtte Üç + Open a document to preview its folded shape. Katlanmış şeklini önizlemek için bir belgeyi açın. +@msg Check the fold lines first. Önce katlama çizgilerini denetleyin. +@msg Panels: {panels}, hinges: {hinges} Paneller: {panels}, menteşeler: {hinges} +@msg Other blanks not shown: {count} Gösterilmeyen diğer açınımlar: {count} +@msg A joint does not close by {gap} pt. Bir birleşim {gap} pt kadar kapanmıyor. +@msg Two panels pass through each other. İki panel birbirinin içinden geçiyor. diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index dbd6d2609e..d6f50c5ebc 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -113,6 +113,7 @@ Add Anchor Point Додати опорну точку Add Anchor Point Tool Інструмент «Додати опорну точку» Add Anchor Points Додати опорні точки + Add Around Додати навколо об’єкта Add Effect Додати ефект Add Freeform Line Додати довільну лінію Add Freeform Point Додати довільну точку @@ -134,8 +135,12 @@ Add to Swatches Додати до зразків Add Used Colors Додати використані кольори Additional Plug-ins Folder Папка додаткових модулів + Plug-in Instruction Budget Бюджет інструкцій модулів Additional Fonts Folder Папка додаткових шрифтів Adjust Adjoining Width Points Налаштувати суміжні точки ширини + Incoming Вхідна + Outgoing Вихідна + Single Width Only Лише одна ширина Adjust Color Balance… Налаштувати колірний баланс… Adjust Colors Налаштувати кольори Adjust Options: Параметри налаштування: @@ -190,6 +195,7 @@ Angle: Кут: Angles Кути Animated Zoom Анімоване масштабування + Anti Alias Згладжування Anti-alias Згладжування Anti-Alias Згладжування Anti-alias Rasters Згладжувати растрові зображення @@ -299,7 +305,7 @@ font-technology Variable Варіативні Background Contents Вміст фону Background: Фон: Backspace Backspace - Bar Graph Tool Інструмент «Гістограма» + Bar Graph Tool Інструмент «Лінійчата діаграма» Baseline Базова лінія Baseline Shift Зміщення базової лінії Basic Latin Основна латиниця @@ -357,6 +363,12 @@ font-technology Variable Варіативні Brush Definition Визначення пензля Brush Libraries Бібліотеки пензлів Brush Options… Параметри пензля… + Options of Selected Object… Параметри виділеного об’єкта… + Options of Selected Object Параметри виділеного об’єкта +@msg no path painted with a brush is selected не виділено контур, намальований пензлем +@msg the selected paths are painted with brushes of different types виділені контури намальовано пензлями різних типів +@msg give `params` or `reset`, not both укажіть `params` або `reset`, але не обидва +@msg a bristle brush has no options of its own on a path щетинний пензель не має власних параметрів на контурі Brush Strokes Мазки пензля Brushes Пензлі Built-in Libraries Вбудовані бібліотеки @@ -413,6 +425,12 @@ font-technology Variable Варіативні Character Alignment Вирівнювання символів Character / Paragraph Символ / Абзац Character Rotation Поворот символів + Chinese Big 5 Китайська Big 5 + Cyrillic Кирилиця + Greek Грецька + Turkish Турецька + Baltic Балтійська + Central European Центральноєвропейська Character Set: Набір символів: Character Style Стиль символу Character Style Options Параметри стилю символу @@ -475,6 +493,8 @@ font-technology Variable Варіативні Choose a folder Виберіть папку Choose… Вибрати… Circle Коло + Circle Tool Інструмент «Коло» + Circle too large Коло завелике Classic Defaults Класичні значення за промовчанням Clean Up… Очистити… Clear Очистити @@ -550,6 +570,7 @@ font-technology Variable Варіативні Color Mixer (Shift-click the chip) Змішувач кольорів (Shift+клацання на зразку) Color Mode Колірний режим Color Mode: Колірний режим: + Color Model Колірна модель Color Model: Колірна модель: Color Models Колірні моделі Color Picker Палітра кольорів @@ -570,12 +591,18 @@ font-technology Variable Варіативні Saturation and brightness Насиченість і яскравість Color field Колірне поле {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Вигляд «Коло» + Box View Вигляд «Квадрат» + Box Channel Канал квадрата + Color box Колірний квадрат + Color Wheel Options Параметри колірного кола Color Type: Тип кольору: Color: Колір: Colorize Тонувати Colors Кольори Colors: Кольори: Column Graph Tool Інструмент «Гістограма» + Columns Стовпці Columns: Стовпці: Column… Стовпець… Combine Slices Об’єднати фрагменти @@ -786,6 +813,8 @@ font-technology Variable Варіативні Delete Artboard Видалити монтажну область Delete Artboards Видалити монтажні області Delete Brush Видалити пензель + Delete Color Видалити колір + Restore Generated Table Відновити створену таблицю Delete Character Style Видалити стиль символу Delete Empty Artboards Видалити порожні монтажні області Delete Freeform Point Видалити довільну точку @@ -854,6 +883,7 @@ font-technology Variable Варіативні Direct Selection Tool Інструмент «Пряме виділення» Direction Handles Маркери напряму Disable Auto Add/Delete Вимкнути авто-додавання/видалення + Interpolate Control Points When Moving Anchors Інтерполювати маркери напряму під час переміщення опорних точок Disable Opacity Mask Вимкнути маску непрозорості Discard Відкинути Preserve Зберігати @@ -1047,6 +1077,9 @@ font-technology Variable Варіативні Cap Height Висота великих літер x-Height Висота малих літер ICF Box Рамка ICF + Ascent Підйом + x Height Висота малих літер + Em Box Height Висота кегельного майданчика Show Sample Показати зразок Hide Sample Приховати зразок Max Ascent/Descent Макс. висота/глибина @@ -1079,6 +1112,7 @@ font-technology Variable Варіативні Enable text access for screen readers Дозволити доступ до тексту для програм читання з екрану Enable Touch Gestures Увімкнути сенсорні жести Switch Selection and Drawing Modes Перемкнути режими виділення та малювання + Select Last Selection Tool Вибрати останній інструмент виділення Enable Touch Workspace Включити сенсорне робоче середовище Encoding Кодування Encoding: Кодування: @@ -1259,6 +1293,8 @@ font-technology Variable Варіативні Files Файли Files of a PDF standard can't be password-protected. Файли стандарту PDF не можуть бути захищені паролем. Files of this standard tag their colours with ICC profiles. Файли цього стандарту позначають свої кольори профілями ICC. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Файли цього стандарту позначають свої кольори профілями ICC, крім кольорів CMYK у профілі призначення виведення, які записуються як DeviceCMYK. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. З «Не включати профілі» та призначенням виведення CMYK кожен колір CMYK записується як DeviceCMYK, якщо його не перетворено в призначення CMYK з іншим профілем. Fill Заливка Fill & Stroke Заливка та обведення Fill (X), double-click for the Color Picker Заливка (X), двічі клацніть на палітрі кольорів @@ -1308,6 +1344,8 @@ font-technology Variable Варіативні Reset Tracking and Kerning Скинути трекінг і кернінг Reset Horizontal Scale Скинути масштаб по горизонталі Highlight Font Name Виділити назву шрифту + Highlight Font Size Виділити розмір шрифту + Other… Інший… Highlight Kerning Виділити кернінг Highlight Tracking Виділити трекінг Spacing Інтервал @@ -2016,7 +2054,7 @@ file-filter Templates Шаблони Line Cut Розрізання ліній Line Cut Tool Інструмент «Розрізання ліній» Line Endings: Закінчення ліній: - Line Graph Tool Інструмент «Лінійчаста діаграма» + Line Graph Tool Інструмент «Графік» Line Segment Відрізок Line Segment Tool Інструмент «Відрізок» Line Segment Tool Options Параметри інструменту «Відрізок» @@ -2062,6 +2100,7 @@ file-filter Templates Шаблони Load SVG into Clipboard Завантажити SVG у буфер обміну Load Text into Clipboard Завантажити текст у буфер обміну Local Libraries Локальні бібліотеки + Locate Layer Знайти шар Locate Object Знайти об’єкт Locate Selected Objects Знаходити виділені об’єкти Location Розташування @@ -2256,6 +2295,7 @@ file-filter Templates Шаблони Scatter: Розсіювання: Rotation: Поворот: Rotation relative to: Поворот відносно: + Hue Jitter: Розкид відтінку: Brush Scale Options Параметри масштабування пензля Scale Proportionately Масштабувати пропорційно Stretch to Fit Stroke Length Розтягнути за довжиною обведення @@ -2292,6 +2332,7 @@ file-filter Templates Шаблони Black becomes the stroke color and white stays white. Other colors become tints of the stroke color by their lightness. Чорний стає кольором обведення, а білий залишається білим. Інші кольори стають відтінками кольору обведення, і що світліший колір, то світліший його відтінок. Black and white stay as they are. Dark colors become shades of the stroke color and light colors become tints of it. Чорний залишається чорним, а білий залишається білим. Інші кольори стають тінями кольору обведення, якщо вони темні, і його відтінками, якщо вони світлі. The key color becomes the stroke color. The other colors shift their hue by the same amount and keep their saturation and brightness. Ключовий колір стає кольором обведення. Інші кольори зсуваються по колірному колу на стільки ж, на скільки ключовий колір, і зберігають насиченість та яскравість. + Roundness Округлість Roundness: Округлість: Fixed Фіксований Pressure Натиск @@ -2597,6 +2638,9 @@ file-filter Templates Шаблони Overprint Накладення Overprint and Transparency Flattener Накладання та зведення прозорості Overprint and Transparency Flattener Options Параметри накладання та зведення прозорості + Custom… Користувацькі… + Custom Transparency Flattener Options Користувацькі параметри зведення прозорості + EPS has no alpha transparency, and Overprints sets whether overprints are kept. У EPS немає альфа-прозорості, а параметр «Накладення» визначає, чи зберігаються накладення. Overprint Black… Накладення чорного… Overprint Fill Накладання заливки Overprint Preview Перегляд накладання @@ -2646,6 +2690,13 @@ file-filter Templates Шаблони Pathfinders: Обробка контурів: Paths Контури Path Length Довжина контурів + Grid Size Розмір сітки + Grid Colors Кольори сітки + Flattener Preset Набір зведення + X X + Y Y + Orange Помаранчевий + Purple Фіолетовий Paths: {paths} Anchors: {anchors} Colors: {colors} Контури: {paths} Опорні точки: {anchors} Кольори: {colors} Pattern Візерунок Pattern Editing Редагування візерунка @@ -2683,7 +2734,7 @@ diagnostics ui інтерфейс Perspective Grid Settings Параметри сітки перспективи Perspective Grid Tool Інструмент «Сітка перспективи» Perspective Plane Options… Параметри площини перспективи… - Perspective Selection Tool Інструмент "Виділення в перспективі" + Perspective Selection Tool Інструмент «Виділення в перспективі» Phone 390×844 Телефон 390×844 Picas Піки Pie Graph Tool Інструмент «Кругова діаграма» @@ -2705,6 +2756,7 @@ diagnostics ui інтерфейс Play Current Selection Відтворити поточне виділення Save Actions… Зберегти дії… Load Actions… Завантажити дії… + Replace Actions… Замінити дії… Reset Actions Скинути дії Replace the current actions with the default set? Замінити поточні дії набором за умовчанням? Append adds the default set after the current sets instead. Кнопка «Додати» натомість додає набір за умовчанням після поточних наборів. @@ -2720,6 +2772,10 @@ diagnostics ui інтерфейс Polar Grid Tool Інструмент «Полярна сітка» Polygon Багатокутник Polygon Properties: Властивості багатокутника: + Line Properties: Властивості лінії: + Line Length: Довжина лінії: + Line Angle: Кут лінії: + Constrain Pie Angle Зберігати кут сектора Polygon Tool Інструмент «Багатокутник» Portrait Книжкова Power Saving (integrated) Енергозбереження (вбудована) @@ -2881,6 +2937,9 @@ digits Malayalam Малаялам Real World: Реальний світ: Real-time Drawing and Editing Малювання та редагування у реальному часі Use Monitor Profile for Canvas Використовувати профіль монітора для полотна + Refresh Monitor Profile Оновити профіль монітора +@msg turn on Use Monitor Profile for Canvas first спочатку увімкніть «Використовувати профіль монітора для полотна» +@msg this build doesn't read display profiles ця збірка не читає профілі дисплеїв The canvas is drawn in sRGB. Полотно відображається в sRGB. Canvas display profile: Профіль дисплея для полотна: The system matches the window to the display's colors. Система узгоджує кольори вікна з дисплеєм. @@ -3073,6 +3132,8 @@ digits Malayalam Малаялам Reselect Виділити знову Reset Скинути Reset Bounding Box Скинути обмежувальну рамку + Rotate Bounding Box Повернути обмежувальну рамку + Rotate Bounding Box… Повернути обмежувальну рамку… Reset Envelope Mesh Скинути сітку оболонки Reset Envelope Shape Скинути форму оболонки Reset Essentials Скинути «Основні» @@ -3114,6 +3175,7 @@ digits Malayalam Малаялам Reshape Segment Змінити форму сегмента Reshape Tool Інструмент «Зміна форми» Reshape Type Area Змінити форму текстової області + Resolution Роздільна здатність Resolution: Роздільна здатність: Responsive Адаптивний Restore Відновити @@ -3140,6 +3202,7 @@ digits Malayalam Малаялам The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Колесо миші з натиснутою Cmd/Ctrl прокручує полотно по горизонталі. Dragging sideways on a numeric field's label changes the field's value. Перетягування вбік по підпису числового поля змінює значення поля. A two-finger rotate gesture on a trackpad rotates the canvas view. Жест обертання двома пальцями на трекпаді обертає вигляд полотна. + When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Коли ви переміщуєте опорні точки, кожна крива з одним переміщеним кінцем зберігає форму відносно своїх кінців. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Поки ви утримуєте клавішу інструмента, його вибрано, а після відпускання знову вибирається попередній інструмент. Shows the bounding box while you move the selection or draw a shape. Показує обмежувальну рамку, поки ви переміщуєте виділення або малюєте фігуру. Create Trim Marks draws Japanese-style marks instead of Roman ones. «Створити мітки підрізування» малює мітки в японському стилі замість західних. @@ -3170,6 +3233,29 @@ digits Malayalam Малаялам The unit for East Asian type measurements, which no field uses yet. Одиниця для розмірів східноазіатського тексту, якої поки не використовує жодне поле. When on, a number typed without a unit into a field in picas is read in points. Якщо ввімкнено, число, введене без одиниці в поле в піках, читається в пунктах. With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options. З XML ID назви об’єктів показуються як XML ID у «Шарах», «Змінних» і «Параметрах шару». + The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl. Крок розміру тексту й інтерліньяжу: Cmd/Ctrl+Shift+. і Cmd/Ctrl+Shift+, змінюють розмір на один крок, а разом з Alt — на п’ять; у горизонтальному тексті Alt зі стрілкою вгору або вниз змінює інтерліньяж на один крок, а з Cmd/Ctrl — на п’ять. + The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl. Крок трекінгу й кернінгу в тисячних частках em: у горизонтальному тексті Alt зі стрілкою вліво або вправо змінює кернінг біля курсора або трекінг виділеного тексту на один крок, а з Cmd/Ctrl — на п’ять. + The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. Крок зсуву базової лінії: у горизонтальному тексті Alt і Shift зі стрілкою вгору або вниз зсувають базову лінію на один крок, а з Cmd/Ctrl — на п’ять. + Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. Показує параметри японського та іншого східноазійського тексту на панелях «Символ», «Абзац», «OpenType» і «Гліфи», а також команду «Складені шрифти». + Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. Показує параметри арабського, івритського та індійського тексту на панелях «Символ» і «Абзац», наприклад напрямок абзацу, кашиди й цифри. + The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. Інструменти виділення виділяють текст лише на його базовій лінії, рамці тексту в області або його контурі, а не будь-де всередині його рамки. + Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. Меню шрифтів показують кожен шрифт під англійською назвою; якщо вимкнено, шрифт, що має назву власною мовою, показує цю назву. + New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. Новий текст в області починається з увімкненим авторозміром, тож прямокутна рамка горизонтального тексту збільшується або зменшується у висоту під свій текст. + Font lists and the Type › Font menu show a sample of each font beside its name. Списки шрифтів і меню «Шрифт» показують зразок кожного шрифту поруч із його назвою. + Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on. Зразки шрифтів малюються темним текстом на білому за будь-якої яскравості інтерфейсу; це діє, лише поки ввімкнено попередній перегляд шрифтів у меню. + How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is. Висота кожного рядка в списках полів шрифту, як-от на панелі «Символ», а отже, і розмір кожного зразка. + How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first. Скільки останніх використаних шрифтів, від 1 до 15, показують «Останні шрифти» та списки шрифтів, починаючи з найновішого. + When you change the font or font style of text, characters the new font has no glyph for keep the font they had. Коли ви змінюєте шрифт або накреслення тексту, символи, для яких новий шрифт не має гліфа, зберігають попередній шрифт. + A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export. Рожеве підсвічування на полотні позначає гліфи, замінені функціями OpenType, як-от лігатури; воно не друкується й не експортується. + With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from. З інструментом «Текст» виділення одного символу показує поруч із ним на полотні ряд його альтернативних гліфів для вибору. + A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export. Рожеве підсвічування на полотні позначає текст, намальований замінним шрифтом, бо його шрифту бракує; воно не друкується й не експортується. + New type made with a Type tool starts with placeholder text, selected, so typing replaces it. Новий текст, створений текстовим інструментом, починається з виділеного тексту-заповнювача, який замінюється введеним текстом. + Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list. Якщо на початку абзацу ввести маркер списку, як-от 1. або *, а потім пробіл, абзац стає списком. + Fonts in this folder show in the font menus and can be used without being installed. Шрифти з цієї теки з’являються в меню шрифтів, і їх можна використовувати без встановлення. + Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows. Застосування графічного стилю до тексту прибирає власну заливку чи обведення символів там, де вони є в стилю, щоб було видно фарбу стилю. + Align and Distribute measure point type by the ink of its glyphs instead of its em box. «Вирівняти» й «Розподілити» вимірюють текст із точки за фарбою його гліфів, а не за його em-квадратом. + Align and Distribute measure area type by the ink of its glyphs instead of its frame. «Вирівняти» й «Розподілити» вимірюють текст в області за фарбою його гліфів, а не за його рамкою. + The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box. Обмежувальна рамка й панель «Трансформування» вимірюють текст із точки за фарбою його гліфів, а не за його em-квадратом. Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply. Прив’язує малювання, переміщення й масштабування до поділок сітки, навіть коли сітку приховано; поки параметр увімкнено, «Прив’язати до пікселя» не діє. The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead. Колір невиділених напрямних; монтажна область із «Міткою напрямних» малює свої напрямні кольором мітки. Draws guides as solid lines or as dots, including the guides already in the document. Малює напрямні суцільними лініями або крапками, включно з напрямними, які вже є в документі. @@ -3251,6 +3337,7 @@ digits Malayalam Малаялам Rounded Rectangle Tool Інструмент «Округлений прямокутник» Rounded Rectangle… Округлений прямокутник… Row Size: Розмір рядка: + Rows Рядки Rows: Рядки: Rule: Лінійка: Rulers Лінійки @@ -3427,6 +3514,11 @@ digits Malayalam Малаялам Search commands, tools, panels and effects… Пошук команд, інструментів, панелей та ефектів… No commands match Немає відповідних команд {pos} of {total}: {name} {pos} з {total}: {name} + No menu item Немає пункту меню + Toolbar Панель інструментів + {toolbar}, in the {tool} group {toolbar}, у групі «{tool}» + Tool Інструмент + Command Команда @plural {n} result|{n} results {n} результат|{n} результати|{n} результатів @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} з {n} результату. Продовжуйте вводити, щоб звузити їх.|{shown} з {n} результатів. Продовжуйте вводити, щоб звузити їх.|{shown} з {n} результатів. Продовжуйте вводити, щоб звузити їх. Recent Commands Нещодавні команди @@ -3507,6 +3599,7 @@ digits Malayalam Малаялам Set Slice Rectangle Вказати прямокутник фрагмента Set Tab Stops Задати табуляції Set Text Задати текст + Set the current fill or stroke to the selected color Призначити вибраний колір поточній заливці або обведенню Set the selected color to the current color Призначити поточний колір вибраному кольору Set Zoom Задати масштаб Settings… Параметри… @@ -3630,7 +3723,7 @@ digits Malayalam Малаялам Show Vivid/Muted Показати яскраві/приглушені Show Warm/Cool Показати теплі/холодні Show {kind} Brushes Показати пензлі {kind} - Show/hide plate (Alt-click: only this plate) Показати/приховати пластину (Alt+клацання: тільки цю пластину) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Показати/приховати пластину (Alt+клацання: тільки цю пластину; повторне Alt+клацання: усі пластини) Show: Показати: Shown with the optimised preview. Показано оптимізованим переглядом. Side 1: Сторона 1: @@ -3776,8 +3869,8 @@ effect Points Точки Spread: Розворот: Square Квадрат Squeeze… Стиснення… - Stacked Bar Graph Tool Інструмент "Гістограма з накопиченням" - Stacked Column Graph Tool Інструмент "Гістограма з накопиченням" + Stacked Bar Graph Tool Інструмент «Лінійчата діаграма з накопиченням» + Stacked Column Graph Tool Інструмент «Гістограма з накопиченням» Stair Step Ступінчастий Standard Ligatures Стандартні лігатури Standard Vertical Roman Alignment Стандартне римське вертикальне вирівнювання @@ -3941,7 +4034,7 @@ effect Points Точки Composite Fonts Складені шрифти Export Composite Fonts Експорт складених шрифтів Import Composite Fonts Імпорт складених шрифтів -@msg each font must be {name, parts} кожен шрифт має бути у вигляді {name, parts} +@msg each font must be {{name, parts}} кожен шрифт має бути у вигляді {{name, parts}} @msg unknown key `{k}`; a font takes name and parts невідомий ключ `{k}`; шрифт приймає name і parts @msg each font needs a name кожен шрифт повинен мати назву @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` не може бути назвою складеного шрифту (від 1 до {COMPOSITE_NAME_MAX} символів, без керівних символів) @@ -3954,7 +4047,7 @@ effect Points Точки @msg two composite fonts are named `{_1}` два складені шрифти мають назву `{_1}` @msg `{_1}` is the name of an installed font `{_1}` є назвою встановленого шрифту @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2} використовує `{font}`, а це складений шрифт -@msg give fonts: [{name, parts}…] вкажіть fonts: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] вкажіть fonts: [{{name, parts}}…] @msg path is empty path порожній @msg fonts must be a list of composite fonts fonts має бути списком складених шрифтів @msg names must be strings names мають бути рядками @@ -4037,6 +4130,13 @@ effect Points Точки Thumbnail View Мініатюри Thumbnails: Мініатюри: Tile Плитка + Tile All Vertically Усі плиткою вертикально + Tile All Horizontally Усі плиткою горизонтально + 2-Up Layout Макет на 2 + 3-Up Layout Макет на 3 + 4-Up Layout Макет на 4 + 6-Up Layout Макет на 6 + Arrange Documents Упорядкувати документи Tile Edge Color Колір краю плитки Tile Edge Color… Колір краю плитки… Tile Full Pages Плитка цілих сторінок @@ -4232,6 +4332,8 @@ effect Points Точки V Spacing: Інтервал по вертикалі: V: В: Variable Width Profile Профіль змінної ширини + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Пензель обведення зберігає власний розмір, тому профіль ширини його не змінює. Щоб використати профіль, заберіть пензель. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Пензель обведення зберігає власний розмір, тому профіль ширини його не змінює. Щоб використати профіль, заберіть пензель. Variables Змінні New Variable Нова змінна Delete Variable Видалити змінну @@ -4296,7 +4398,7 @@ effect Points Точки Vertical: По вертикалі: Very High Дуже висока View Перегляд - View Artboard Only Перегляд лише монтажної області + View Artboard Contents Only Перегляд лише вмісту монтажної області View Opacity Mask Перегляд маски непрозорості View PDF after saving Переглядати PDF після збереження View {n} Вигляд {n} @@ -4349,7 +4451,7 @@ effect Points Точки Zoom In Збільшити Zoom Out Зменшити Zoom to Selection Масштаб виділення - Zoom Tool Інструмент «Масштаб» + Zoom Tool Інструмент «Лупа» Zoom with Mouse Wheel Масштабувати колесом миші Scroll Sideways with Cmd/Ctrl + Wheel Прокручувати по горизонталі колесом із Cmd/Ctrl Scrub Numeric Fields by Dragging Змінювати числові поля перетягуванням @@ -4511,6 +4613,7 @@ imageTrace Outline Контур Bevel Скіс Offset Зміщення Axis Вісь + Axis Angle Кут осі axis Horizontal Горизонтальна axis Vertical Вертикальна axis Both Обидві @@ -4582,6 +4685,13 @@ axis Both Обидві Show External Script Warning Показувати попередження про зовнішні скрипти A Script Is Running Виконується скрипт Script Alert Повідомлення скрипту + Script File Access Доступ скрипту до файлів + The script asks to read a file you choose. Скрипт просить дозволу прочитати вибраний вами файл. + The script asks to read and write a file you choose. Скрипт просить дозволу читати й записувати вибраний вами файл. + The script asks to read and write a folder you choose, with everything in it. Скрипт просить дозволу читати й записувати вибрану вами папку з усім її вмістом. + Allow Once Дозволити один раз + Always Allow This Script Завжди дозволяти цей скрипт + Deny Заборонити A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Скрипт може змінювати відкриті документи й записувати файли за допомогою команд, які виконує. Запускайте лише ті скрипти, яким довіряєте. Do not show this warning again Більше не показувати це попередження Stop the script and undo what it did? Then quit again. Зупинити скрипт і скасувати його зміни? Потім вийдіть ще раз. @@ -4598,6 +4708,8 @@ axis Both Обидві @msg the script is no longer in the Scripts folder скрипт більше не міститься в папці Scripts Some scripts were not listed Деякі сценарії не показано The Scripts folder cannot be read Не вдалося прочитати папку Scripts + Loading scripts… Завантаження сценаріїв… + The Scripts folder is still being read Папка Scripts ще читається @msg the script's run is no longer available виконання скрипта більше не доступне @msg a failed command changed undo steps that could not be put back, so the script was stopped невдала команда змінила кроки скасування, які не вдалося відновити, тому скрипт зупинено @msg a recovery copy could not be written, so the script was not run не вдалося записати копію для відновлення, тому скрипт не виконано @@ -4610,8 +4722,6 @@ axis Both Обидві @msg Script file could not be read Не вдалося прочитати файл скрипта @msg Script folder has more than 2,048 entries Тека скрипта має понад 2048 елементів @msg Script file open mode must be r, w, e or a Режим відкриття файлу скрипта має бути r, w, e або a -@msg Script file writing is not available Запис файлів скрипта недоступний -@msg Script file dialogs are not available Діалогові вікна файлів скрипта недоступні @msg Script files cannot be opened in another application Файли скрипта не можна відкрити в іншому застосунку @msg Script file access is unavailable on the web Доступ до файлів скрипта у вебверсії недоступний @msg Script has 256 files open Скрипт має 256 відкритих файлів @@ -4728,6 +4838,27 @@ liquify-list-end {0}, {1} {0} і {1} @msg there is no script engine named {name} рушія скриптів з назвою {name} немає @msg Running a script Виконується скрипт @msg Copied the script report Звіт про сценарій скопійовано +@msg Script file access denied: {path} Доступ скрипту до файлів заборонено: {path} +@msg Script file access to the app's own folders is not allowed Скрипту не дозволено доступ до власних папок застосунку +@msg Script file cannot encode the text Файл скрипту не може закодувати текст +@msg Script file could not be written Не вдалося записати файл скрипту +@msg Script file dialogs need a person to answer them Для відповіді на файлові діалоги скрипту потрібна людина +@msg Script file is not open for writing Файл скрипту не відкрито для запису +@msg Script file name is already in use Ім’я файлу скрипту вже використовується +@msg Script file name must be a name without a folder Ім’я файлу скрипту має бути іменем без папки +@msg Script file permission can be kept only for a script run from a file Дозвіл на файли можна зберегти лише для скрипту, запущеного з файлу +@msg Script file permission could not be saved Не вдалося зберегти дозвіл скрипту на файли +@msg Script folder is not empty Папка скрипту не порожня +@msg Script files cannot make aliases Файли скрипту не можуть створювати псевдоніми +@msg Script file hidden setting cannot be changed Не можна змінити параметр прихованості файлу скрипту +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: файловий діалог не можна відкрити всередині зворотного виклику вбудованої функції, гетера, перетворення або файлу, який виконує $.evalFile; викличте його з власного коду скрипту +@msg the script wrote more file data than one run may write (32 MiB) скрипт записав більше даних файлів, ніж може записати один запуск (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` для файлового діалогу скрипту має бути одним із: once, always, deny, stop +@msg choose a file or folder first, or deny спершу виберіть файл або папку чи відмовте +@msg the script file permissions could not be saved: {e} не вдалося зберегти дозволи скриптів на файли: {e} +@msg this script's file access can be allowed only once доступ цього скрипту до файлів можна дозволити лише один раз +@msg Only the person at the keyboard can allow a script's file access Дозволити скрипту доступ до файлів може лише людина за клавіатурою +@msg A script is given at most 2,048 files: the files picked after them were left out Скрипт отримує щонайбільше 2 048 файлів: файли, вибрані після них, пропущено @msg Copied the link info Відомості про зв’язок скопійовано @msg Corners edits the corners of a path «Кути» редагує кути контуру @msg Couldn't copy to the system clipboard: {e} Не вдалося скопіювати до системного буфера обміну: {e} @@ -4803,6 +4934,7 @@ liquify-list-end {0}, {1} {0} і {1} @msg Saved {path} Збережено: {path} @msg Select text or click into text with the Type tool to insert glyphs Виділіть текст або клацніть всередині тексту інструментом «Текст», щоб вставити гліфи @msg Shape Builder: no region under the pointer Створення фігур: під вказівником немає області +@msg Shape Builder: select all paths you want to merge Створення фігур: виділіть усі контури, які потрібно об’єднати @msg Shape Builder: select paths or compound paths Створення фігур: виділіть контури або складені контури @msg Show All Hidden Attributes: nothing is hidden Показати всі приховані атрибути: нічого не приховано @msg Split Into Grid: select paths large enough for the grid Поділ на сітку: виділіть контури, досить великі для сітки @@ -4858,6 +4990,8 @@ liquify-list-end {0}, {1} {0} і {1} @msg `{min_key}` is greater than `{max_key}` `{min_key}` більше за `{max_key}` @msg give at least one of `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` укажіть принаймні один із параметрів `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` має бути grayscale, rgb, hsb, cmyk або websafe +@msg `view` must be wheel or box `view` має бути wheel або box +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` має бути hue, saturation, brightness, red, green або blue @msg `{k}` must be [x, y] `{k}` має бути [x, y] @msg `{name}` has no options `{name}` не має параметрів @msg `{name}` is a built-in workspace; choose another name `{name}` - вбудоване робоче середовище; виберіть інше ім’я @@ -4946,6 +5080,7 @@ liquify-list-end {0}, {1} {0} і {1} @msg bad trailer неприпустимий трейлер @msg balance must be between 0 and 100 balance має бути від 0 до 100 @msg batch step {_1} (`{id}`) failed: {e} крок пакету {_1} (`{id}`) не виконано: {e} +@msg action step {_1} (`{id}`) failed: {reason} крок дії {_1} (`{id}`) не виконано: {reason} @msg brightness must be dark|mediumDark|mediumLight|light brightness має бути dark|mediumDark|mediumLight|light @msg can't encode the document: {0} не вдалося закодувати документ: {0} @msg can't parse shortcut `{c}` не вдалося розібрати поєднання `{c}` @@ -4965,6 +5100,7 @@ liquify-list-end {0}, {1} {0} і {1} @msg choose a folder to export to виберіть папку для експорту @msg choose a location for the package виберіть розташування для пакета @msg clipboard is empty буфер обміну порожній +@msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: у колірній таблиці має залишитися принаймні один колір @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` не є кольором, наприклад "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: не більше {MAX_TABLE} кольорів @msg command `{0}` is not available right now: {1} команда `{0}` зараз недоступна: {1} @@ -5032,9 +5168,15 @@ liquify-list-end {0}, {1} {0} і {1} @msg no PNG encoder немає кодера PNG @msg no active document немає активного документа @msg no active perspective plane немає активної площини перспективи +@msg the perspective grid is hidden сітку перспективи приховано +@msg Automatic Plane Positioning is off: turn on anchorPoint or gridlineIntersection (perspective.widget.options) Автоматичне розміщення площини вимкнено: увімкніть anchorPoint або gridlineIntersection (perspective.widget.options) +@msg anchorPoint must be true or false anchorPoint має бути true або false +@msg gridlineIntersection must be true or false gridlineIntersection має бути true або false +@msg tolerance must be 0 or more tolerance має бути 0 або більше +@msg give `at` or `clear`, not both укажіть `at` або `clear`, але не обидва @msg no anchor points selected опорні точки не виділені -@msg `points` must be three [x, y] pairs of numbers `points` має містити три пари чисел [x, y] -@msg direct-select three anchor points, or give `points` виділіть три опорні точки прямим виділенням або задайте `points` +@msg `points` must be two or three [x, y] pairs of numbers `points` має містити дві або три пари чисел [x, y] +@msg direct-select two or three anchor points, or give `points` виділіть дві або три опорні точки прямим виділенням або задайте `points` @msg no circle passes through these points: two are the same or all three lie on one line через ці точки не проходить жодне коло: дві точки збігаються або всі три лежать на одній прямій @msg no app to open files here тут немає програми для відкриття файлів @msg no artboard немає монтажної області @@ -5136,6 +5278,9 @@ liquify-list-end {0}, {1} {0} і {1} @msg no such user library такої користувацької бібліотеки немає @msg no such view такого виду немає @msg no such width point такої точки ширини немає +@msg `single` must be `incoming` or `outgoing` `single` має бути `incoming` або `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` і `outIndex` мають бути двома половинами однієї розривної точки ширини +@msg a discontinuous width point keeps its place розривна точка ширини зберігає своє місце @msg no swatch `{name}` немає зразка `{name}` @msg no swatch library `{l}` (see swatch.library.list) немає бібліотеки зразків `{l}` (див. swatch.library.list) @msg no symbol instances selected екземпляри символів не виділені @@ -5395,6 +5540,13 @@ liquify-list-end {0}, {1} {0} і {1} @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} більше ніж {MAX_CSV_ROWS} наборів даних: «Імпортувати набори даних» читає не більше {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} більше ніж {MAX_CSV_COLS} змінних: «Імпортувати набори даних» читає не більше {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} змінні, що не є текстовими, пропущено: {kinds} +variable-kind Visibility Видимість +variable-kind Linked File Пов’язаний файл +variable-kind Graph Data Дані діаграми +variable-kind Unknown Невідомо +variable-list-two {0}, {1} {0} і {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} і {1} @msg a new document won't read these variables back with their kind: {names} новий документ не прочитає ці змінні назад з їхнім видом: {names} @msg a new document refuses this file because of these variables: {names} новий документ відхиляє цей файл через ці змінні: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them заголовок `{header}` для `{name}` буде прочитано як змінну `{other}`: перейменуйте одну з них @@ -5420,6 +5572,8 @@ liquify-list-end {0}, {1} {0} і {1} @msg {label}: lost track of a shape's style {label}: втрачено стиль фігури @msg {label}: select paths {label}: виділіть контури @msg {label}: select paths, compound paths, groups or text {label}: виділіть контури, складені контури, групи або текст +@msg a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first лінія чи інший відкритий контур, що не охоплює площі, не змінює форми результату; щоб включити його, спершу застосуйте до нього Об’єкт › Контур › Обвести обведення +@msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first {label} дав порожній результат: лінія чи інший відкритий контур не охоплює площі; щоб включити його, спершу застосуйте до нього Об’єкт › Контур › Обвести обведення @msg {label}… {label}… @msg {name}: CRC mismatch {name}: розбіжність CRC @msg {name}: no local header {name}: немає локального заголовка @@ -5446,6 +5600,9 @@ liquify-list-end {0}, {1} {0} і {1} @msgplural Discarded {n} recovered document|Discarded {n} recovered documents Скасовано {n} відновлений документ|Скасовано {n} відновлені документи|Скасовано {n} відновлених документів @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them Відновлено {n} документ: збережіть його, щоб залишити|Відновлено {n} документи: збережіть їх, щоб залишити|Відновлено {n} документів: збережіть їх, щоб залишити @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} Відкрито з {n} приміткою: {first}|Відкрито з {n} примітками: {first}|Відкрито з {n} примітками: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Скопійовано з {n} приміткою: {first}|Скопійовано з {n} примітками: {first}|Скопійовано з {n} примітками: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Вирізано з {n} приміткою: {first}|Вирізано з {n} примітками: {first}|Вирізано з {n} примітками: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Зображення трасовано з {n} приміткою: {first}|Зображення трасовано з {n} примітками: {first}|Зображення трасовано з {n} примітками: {first} @msgplural {notice}. Opened with {n} note: {first}|{notice}. Opened with {n} notes: {first} {notice}. Відкрито з {n} приміткою: {first}|{notice}. Відкрито з {n} примітками: {first}|{notice}. Відкрито з {n} примітками: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} Збережено: {path} з {n} приміткою: {first}|Збережено: {path} з {n} примітками: {first}|Збережено: {path} з {n} примітками: {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first Вбудовано {n} зображення; відсутніх: {missing}. Спочатку відновіть їхні зв’язки|Вбудовано {n} зображення; відсутніх: {missing}. Спочатку відновіть їхні зв’язки|Вбудовано {n} зображень; відсутніх: {missing}. Спочатку відновіть їхні зв’язки @@ -5472,6 +5629,8 @@ liquify-list-end {0}, {1} {0} і {1} @msg All colors are within the CMYK gamut Усі кольори входять у колірне охоплення CMYK @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} колір виходить за межі колірного охоплення CMYK|{n} кольори виходять за межі колірного охоплення CMYK|{n} кольорів виходять за межі колірного охоплення CMYK @msg Unembedded to {_1} Вилучено у {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} Вилучено {n} зображення у {folder}|Вилучено {n} зображення у {folder}|Вилучено {n} зображень у {folder} +@msg every numbered name for {name} is taken in that folder усі нумеровані імена для {name} уже зайняті в цій папці @msg Reset {_1} Скинуто: {_1} @msg Sent to {_1} Відправлено до {_1} @msg {_1} files {_1} файлів @@ -5487,6 +5646,8 @@ liquify-list-end {0}, {1} {0} і {1} @msg Reload the page to go on (changes not saved yet may be lost). Перезавантажте сторінку, щоб продовжити (незбережені зміни можуть бути втрачені). @msg tool (a tool id) is required потрібно tool (ідентифікатор інструменту) @msg {tool} isn't in a toolbar group of several tools {tool} не входить до групи панелі інструментів з кількох інструментів +@msg Presentation Mode hides the toolbars: change the screen mode to show them Режим презентації приховує панелі інструментів: щоб показати їх, змініть режим екрану +@msg Tab has hidden the toolbars: press Tab to show them клавіша Tab приховала панелі інструментів: щоб показати їх, натисніть Tab @msg onto must name a panel floating in another group onto має називати панель, що плаває в іншій групі @msg below and above must name a panel floating in another group below і above мають називати панель, що плаває в іншій групі @msg give only one of onto, below and above вкажіть лише один із onto, below і above @@ -5601,6 +5762,9 @@ liquify-list-end {0}, {1} {0} і {1} @msg automation path rejected: outside the read root {root}: {path} шлях автоматизації відхилено: поза кореневою папкою для читання {root}: {path} @msg automation path rejected: outside the read roots {roots}: {path} шлях автоматизації відхилено: поза кореневими папками для читання {roots}: {path} @msg a linked JavaScript file is outside the read roots зв’язаний файл JavaScript перебуває поза кореневими папками для читання +@msg a linked image file is outside the read roots зв’язаний файл зображення перебуває поза кореневими папками для читання +@msg a linked file's export folder is outside the read roots папка експорту зв’язаного файлу перебуває поза кореневими папками для читання +@msg a linked file's editing data can't be read to check it against the read roots не вдається прочитати дані редагування зв’язаного файлу, щоб звірити їх із кореневими папками для читання @msg automation path rejected: outside the write root {root}: {path} шлях автоматизації відхилено: поза кореневою папкою для запису {root}: {path} @msg automation path rejected: outside the write roots {roots}: {path} шлях автоматизації відхилено: поза кореневими папками для запису {roots}: {path} @msg automation path rejected: path is empty шлях автоматизації відхилено: шлях порожній @@ -5826,6 +5990,7 @@ lighting Light Світло @msg missing panel layout Відсутнє розташування панелей @msg unsupported native docking operation Непідтримувана власна операція прикріплення Linux Display Server Дисплейний сервер Linux + Low-Latency Drawing Малювання з низькою затримкою X11 (XWayland) When a Pen Is Attached X11 (XWayland), коли підключено перо If a drawing tablet's pen doesn't draw, choose an X11 (XWayland) option. Якщо перо графічного планшета не малює, виберіть варіант X11 (XWayland). X11 (XWayland) X11 (XWayland) @@ -5880,6 +6045,7 @@ lighting Light Світло Cove Викружка Depth Глибина Front Спереду + Side Збоку Isometric Bottom Ізометрія знизу Isometric Left Ізометрія ліворуч Isometric Right Ізометрія праворуч @@ -5974,7 +6140,7 @@ lighting Light Світло @msg each of `{GRAPHICS}` must be an object кожен елемент `{GRAPHICS}` має бути об’єктом @msg `{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}` елементи `{GRAPHICS}` приймають symbol, face, x, y, scale і rotation, а не `{k}` @msg each of `{GRAPHICS}` needs `symbol`, the name of a symbol кожному елементу `{GRAPHICS}` потрібен `symbol`, назва символу -@msg `{GRAPHICS}` face must be front or back face у `{GRAPHICS}` має бути front або back +@msg `{GRAPHICS}` face must be front, back or side face у `{GRAPHICS}` має бути front, back або side @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} у `{GRAPHICS}` має бути числом від {lo} до {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` має бути масивом @msg Graphics map onto the Plane, Extrude and Revolve object types Графіка наноситься на об’єкти типів «Площина», «Видавлювання» та «Обертання» @@ -6990,6 +7156,12 @@ anchor Points: Точки: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` має бути "free", "keepAngles" або "symmetric" @msg `{key}` must be [x, y] `{key}` має бути [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Конвертер одиниць + Unit Converter Panel Панель «Конвертер одиниць» + Copy with Units Копіювати з одиницями + From Selection З виділення + # Color Effects add-on: Select by Color Kind. Select by Color Kind Виділити за типом кольору Objects with Spot Colors Об’єкти з плашковими кольорами @@ -7215,6 +7387,14 @@ breakText Glyphs Гліфи Remove Gaps Прибрати проміжки @msg that makes too many pieces (at most 100000): make the dashes longer так вийде забагато частин (не більше 100000): подовжте штрихи @msg select paths, or segments, to divide виділіть контури або сегменти для розділення +# Path Precision Tools add-on: Smooth Bridge. + Smooth Bridge… Плавний міст… + Smooth Bridge Плавний міст + Keep Originals Зберегти оригінали +@msg select two circles to bridge виділіть два кола для з’єднання +@msg one circle is inside the other одне коло всередині іншого +@msg the circles are too far apart for this radius: raise the radius кола надто далеко одне від одного для цього радіуса: збільште радіус +@msg the circles are too far apart for this radius кола надто далеко одне від одного для цього радіуса # Path Precision Tools add-on: Common Tangents. Common Tangents… Спільні дотичні… Common Tangents Спільні дотичні @@ -7761,6 +7941,14 @@ breakText Glyphs Гліфи @msg `answers` has more than {MAX_ANSWERS} answers `answers` містить понад {MAX_ANSWERS} відповідей @msg `answers` is larger than 1 MiB `answers` більший за 1 МіБ @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` призначений лише для запуску, у якому немає кого запитати: у застосунку людина сама відповідає на кожне діалогове вікно +@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` має бути цілим числом від 1 до {_1} +@msg `args{place}` is nested more than 64 levels deep `args{place}` має вкладеність понад 64 рівні +@msg `args` must be an object `args` має бути об’єктом +@msg `args` is larger than 1 MiB `args` більший за 1 МіБ +@msg `path` is empty параметр `path` порожній +@msg `installed` takes a `path`, not a `source` `installed` приймає `path`, а не `source` +@msg `path` must name a .js or .jsx file `path` має вказувати на файл .js або .jsx +@msg give exactly one of `path` and `source` укажіть рівно одне з: `path`, `source` @msg `answers` must be a list of answers `answers` має бути списком відповідей @msg `artboard` must be the index of an artboard of the document `artboard` має бути індексом монтажної області документа @msg `artboardsAt` must be [x, y] `artboardsAt` має бути [x, y] @@ -7912,7 +8100,7 @@ breakText Glyphs Гліфи @msg `scale` must be a number from 0.001 to 1000 `scale` має бути числом від 0.001 до 1000 @msg `scale` must be a number in (0, 100] `scale` має бути числом у діапазоні (0, 100] @msg `scope.{key}` must be a non-empty array `scope.{key}` має бути непорожнім масивом -@msg `scope` must be "document", {artboards} or {layers} `scope` має бути "document", {artboards} або {layers} +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` має бути "document", {{artboards: [index, …]}} або {{layers: [id, …]}} @msg `scope` must be "selection" or "document", not {other} `scope` має бути "selection" або "document", а не {other} @msg `script` must be a string `script` має бути рядком @msg `seriesIndexes` is a non-empty list of series indexes `seriesIndexes` — це непорожній список індексів рядів @@ -7988,6 +8176,8 @@ breakText Glyphs Гліфи @msg `{f}` is the copy of a document open now `{f}` — це копія документа, відкритого зараз @msg `{id}` is no writable format (see document.formats) `{id}` не є форматом, доступним для запису (див. document.formats) @msg `{id}` isn't a loaded library `{id}` не є завантаженою бібліотекою +@msg `{file}` has no swatches of its own у `{file}` немає власних зразків +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold у `{_1}` є зразки візерунків, яких файл .vcswatches не може містити @msg `{key}` has no colours `{key}` не містить кольорів @msg `{key}` holds more than {MAX_EDIT_WORDS} words `{key}` містить понад {MAX_EDIT_WORDS} слів @msg `{key}` is a design name `{key}` — це назва дизайну @@ -8278,7 +8468,13 @@ breakText Glyphs Гліфи @msg colorModel must be {own} (the document's mode), grayscale or bitmap colorModel має бути {own} (режим документа), grayscale або bitmap @msg colour groups can't go into colour groups групи кольорів не можна поміщати в групи кольорів @msg colour, mode and spot apply to solid-colour swatches only colour, mode і spot застосовуються лише до зразків суцільного кольору -@msg column {column}: `{cell}` is a `%` column of graph data files, which are not read стовпець {column}: `{cell}` — це стовпець `%` файлів даних діаграм, які не читаються +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path рядок {line}, стовпець {column}: файл даних діаграми `{path}` для `{var}` задано відносним шляхом: укажіть `base` або абсолютний шлях +@msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} рядок {line}, стовпець {column}: не вдається прочитати файл даних діаграми для `{var}`: {e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` isn't followed: {r} рядок {line}, стовпець {column}: перехід до файлу даних діаграми `{path}` для `{var}` не виконується: {r} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes рядок {line}, стовпець {column}: файл даних діаграми `{path}` для `{var}` більший за {MAX_GRAPH_DATA_FILE} байтів +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes рядок {line}, стовпець {column}: файл даних діаграми `{path}` для `{var}` дає значення діаграми довше за {MAX_GRAPH_CSV} байтів +@msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all рядок {line}, стовпець {column}: файли даних діаграм разом містять понад {MAX_GRAPH_FILES_TOTAL} байтів +@msg `base` is empty `base` порожнє @msg column {column}: `{cell}` names `{name}`, which is a {_1} variable стовпець {column}: `{cell}` указує `{name}`, а це змінна типу {_1} @msg column {column}: `{cell}` names no variable стовпець {column}: `{cell}` не вказує жодної змінної @msg column {column}: the variable name is longer than {MAX_NAME} characters стовпець {column}: ім’я змінної довше за {MAX_NAME} символів @@ -8289,6 +8485,7 @@ breakText Glyphs Гліфи @msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes складені фігури приймають контури, складені контури, групи, складені фігури, текст, переходи й оболонки @msg compound {_1} must contain exactly one open path to join складений об’єкт {_1} має містити рівно один відкритий контур для з’єднання @msg connect needs a path other than the one extended для connect потрібен контур, відмінний від того, що продовжується +@msg connect needs extend для connect потрібен extend @msg connect needs id для connect потрібен id @msg connect path has no open end контур для connect не має відкритого кінця @msg continuation must be an array of path chunks continuation має бути масивом частин контуру @@ -8800,7 +8997,7 @@ breakText Glyphs Гліфи @msg nothing to print: every artboard picked is blank немає чого друкувати: усі вибрані монтажні області порожні @msg nothing to print: the document has no art that prints немає чого друкувати: документ не містить графіки, яка друкується @msg nothing to repeat немає чого повторювати -@msg numbers out of order in {_1} quantifier числа в неправильному порядку у квантифікаторі {_1} +@msg numbers out of order in {{}} quantifier числа в неправильному порядку у квантифікаторі {{}} @msg object is not a path об’єкт не є контуром @msg object transparency cannot be sampled onto highlighted characters; disable Transparency in Eyedropper Options or select the whole object прозорість об’єкта не можна перенести на виділені символи; вимкніть «Прозорість» у параметрах піпетки або виділіть увесь об’єкт @msg object {_1} can't be set as point type об’єкт {_1} не можна зробити текстом із точки @@ -9157,7 +9354,7 @@ breakText Glyphs Гліфи @msg the page has no area сторінка не має площі @msg the page's type in an unread object's box isn't in its page art тексту сторінки в рамці непрочитаного об’єкта немає в графіці цієї сторінки @msg the paint behind the proxy is not a gradient фарба за індикатором не є градієнтом -@msg the paint is not a freeform gradient (apply one with paint.editGradient {kind}) фарба не є довільним градієнтом (застосуйте його за допомогою paint.editGradient {kind}) +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) фарба не є довільним градієнтом (застосуйте його за допомогою paint.editGradient {{kind: "freeform"}}) @msg the parameters or body do not form one function параметри або тіло не утворюють одну функцію @msg the parent must be a layer or sublayer батьківським елементом має бути шар або підшар @msg the pasted SVG filter {name} draws differently from the document's filter of that name, and no free name fits it вставлений фільтр SVG {name} малює інакше, ніж фільтр документа з таким іменем, а вільного імені для нього немає @@ -9526,3 +9723,13 @@ breakText Glyphs Гліфи @msg A panel is not joined to the rest by a crease. Панель не з’єднана з рештою жодною лінією біговки. @msg A fold line is on a non-printing layer. Лінія згину лежить на шарі, що не друкується. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Панелі: {panels}, шарніри: {hinges}, помилки: {errors}, попередження: {warnings} + Fold Preview Перегляд згину + Fold Згин + Show Fold Lines Показати лінії згину + Three-Quarter Три чверті + Open a document to preview its folded shape. Відкрийте документ, щоб переглянути його у складеному вигляді. +@msg Check the fold lines first. Спершу перевірте лінії згину. +@msg Panels: {panels}, hinges: {hinges} Панелі: {panels}, шарніри: {hinges} +@msg Other blanks not shown: {count} Інші розгортки не показано: {count} +@msg A joint does not close by {gap} pt. Стик не змикається на {gap} pt. +@msg Two panels pass through each other. Дві панелі проходять одна крізь одну. diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 519c5d8f0d..bb00f747b8 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -128,6 +128,7 @@ Add Anchor Point Thêm điểm neo Add Anchor Point Tool Công cụ Thêm điểm neo Add Anchor Points Thêm các điểm neo + Add Around Thêm xung quanh đối tượng Add Content Thêm nội dung Add Effect Thêm hiệu ứng Add Font Files Thêm tệp phông chữ @@ -156,7 +157,11 @@ Add Used Colors Thêm các màu đã dùng Additional Fonts Folder Thư mục phông bổ sung Additional Plug-ins Folder Thư mục plug-in bổ sung + Plug-in Instruction Budget Ngân sách lệnh của plug-in Adjust Adjoining Width Points Điều chỉnh các điểm chiều rộng kề nhau + Incoming Phía vào + Outgoing Phía ra + Single Width Only Chỉ một chiều rộng Adjust Color Balance… Điều chỉnh cân bằng màu… Adjust Colors Điều chỉnh màu sắc Adjust Options: Tùy chọn điều chỉnh: @@ -213,6 +218,7 @@ Angled Strokes… Nét xiên góc… Angles Các góc Animated Zoom Thu phóng có hiệu ứng + Anti Alias Khử răng cưa Anti-alias Khử răng cưa Anti-Alias Khử răng cưa Anti-alias Rasters Khử răng cưa ảnh raster @@ -312,6 +318,7 @@ font-technology Variable Biến thiên Average Trung bình Average… Trung bình… Axis Trục + Axis Angle Góc trục Axis side Mặt trục Axis: Trục: Back Sau @@ -416,6 +423,12 @@ font-technology Variable Biến thiên Brush Definition Định nghĩa cọ Brush Libraries Thư viện cọ Brush Options… Tùy chọn cọ… + Options of Selected Object… Tùy chọn của đối tượng đã chọn… + Options of Selected Object Tùy chọn của đối tượng đã chọn +@msg no path painted with a brush is selected chưa chọn đường được vẽ bằng cọ +@msg the selected paths are painted with brushes of different types các đường đã chọn được vẽ bằng các loại cọ khác nhau +@msg give `params` or `reset`, not both chỉ cung cấp `params` hoặc `reset`, không cả hai +@msg a bristle brush has no options of its own on a path cọ lông không có tùy chọn riêng trên một đường Brush Scale Options Tùy chọn tỷ lệ cọ Brush Strokes Nét cọ Brushes Cọ @@ -492,6 +505,12 @@ font-technology Variable Biến thiên Character options Tùy chọn ký tự Paragraph options Tùy chọn đoạn văn Character Rotation Xoay ký tự + Chinese Big 5 Tiếng Trung Big 5 + Cyrillic Chữ Kirin + Greek Tiếng Hy Lạp + Turkish Tiếng Thổ Nhĩ Kỳ + Baltic Vùng Baltic + Central European Trung Âu Character Set: Bộ ký tự: Character Style Kiểu ký tự Character Style Options Tùy chọn kiểu ký tự @@ -557,6 +576,8 @@ font-technology Variable Biến thiên Choose the file to relink each linked file to. Files with the size and contents saved with the link come first. Chọn tệp để liên kết lại từng tệp liên kết. Các tệp có kích thước và nội dung đã lưu cùng liên kết được hiển thị trước. Choose… Chọn… Circle Hình tròn + Circle Tool Công cụ Hình tròn + Circle too large Hình tròn quá lớn Classic Cổ điển Classic Defaults Mặc định cổ điển Clean Up… Dọn dẹp… @@ -648,6 +669,7 @@ font-technology Variable Biến thiên Color Mixer (Shift-click the chip) Trộn màu (Shift-bấm chip màu) Color Mode Chế độ màu Color Mode: Chế độ màu: + Color Model Mô hình màu Color Model: Mô hình màu: Color Models Các mô hình màu Color Picker Bộ chọn màu @@ -668,6 +690,11 @@ font-technology Variable Biến thiên Saturation and brightness Độ bão hòa và độ sáng Color field Vùng chọn màu {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Hiển thị bánh xe + Box View Hiển thị hộp + Box Channel Kênh của hộp + Color box Hộp màu + Color Wheel Options Tùy chọn bánh xe màu Color Type: Loại màu: Color: Màu: Colorization Tô màu @@ -676,6 +703,7 @@ font-technology Variable Biến thiên Colors: Màu sắc: Column Graph Tool Công cụ Biểu đồ cột Column Width: Chiều rộng cột: + Columns Cột Columns: Cột: Column… Cột… Combine Slices Kết hợp lát cắt @@ -915,6 +943,8 @@ font-technology Variable Biến thiên Delete Artboard Xóa bảng vẽ Delete Artboards Xóa các bảng vẽ Delete Brush Xóa cọ + Delete Color Xóa màu + Restore Generated Table Khôi phục bảng đã tạo Delete Character Style Xóa kiểu ký tự Delete Data Set Xóa tập dữ liệu Delete Design Xóa thiết kế @@ -1000,6 +1030,7 @@ font-technology Variable Biến thiên Direction Handles Tay nắm hướng Direction: Hướng: Disable Auto Add/Delete Tắt tự động thêm/xóa + Interpolate Control Points When Moving Anchors Nội suy tay nắm hướng khi di chuyển điểm neo Disable Opacity Mask Tắt mặt nạ độ mờ Discard Loại bỏ Preserve Bảo lưu @@ -1249,6 +1280,7 @@ font-technology Variable Biến thiên Enable text access for screen readers Bật truy cập văn bản cho trình đọc màn hình Enable Touch Gestures Bật cử chỉ cảm ứng Switch Selection and Drawing Modes Chuyển giữa chế độ chọn và vẽ + Select Last Selection Tool Chọn công cụ chọn dùng gần nhất Enable Touch Workspace Bật không gian làm việc cảm ứng Encoding Mã hóa Encoding: Mã hóa: @@ -1451,6 +1483,8 @@ digits Malayalam Malayalam Files Tệp Files of a PDF standard can't be password-protected. Tệp theo tiêu chuẩn PDF không thể bảo vệ bằng mật khẩu. Files of this standard tag their colours with ICC profiles. Tệp theo tiêu chuẩn này gắn thẻ màu bằng hồ sơ ICC. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Tệp theo tiêu chuẩn này gắn thẻ màu bằng hồ sơ ICC, trừ các màu CMYK trong hồ sơ mục đích đầu ra, được ghi dưới dạng DeviceCMYK. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. Với “Không bao gồm hồ sơ” và mục đích đầu ra CMYK, mọi màu CMYK được ghi dưới dạng DeviceCMYK, trừ khi được chuyển đổi sang đích CMYK của hồ sơ khác. Fill Tô Fill & Stroke Tô & Nét Fill (X), double-click for the Color Picker Tô (X), bấm đúp để mở Bộ chọn màu @@ -1632,6 +1666,7 @@ file-filter Templates Mẫu Frequencies and angles are the output device's to apply. Tần số và góc do thiết bị đầu ra quyết định. Frequency Tần số Front Trước + Side Bên cạnh Frosted Sương mờ Full Document Toàn bộ tài liệu Full Screen Mode Chế độ toàn màn hình @@ -2028,6 +2063,9 @@ digits Hindi Hindi Cap Height Chiều cao chữ hoa x-Height Chiều cao chữ x ICF Box Ô ICF + Ascent Độ cao nét trên + x Height Chiều cao chữ x + Em Box Height Chiều cao ô em Show Sample Hiện mẫu Hide Sample Ẩn mẫu Max Ascent/Descent Độ cao/sâu tối đa @@ -2334,6 +2372,7 @@ digits Hindi Hindi Linked File Not Found Không tìm thấy tệp liên kết Links Liên kết Linux Display Server Máy chủ hiển thị Linux + Low-Latency Drawing Vẽ độ trễ thấp Liquify Lỏng hóa List Data Sets Liệt kê tập dữ liệu List Folder Liệt kê thư mục @@ -2367,6 +2406,7 @@ digits Hindi Hindi Load Texture… Tải kết cấu… Loaded Texture Kết cấu đã tải Local Libraries Thư viện cục bộ + Locate Layer Xác định vị trí lớp Locate Object Xác định vị trí đối tượng Locate Selected Objects Xác định vị trí đối tượng đã chọn Location Vị trí @@ -2451,7 +2491,7 @@ digits Hindi Hindi Medium Thumbnail View Chế độ hình thu nhỏ vừa Medium Thumbnails Hình thu nhỏ vừa Menu Dialog Hộp thoại menu - Merge Hợp nhất + Merge Gộp Merge colors into one row Hợp nhất màu vào một hàng New Row Hàng mới Merge Graphic Styles Hợp nhất kiểu đồ họa @@ -2876,6 +2916,9 @@ digits Hindi Hindi Overprint In chồng Overprint and Transparency Flattener In chồng và làm phẳng trong suốt Overprint and Transparency Flattener Options Tùy chọn in chồng và làm phẳng trong suốt + Custom… Tùy chỉnh… + Custom Transparency Flattener Options Tùy chọn làm phẳng trong suốt tùy chỉnh + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS không có trong suốt kênh Alpha, và In chồng quyết định có giữ in chồng hay không. Overprint Black… In chồng đen… Overprint Fill Tô in chồng Overprint Preview Xem trước in chồng @@ -2931,6 +2974,13 @@ digits Hindi Hindi Pathfinders: Pathfinder: Paths Đường dẫn Path Length Độ dài đường dẫn + Grid Size Kích thước lưới + Grid Colors Màu lưới + Flattener Preset Thiết lập sẵn làm phẳng + X X + Y Y + Orange Cam + Purple Tím Paths: {paths} Anchors: {anchors} Colors: {colors} Đường dẫn: {paths} Điểm neo: {anchors} Màu: {colors} Pattern Họa tiết Pattern Brush Cọ họa tiết @@ -3022,6 +3072,7 @@ diagnostics ui giao diện Play Current Selection Phát vùng chọn hiện tại Save Actions… Lưu hành động… Load Actions… Tải hành động… + Replace Actions… Thay thế hành động… Reset Actions Đặt lại hành động Replace the current actions with the default set? Thay thế các hành động hiện tại bằng bộ mặc định? Append adds the default set after the current sets instead. Nối thêm sẽ thêm bộ mặc định vào sau các bộ hiện tại. @@ -3039,6 +3090,10 @@ diagnostics ui giao diện Polar Grid Tool Công cụ Lưới cực Polygon Đa giác Polygon Properties: Thuộc tính đa giác: + Line Properties: Thuộc tính đường thẳng: + Line Length: Độ dài đường thẳng: + Line Angle: Góc đường thẳng: + Constrain Pie Angle Ràng buộc góc hình quạt Polygon Tool Công cụ Đa giác Portrait Đứng Portuguese Tiếng Bồ Đào Nha @@ -3206,6 +3261,9 @@ mark-style Japanese Kiểu Nhật Real World: Thực tế: Real-time Drawing and Editing Vẽ và chỉnh sửa theo thời gian thực Use Monitor Profile for Canvas Dùng hồ sơ màn hình cho vùng vẽ + Refresh Monitor Profile Làm mới hồ sơ màn hình +@msg turn on Use Monitor Profile for Canvas first hãy bật "Dùng hồ sơ màn hình cho vùng vẽ" trước +@msg this build doesn't read display profiles bản dựng này không đọc hồ sơ màn hình The canvas is drawn in sRGB. Vùng vẽ được hiển thị ở sRGB. Canvas display profile: Hồ sơ màn hình của vùng vẽ: The system matches the window to the display's colors. Hệ thống điều chỉnh cửa sổ theo màu của màn hình. @@ -3376,6 +3434,8 @@ mark-style Japanese Kiểu Nhật Reset all Revolve settings to their defaults. Đặt lại tất cả cài đặt Revolve về mặc định. Reset Bar Position Đặt lại vị trí thanh Reset Bounding Box Đặt lại hộp bao + Rotate Bounding Box Xoay hộp bao + Rotate Bounding Box… Xoay hộp bao… Reset Envelope Mesh Đặt lại lưới Envelope Reset Envelope Shape Đặt lại hình dạng Envelope Reset Essentials Đặt lại Essentials @@ -3412,6 +3472,8 @@ mark-style Japanese Kiểu Nhật Reset to White, Black Đặt lại về Trắng, Đen Reset Tracking and Kerning Đặt lại giãn chữ và kerning Highlight Font Name Đánh dấu tên phông + Highlight Font Size Đánh dấu cỡ chữ + Other… Khác… Highlight Kerning Đánh dấu kerning Highlight Tracking Đánh dấu giãn chữ Reset with Mesh Đặt lại với lưới @@ -3429,6 +3491,7 @@ mark-style Japanese Kiểu Nhật Resize Thay đổi kích thước Resize panel window Thay đổi kích thước cửa sổ bảng Resize panels Thay đổi kích thước bảng + Resolution Độ phân giải Resolution: Độ phân giải: Responsive Đáp ứng Restore Khôi phục @@ -3455,6 +3518,7 @@ mark-style Japanese Kiểu Nhật The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Con lăn chuột kèm giữ Cmd/Ctrl cuộn khung vẽ sang ngang. Dragging sideways on a numeric field's label changes the field's value. Kéo sang ngang trên nhãn của một trường số sẽ thay đổi giá trị của trường. A two-finger rotate gesture on a trackpad rotates the canvas view. Cử chỉ xoay bằng hai ngón trên bàn di chuột sẽ xoay khung nhìn của khung vẽ. + When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Khi bạn di chuyển điểm neo, mỗi đường cong có một đầu bị di chuyển sẽ giữ hình dạng so với các đầu của nó. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Giữ phím tắt của một công cụ sẽ chọn công cụ đó cho đến khi bạn thả ra, rồi công cụ trước đó được chọn lại. Shows the bounding box while you move the selection or draw a shape. Hiển thị hộp giới hạn khi bạn di chuyển vùng chọn hoặc vẽ một hình. Create Trim Marks draws Japanese-style marks instead of Roman ones. Tạo dấu cắt xén vẽ dấu kiểu Nhật thay cho kiểu La Mã. @@ -3485,6 +3549,29 @@ mark-style Japanese Kiểu Nhật The unit for East Asian type measurements, which no field uses yet. Đơn vị cho số đo chữ Đông Á, hiện chưa có trường nào dùng. When on, a number typed without a unit into a field in picas is read in points. Khi bật, số nhập không có đơn vị vào trường tính bằng pica được đọc theo điểm. With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options. Với XML ID, tên đối tượng hiển thị dưới dạng XML ID trong Các lớp, Biến số và Tùy chọn lớp. + The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl. Bước cho cỡ chữ và khoảng cách dòng: Cmd/Ctrl+Shift+. và Cmd/Ctrl+Shift+, đổi cỡ chữ một bước, hoặc năm bước khi có thêm Alt; trong chữ ngang, Alt cùng mũi tên lên hoặc xuống đổi khoảng cách dòng một bước, hoặc năm bước khi có Cmd/Ctrl. + The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl. Bước cho giãn chữ và kerning, tính bằng phần nghìn em: trong chữ ngang, Alt cùng mũi tên trái hoặc phải đổi kerning tại con trỏ hoặc giãn chữ của văn bản đã chọn một bước, hoặc năm bước khi có Cmd/Ctrl. + The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. Bước cho dịch đường cơ sở: trong chữ ngang, Alt và Shift cùng mũi tên lên hoặc xuống dời đường cơ sở một bước, hoặc năm bước khi có Cmd/Ctrl. + Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. Hiện các tùy chọn cho chữ Nhật và chữ Đông Á khác trong các bảng Ký tự, Đoạn văn, OpenType và Glyph, cùng lệnh Phông chữ tổ hợp. + Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. Hiện các tùy chọn cho chữ Ả Rập, Do Thái và Ấn Độ trong các bảng Ký tự và Đoạn văn, như hướng đoạn văn, kashida và chữ số. + The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. Các công cụ chọn chỉ chọn chữ trên đường cơ sở, khung của chữ vùng hoặc đường dẫn của nó, không phải bất kỳ đâu bên trong hộp của nó. + Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. Menu phông chữ liệt kê mỗi phông bằng tên tiếng Anh; khi tắt, phông có cả tên bằng ngôn ngữ của nó sẽ hiện tên đó. + New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. Chữ vùng mới bắt đầu với Tự động định cỡ bật, nên khung chữ nhật chứa chữ ngang cao lên hoặc thấp xuống cho vừa chữ của nó. + Font lists and the Type › Font menu show a sample of each font beside its name. Các danh sách phông chữ và menu Phông chữ hiện mẫu của mỗi phông bên cạnh tên của nó. + Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on. Mẫu phông chữ được vẽ bằng chữ tối trên nền trắng, bất kể độ sáng của giao diện; điều này chỉ áp dụng khi xem trước phông chữ trong menu đang bật. + How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is. Độ cao của mỗi hàng trong danh sách của các ô phông chữ, như ô trong bảng Ký tự, và do đó độ lớn của mỗi mẫu. + How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first. Số phông chữ dùng gần nhất, từ 1 đến 15, mà Phông chữ gần đây và các danh sách phông chữ hiện, mới nhất trước. + When you change the font or font style of text, characters the new font has no glyph for keep the font they had. Khi bạn đổi phông chữ hoặc kiểu phông của văn bản, các ký tự mà phông mới không có glyph sẽ giữ phông cũ. + A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export. Vùng tô hồng trên canvas đánh dấu các glyph mà tính năng OpenType đã thay thế, như chữ ghép; vùng này không được in hay xuất. + With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from. Với công cụ Chữ, chọn một ký tự sẽ hiện bên cạnh nó trên canvas một hàng glyph thay thế để chọn. + A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export. Vùng tô hồng trên canvas đánh dấu chữ được vẽ bằng phông thay thế vì thiếu phông của nó; vùng này không được in hay xuất. + New type made with a Type tool starts with placeholder text, selected, so typing replaces it. Chữ mới tạo bằng công cụ chữ bắt đầu với văn bản giữ chỗ đã được chọn, nên những gì bạn gõ sẽ thay thế nó. + Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list. Gõ một dấu danh sách như 1. hoặc * rồi một dấu cách ở đầu đoạn văn sẽ biến đoạn đó thành danh sách. + Fonts in this folder show in the font menus and can be used without being installed. Phông chữ trong thư mục này hiện trong các menu phông chữ và có thể dùng mà không cần cài đặt. + Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows. Áp dụng kiểu đồ họa cho chữ sẽ bỏ phần tô hoặc nét riêng của ký tự ở nơi kiểu có phần đó, để màu của kiểu hiện ra. + Align and Distribute measure point type by the ink of its glyphs instead of its em box. Căn chỉnh và Phân bố đo chữ điểm theo phần mực của các glyph thay vì hộp em của nó. + Align and Distribute measure area type by the ink of its glyphs instead of its frame. Căn chỉnh và Phân bố đo chữ vùng theo phần mực của các glyph thay vì khung của nó. + The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box. Hộp giới hạn và bảng Biến đổi đo chữ điểm theo phần mực của các glyph thay vì hộp em của nó. Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply. Hút thao tác vẽ, di chuyển và co giãn vào các phân chia của lưới, kể cả khi lưới đang ẩn; khi tùy chọn này bật, Hút vào pixel không có tác dụng. The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead. Màu của các đường căn không được chọn; bảng vẽ có Nhãn đường căn vẽ các đường căn của riêng nó bằng màu của nhãn. Draws guides as solid lines or as dots, including the guides already in the document. Vẽ đường căn dưới dạng đường liền hoặc chấm, kể cả các đường căn đã có trong tài liệu. @@ -3564,6 +3651,7 @@ mark-style Japanese Kiểu Nhật Rotate… Xoay… Rotation Góc xoay Rotation relative to: Xoay tương đối với: + Hue Jitter: Biến thiên sắc độ: Rotation X Xoay X Rotation Y Xoay Y Rotation Z Xoay Z @@ -3582,8 +3670,10 @@ mark-style Japanese Kiểu Nhật Rounded Rectangle Hình chữ nhật bo góc Rounded Rectangle Tool Công cụ Hình chữ nhật bo góc Rounded Rectangle… Hình chữ nhật bo góc… + Roundness Độ tròn Roundness: Độ tròn: Row Size: Kích thước hàng: + Rows Hàng Rows: Hàng: Rule: Quy tắc: Ruler Origin Gốc thước @@ -3770,6 +3860,11 @@ mark-style Japanese Kiểu Nhật Search commands, tools, panels and effects… Tìm kiếm lệnh, công cụ, bảng và hiệu ứng… No commands match Không có lệnh nào khớp {pos} of {total}: {name} {pos} trên {total}: {name} + No menu item Không có mục menu + Toolbar Thanh công cụ + {toolbar}, in the {tool} group {toolbar}, trong nhóm {tool} + Tool Công cụ + Command Lệnh @plural {n} result|{n} results {n} kết quả @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} trên {n} kết quả. Tiếp tục gõ để thu hẹp. Recent Commands Lệnh gần đây @@ -3861,6 +3956,7 @@ mark-style Japanese Kiểu Nhật Set Slice Rectangle Đặt hình chữ nhật lát cắt Set Tab Stops Đặt vị trí tab Set Text Đặt văn bản + Set the current fill or stroke to the selected color Đặt tô hoặc nét hiện tại thành màu đã chọn Set the selected color to the current color Đặt màu đã chọn thành màu hiện tại Set Zoom Đặt thu phóng Settings Cài đặt @@ -3996,7 +4092,7 @@ mark-style Japanese Kiểu Nhật Show Vivid/Muted Hiện màu sống động/tối Show Warm/Cool Hiện màu nóng/lạnh Show {kind} Brushes Hiện cọ {kind} - Show/hide plate (Alt-click: only this plate) Hiện/ẩn bản in (Alt-bấm: chỉ bản in này) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Hiện/ẩn bản in (Alt-bấm: chỉ bản in này; Alt-bấm lần nữa: tất cả bản in) Show: Hiện: Shown with the optimised preview. Hiển thị với bản xem trước được tối ưu hóa. Side 1: Mặt 1: @@ -4296,7 +4392,7 @@ mark-style Japanese Kiểu Nhật Composite Fonts Phông chữ tổ hợp Export Composite Fonts Xuất phông chữ tổ hợp Import Composite Fonts Nhập phông chữ tổ hợp -@msg each font must be {name, parts} mỗi phông chữ phải là {name, parts} +@msg each font must be {{name, parts}} mỗi phông chữ phải là {{name, parts}} @msg unknown key `{k}`; a font takes name and parts khóa không xác định `{k}`; một phông chữ nhận name và parts @msg each font needs a name mỗi phông chữ cần có tên @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` không thể là tên phông chữ tổ hợp (từ 1 đến {COMPOSITE_NAME_MAX} ký tự, không có ký tự điều khiển) @@ -4309,7 +4405,10 @@ mark-style Japanese Kiểu Nhật @msg two composite fonts are named `{_1}` có hai phông chữ tổ hợp cùng tên `{_1}` @msg `{_1}` is the name of an installed font `{_1}` là tên của một phông chữ đã cài đặt @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2} dùng `{font}`, một phông chữ tổ hợp -@msg give fonts: [{name, parts}…] hãy cung cấp fonts: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] hãy cung cấp fonts: [{{name, parts}}…] +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` phải là "document", {{artboards: [index, …]}} hoặc {{layers: [id, …]}} +@msg numbers out of order in {{}} quantifier các số không theo thứ tự trong lượng từ {{}} +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) màu tô không phải là chuyển sắc dạng tự do (hãy áp dụng một chuyển sắc bằng paint.editGradient {{kind: "freeform"}}) @msg path is empty path trống @msg fonts must be a list of composite fonts fonts phải là danh sách phông chữ tổ hợp @msg names must be strings names phải là chuỗi @@ -4403,6 +4502,13 @@ mark-style Japanese Kiểu Nhật Thumbnail View Dạng xem hình thu nhỏ Thumbnails: Hình thu nhỏ: Tile Ô + Tile All Vertically Xếp tất cả theo chiều dọc + Tile All Horizontally Xếp tất cả theo chiều ngang + 2-Up Layout Bố cục 2 + 3-Up Layout Bố cục 3 + 4-Up Layout Bố cục 4 + 6-Up Layout Bố cục 6 + Arrange Documents Sắp xếp tài liệu Tile Edge Color Màu cạnh ô Tile Edge Color… Màu cạnh ô… Tile Full Pages Ô toàn trang @@ -4641,6 +4747,8 @@ mark-style Japanese Kiểu Nhật Variable Options Tùy chọn biến Variable Options… Tùy chọn biến số… Variable Width Profile Hồ sơ chiều rộng biến đổi + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Cọ của nét giữ kích thước riêng, nên hồ sơ chiều rộng không thay đổi nét. Gỡ cọ để dùng hồ sơ. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Cọ của nét giữ kích thước riêng, nên hồ sơ chiều rộng không thay đổi nét. Gỡ cọ để dùng hồ sơ. Variables Biến số Variation: Biến thể: Vector Effects Hiệu ứng vector @@ -4676,7 +4784,7 @@ mark-style Japanese Kiểu Nhật Very High Rất cao Video Video View Hiển thị - View Artboard Only Chỉ hiển thị bảng vẽ + View Artboard Contents Only Chỉ hiển thị nội dung bảng vẽ View Opacity Mask Hiển thị mặt nạ độ mờ View PDF after saving Xem PDF sau khi lưu View {n} Hiển thị {n} @@ -4862,6 +4970,8 @@ theme Appearance Giao diện @msg `{min_key}` is greater than `{max_key}` `{min_key}` lớn hơn `{max_key}` @msg give at least one of `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` hãy cung cấp ít nhất một trong `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` phải là grayscale, rgb, hsb, cmyk hoặc websafe +@msg `view` must be wheel or box `view` phải là wheel hoặc box +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` phải là hue, saturation, brightness, red, green hoặc blue @msg `{k}` must be [x, y] `{k}` phải là [x, y] @msg `{name}` has no options `{name}` không có tùy chọn @msg `{name}` is a built-in workspace; choose another name `{name}` là không gian làm việc tích hợp sẵn; hãy chọn tên khác @@ -4957,6 +5067,9 @@ theme Appearance Giao diện @msg automation path rejected: outside the read root {root}: {path} đường dẫn tự động bị từ chối: ngoài thư mục gốc đọc {root}: {path} @msg automation path rejected: outside the read roots {roots}: {path} đường dẫn tự động bị từ chối: ngoài các thư mục gốc đọc {roots}: {path} @msg a linked JavaScript file is outside the read roots một tệp JavaScript được liên kết nằm ngoài các thư mục gốc đọc +@msg a linked image file is outside the read roots một tệp hình ảnh được liên kết nằm ngoài các thư mục gốc đọc +@msg a linked file's export folder is outside the read roots thư mục xuất của một tệp được liên kết nằm ngoài các thư mục gốc đọc +@msg a linked file's editing data can't be read to check it against the read roots không thể đọc dữ liệu chỉnh sửa của một tệp được liên kết để kiểm tra với các thư mục gốc đọc @msg the library's file is outside the read roots tệp của thư viện nằm ngoài các thư mục gốc đọc @msg {file} names more than one linked JavaScript file {file} khớp với nhiều hơn một tệp JavaScript được liên kết @msg automation path rejected: outside the write root {root}: {path} đường dẫn tự động bị từ chối: ngoài thư mục gốc ghi {root}: {path} @@ -4983,6 +5096,7 @@ theme Appearance Giao diện @msg bad trailer trailer không hợp lệ @msg balance must be between 0 and 100 balance phải nằm trong khoảng 0 đến 100 @msg batch step {_1} (`{id}`) failed: {e} bước hàng loạt {_1} (`{id}`) thất bại: {e} +@msg action step {_1} (`{id}`) failed: {reason} bước {_1} của hành động (`{id}`) thất bại: {reason} @msg before must name a panel before phải đặt tên bảng @msg below and above must name a panel floating in another group below và above phải đặt tên bảng đang thả nổi trong nhóm khác @msg Blend colors: select at least three objects with filled colours Hòa trộn màu: chọn ít nhất ba đối tượng có màu tô @@ -5007,6 +5121,7 @@ theme Appearance Giao diện @msg choose the font files to add hãy chọn các tệp phông chữ để thêm @msg clipboard is empty khay nhớ tạm trống @msg closing needs three anchors đóng đường dẫn cần ba điểm neo +@msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: phải giữ lại ít nhất một màu trong bảng màu @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` không phải là màu như "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: tối đa {MAX_TABLE} màu @msg column must be true or a number from 1 column phải là true hoặc số từ 1 @@ -5023,6 +5138,13 @@ theme Appearance Giao diện Show External Script Warning Hiện cảnh báo tập lệnh bên ngoài A Script Is Running Một tập lệnh đang chạy Script Alert Thông báo của tập lệnh + Script File Access Quyền truy cập tệp của tập lệnh + The script asks to read a file you choose. Tập lệnh yêu cầu đọc một tệp bạn chọn. + The script asks to read and write a file you choose. Tập lệnh yêu cầu đọc và ghi một tệp bạn chọn. + The script asks to read and write a folder you choose, with everything in it. Tập lệnh yêu cầu đọc và ghi một thư mục bạn chọn, cùng mọi thứ bên trong. + Allow Once Cho phép một lần + Always Allow This Script Luôn cho phép tập lệnh này + Deny Từ chối A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Tập lệnh có thể thay đổi các tài liệu đang mở và ghi tệp thông qua các lệnh mà nó chạy. Chỉ chạy những tập lệnh bạn tin cậy. Do not show this warning again Không hiện lại cảnh báo này Stop the script and undo what it did? Then quit again. Dừng tập lệnh và hoàn tác những gì nó đã làm? Sau đó hãy thoát lại. @@ -5039,6 +5161,8 @@ theme Appearance Giao diện @msg the script is no longer in the Scripts folder tập lệnh không còn trong thư mục Scripts Some scripts were not listed Một số tập lệnh không được liệt kê The Scripts folder cannot be read Không thể đọc thư mục Scripts + Loading scripts… Đang tải tập lệnh… + The Scripts folder is still being read Thư mục Scripts vẫn đang được đọc @msg the script's run is no longer available lần chạy tập lệnh không còn khả dụng @msg a failed command changed undo steps that could not be put back, so the script was stopped một lệnh thất bại đã thay đổi các bước hoàn tác không thể khôi phục, nên tập lệnh đã bị dừng @msg a recovery copy could not be written, so the script was not run không thể ghi bản sao khôi phục nên tập lệnh không được chạy @@ -5051,8 +5175,6 @@ theme Appearance Giao diện @msg Script file could not be read Không thể đọc tệp tập lệnh @msg Script folder has more than 2,048 entries Thư mục tập lệnh có hơn 2.048 mục @msg Script file open mode must be r, w, e or a Chế độ mở tệp tập lệnh phải là r, w, e hoặc a -@msg Script file writing is not available Không thể ghi tệp tập lệnh -@msg Script file dialogs are not available Không có hộp thoại tệp cho tập lệnh @msg Script files cannot be opened in another application Không thể mở tệp tập lệnh trong ứng dụng khác @msg Script file access is unavailable on the web Không thể truy cập tệp tập lệnh trên web @msg Script has 256 files open Tập lệnh đang mở 256 tệp @@ -5191,8 +5313,37 @@ liquify-list-end {0}, {1} {0} và {1} @msg is a prompt's answer, whose `value` must be a string or null là câu trả lời cho prompt, nên `value` phải là chuỗi hoặc null @msg must have `kind` alert, confirm or prompt phải có `kind` là alert, confirm hoặc prompt @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` chỉ dành cho lần chạy không có ai để hỏi: trong ứng dụng, người dùng trả lời từng hộp thoại +@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` phải là số nguyên từ 1 đến {_1} +@msg `args{place}` is nested more than 64 levels deep `args{place}` lồng sâu hơn 64 cấp +@msg `args` must be an object `args` phải là một đối tượng +@msg `args` is larger than 1 MiB `args` lớn hơn 1 MiB +@msg `path` is empty `path` trống +@msg `installed` takes a `path`, not a `source` `installed` nhận `path`, không nhận `source` +@msg `path` must name a .js or .jsx file `path` phải chỉ đến tệp .js hoặc .jsx +@msg give exactly one of `path` and `source` hãy cung cấp đúng một trong `path` và `source` @msg Running a script Đang chạy tập lệnh @msg Copied the script report Đã sao chép báo cáo script +@msg Script file access denied: {path} Quyền truy cập tệp của tập lệnh bị từ chối: {path} +@msg Script file access to the app's own folders is not allowed Tập lệnh không được phép truy cập các thư mục riêng của ứng dụng +@msg Script file cannot encode the text Tệp của tập lệnh không thể mã hóa văn bản +@msg Script file could not be written Không thể ghi tệp của tập lệnh +@msg Script file dialogs need a person to answer them Hộp thoại tệp của tập lệnh cần một người trả lời +@msg Script file is not open for writing Tệp của tập lệnh chưa được mở để ghi +@msg Script file name is already in use Tên tệp của tập lệnh đã được sử dụng +@msg Script file name must be a name without a folder Tên tệp của tập lệnh phải là một tên không có thư mục +@msg Script file permission can be kept only for a script run from a file Chỉ có thể giữ quyền truy cập tệp cho tập lệnh chạy từ một tệp +@msg Script file permission could not be saved Không thể lưu quyền truy cập tệp của tập lệnh +@msg Script folder is not empty Thư mục của tập lệnh không trống +@msg Script files cannot make aliases Tệp của tập lệnh không thể tạo bí danh +@msg Script file hidden setting cannot be changed Không thể thay đổi cài đặt ẩn của tệp tập lệnh +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: không thể mở hộp thoại tệp bên trong callback của hàm dựng sẵn, getter, phép chuyển đổi hoặc tệp mà $.evalFile chạy; hãy gọi nó từ mã riêng của tập lệnh +@msg the script wrote more file data than one run may write (32 MiB) tập lệnh đã ghi nhiều dữ liệu tệp hơn mức một lần chạy được phép ghi (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` cho hộp thoại tệp của tập lệnh phải là một trong: once, always, deny, stop +@msg choose a file or folder first, or deny hãy chọn một tệp hoặc thư mục trước, hoặc từ chối +@msg the script file permissions could not be saved: {e} không thể lưu quyền truy cập tệp của các tập lệnh: {e} +@msg this script's file access can be allowed only once quyền truy cập tệp của tập lệnh này chỉ có thể được cho phép một lần +@msg Only the person at the keyboard can allow a script's file access Chỉ người ngồi tại bàn phím mới có thể cho phép tập lệnh truy cập tệp +@msg A script is given at most 2,048 files: the files picked after them were left out Một tập lệnh nhận tối đa 2.048 tệp: các tệp được chọn sau đó đã bị bỏ qua @msg Copied the link info Đã sao chép thông tin liên kết @msg Corners edits the corners of a path Corners chỉnh sửa các góc của đường dẫn @msg could not decode image: {0} không thể giải mã ảnh: {0} @@ -5364,9 +5515,15 @@ liquify-list-end {0}, {1} {0} và {1} @msg name the file hãy đặt tên tệp @msg no active document không có tài liệu đang hoạt động @msg no active perspective plane không có mặt phẳng phối cảnh đang hoạt động +@msg the perspective grid is hidden lưới phối cảnh đang ẩn +@msg Automatic Plane Positioning is off: turn on anchorPoint or gridlineIntersection (perspective.widget.options) Tự động định vị mặt phẳng đang tắt: hãy bật anchorPoint hoặc gridlineIntersection (perspective.widget.options) +@msg anchorPoint must be true or false anchorPoint phải là true hoặc false +@msg gridlineIntersection must be true or false gridlineIntersection phải là true hoặc false +@msg tolerance must be 0 or more tolerance phải từ 0 trở lên +@msg give `at` or `clear`, not both hãy cung cấp `at` hoặc `clear`, không phải cả hai @msg no anchor points selected chưa chọn điểm neo -@msg `points` must be three [x, y] pairs of numbers `points` phải là ba cặp số [x, y] -@msg direct-select three anchor points, or give `points` hãy chọn trực tiếp ba điểm neo hoặc cung cấp `points` +@msg `points` must be two or three [x, y] pairs of numbers `points` phải là hai hoặc ba cặp số [x, y] +@msg direct-select two or three anchor points, or give `points` hãy chọn trực tiếp hai hoặc ba điểm neo hoặc cung cấp `points` @msg no circle passes through these points: two are the same or all three lie on one line không có đường tròn nào đi qua các điểm này: hai điểm trùng nhau hoặc cả ba điểm thẳng hàng @msg no app to open files here không có ứng dụng để mở tệp ở đây @msg no artboard không có bảng vẽ @@ -5480,12 +5637,17 @@ liquify-list-end {0}, {1} {0} và {1} @msg no such user library không có thư viện người dùng như vậy @msg no such view không có chế độ xem như vậy @msg no such width point không có điểm chiều rộng như vậy +@msg `single` must be `incoming` or `outgoing` `single` phải là `incoming` hoặc `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` và `outIndex` phải là hai nửa của cùng một điểm chiều rộng gián đoạn +@msg a discontinuous width point keeps its place điểm chiều rộng gián đoạn giữ nguyên vị trí @msg no swatch `{name}` không có mẫu màu `{name}` @msg no swatch library `{l}` (see swatch.library.list) không có thư viện mẫu màu `{l}` (xem swatch.library.list) @msg no symbol instances selected chưa chọn đối tượng ký hiệu @msg no target object has an opacity mask: select one or give `id` không có đối tượng đích có mặt nạ độ mờ: hãy chọn hoặc cung cấp `id` @msg no threaded text selected chưa chọn văn bản liên kết @msg no user library folder here không có thư mục thư viện người dùng ở đây +@msg `{file}` has no swatches of its own `{file}` không có mẫu màu riêng +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` có mẫu họa tiết, mà tệp .vcswatches không thể chứa @msg no user workspace `{from}` không có không gian làm việc người dùng `{from}` @msg node {_1} is not text nút {_1} không phải là văn bản @msg node {_1} is on a locked artboard nút {_1} nằm trên bảng vẽ bị khóa @@ -5632,6 +5794,9 @@ liquify-list-end {0}, {1} {0} và {1} @msg Saved to User Defined: {_1} Đã lưu vào Người dùng tùy chỉnh: {_1} @msg Saved {n} files beside {path} Đã lưu {n} tệp bên cạnh {path} @msg Saved {path} Đã lưu {path} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Đã sao chép với {n} ghi chú: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Đã cắt với {n} ghi chú: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Đã vector hóa ảnh với {n} ghi chú: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} Đã lưu {path} với {n} ghi chú: {first} @msg Saving Đang lưu @msg Saving recovery data for {_1} Đang lưu dữ liệu phục hồi cho {_1} @@ -5710,6 +5875,7 @@ liquify-list-end {0}, {1} {0} và {1} @msg shadings of more than 4096 patches or triangles were left out các vùng tô có hơn 4096 mảnh hoặc tam giác đã bị bỏ qua @msg shadings whose functions are of an unknown type are filled with their middle colour các vùng tô có hàm loại không xác định được tô bằng màu giữa @msg Shape Builder: no region under the pointer Xây dựng hình dạng: không có vùng nào dưới con trỏ +@msg Shape Builder: select all paths you want to merge Xây dựng hình dạng: chọn tất cả đường dẫn bạn muốn hợp nhất @msg Shape Builder: select paths or compound paths Xây dựng hình dạng: chọn đường dẫn hoặc đường dẫn phức @msg shortcut for `{k}` must be a string phím tắt cho `{k}` phải là chuỗi @msg Show All Hidden Attributes: nothing is hidden Hiện tất cả thuộc tính ẩn: không có gì bị ẩn @@ -5787,7 +5953,7 @@ liquify-list-end {0}, {1} {0} và {1} @msg each of `{GRAPHICS}` must be an object mỗi mục của `{GRAPHICS}` phải là một đối tượng @msg `{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}` các mục của `{GRAPHICS}` nhận symbol, face, x, y, scale và rotation, không nhận `{k}` @msg each of `{GRAPHICS}` needs `symbol`, the name of a symbol mỗi mục của `{GRAPHICS}` cần `symbol`, tên của một ký hiệu -@msg `{GRAPHICS}` face must be front or back face của `{GRAPHICS}` phải là front hoặc back +@msg `{GRAPHICS}` face must be front, back or side face của `{GRAPHICS}` phải là front, back hoặc side @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} của `{GRAPHICS}` phải là số từ {lo} đến {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` phải là một mảng @msg Graphics map onto the Plane, Extrude and Revolve object types Đồ họa được đặt lên các loại đối tượng Mặt phẳng, Kéo dài và Xoay tròn @@ -5921,6 +6087,8 @@ liquify-list-end {0}, {1} {0} và {1} @msg tool shortcuts must be a single key (optionally with Shift) phím tắt công cụ phải là một phím đơn (tùy chọn với Shift) @msg truncated bị cắt ngắn @msg Unembedded to {_1} Đã bỏ nhúng vào {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} Đã bỏ nhúng {n} ảnh vào {folder} +@msg every numbered name for {name} is taken in that folder mọi tên đánh số cho {name} đã được dùng trong thư mục đó @msg unknown command `{0}` lệnh không xác định `{0}` @msg step {step} of “{action}” runs the unknown command `{command}` bước {step} của “{action}” chạy lệnh không xác định `{command}` @msg unknown command `{0}`; did you mean `{1}`? lệnh không xác định `{0}`; ý bạn là `{1}`? @@ -5989,6 +6157,13 @@ liquify-list-end {0}, {1} {0} và {1} @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} hơn {MAX_CSV_ROWS} tập dữ liệu: Nhập tập dữ liệu chỉ đọc tối đa {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} hơn {MAX_CSV_COLS} biến số: Nhập tập dữ liệu chỉ đọc tối đa {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} các biến số không phải văn bản đã bị bỏ qua: {kinds} +variable-kind Visibility Hiển thị +variable-kind Linked File Tệp được liên kết +variable-kind Graph Data Dữ liệu biểu đồ +variable-kind Unknown Không xác định +variable-list-two {0}, {1} {0} và {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} và {1} @msg a new document won't read these variables back with their kind: {names} tài liệu mới sẽ không đọc lại các biến số này đúng loại: {names} @msg a new document refuses this file because of these variables: {names} tài liệu mới sẽ từ chối tệp này vì các biến số sau: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them tiêu đề `{header}` của `{name}` sẽ được đọc thành biến số `{other}`: hãy đổi tên một trong hai @@ -6037,6 +6212,8 @@ liquify-list-end {0}, {1} {0} và {1} @msg {label}: lost track of a shape's style {label}: mất dấu kiểu của hình dạng @msg {label}: select paths {label}: hãy chọn đường dẫn @msg {label}: select paths, compound paths, groups or text {label}: hãy chọn đường dẫn, đường dẫn phức, nhóm hoặc văn bản +@msg a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first một đường thẳng hoặc đường dẫn mở khác không bao quanh vùng nào sẽ không làm thay đổi hình dạng của kết quả; để đưa nó vào, trước tiên hãy áp dụng Đối tượng › Đường dẫn › Đường bao nét cho nó +@msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first {label} tạo ra kết quả trống: một đường thẳng hoặc đường dẫn mở khác không bao quanh vùng nào; để đưa nó vào, trước tiên hãy áp dụng Đối tượng › Đường dẫn › Đường bao nét cho nó @msg {label}… {label}… @msg {name}: CRC mismatch {name}: CRC không khớp @msg {name}: no local header {name}: không có tiêu đề cục bộ @@ -6048,6 +6225,8 @@ liquify-list-end {0}, {1} {0} và {1} @msg {path}: {e} {path}: {e} @msg {status} ({e}) {status} ({e}) @msg {tool} isn't in a toolbar group of several tools {tool} không nằm trong nhóm thanh công cụ có nhiều công cụ +@msg Presentation Mode hides the toolbars: change the screen mode to show them Chế độ trình bày ẩn các thanh công cụ: hãy đổi chế độ màn hình để hiện chúng +@msg Tab has hidden the toolbars: press Tab to show them phím Tab đã ẩn các thanh công cụ: nhấn Tab để hiện chúng Load EPS into Clipboard Tải EPS vào bảng tạm @msg an image of {w} × {h} pixels is too large to draw ảnh {w} × {h} điểm ảnh quá lớn nên không thể vẽ @msg {path}: not a PNG, JPEG, WebP, TIFF or BMP image {path}: không phải ảnh PNG, JPEG, WebP, TIFF hay BMP @@ -7021,6 +7200,12 @@ anchor Points: Điểm: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` phải là "free", "keepAngles" hoặc "symmetric" @msg `{key}` must be [x, y] `{key}` phải là [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Bộ chuyển đổi đơn vị + Unit Converter Panel Bảng Bộ chuyển đổi đơn vị + Copy with Units Sao chép kèm đơn vị + From Selection Từ vùng chọn + # Color Effects add-on: Select by Color Kind. Select by Color Kind Chọn theo loại màu Objects with Spot Colors Đối tượng có màu pha @@ -7246,6 +7431,14 @@ breakText Glyphs Glyph Remove Gaps Gỡ các khoảng hở @msg that makes too many pieces (at most 100000): make the dashes longer như vậy tạo ra quá nhiều mảnh (tối đa 100000): hãy kéo dài nét @msg select paths, or segments, to divide chọn các đường dẫn hoặc đoạn để chia +# Path Precision Tools add-on: Smooth Bridge. + Smooth Bridge… Cầu nối mượt… + Smooth Bridge Cầu nối mượt + Keep Originals Giữ bản gốc +@msg select two circles to bridge chọn hai hình tròn để nối +@msg one circle is inside the other một hình tròn nằm bên trong hình tròn kia +@msg the circles are too far apart for this radius: raise the radius các hình tròn cách nhau quá xa so với bán kính này: hãy tăng bán kính +@msg the circles are too far apart for this radius các hình tròn cách nhau quá xa so với bán kính này # Path Precision Tools add-on: Common Tangents. Common Tangents… Tiếp tuyến chung… Common Tangents Tiếp tuyến chung @@ -7640,6 +7833,16 @@ breakText Glyphs Glyph @msg A panel is not joined to the rest by a crease. Một mặt không được nối với phần còn lại bằng đường cấn nào. @msg A fold line is on a non-printing layer. Một đường gấp nằm trên lớp không in. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Mặt: {panels}, bản lề: {hinges}, lỗi: {errors}, cảnh báo: {warnings} + Fold Preview Xem trước nếp gấp + Fold Gấp + Show Fold Lines Hiện đường gấp + Three-Quarter Ba phần tư + Open a document to preview its folded shape. Mở tài liệu để xem trước hình dạng đã gấp của nó. +@msg Check the fold lines first. Hãy kiểm tra đường gấp trước. +@msg Panels: {panels}, hinges: {hinges} Mặt: {panels}, bản lề: {hinges} +@msg Other blanks not shown: {count} Các khuôn trải khác không được hiển thị: {count} +@msg A joint does not close by {gap} pt. Một mối nối hở {gap} pt. +@msg Two panels pass through each other. Hai mặt xuyên qua nhau. # Messages of the effects, 3D, image export, color profiles, swatch exchange files, color books and DXF import. @msg 3D effects require finite coordinates within 100 million points Hiệu ứng 3D yêu cầu tọa độ hữu hạn trong phạm vi 100 triệu điểm @@ -7759,3 +7962,4 @@ breakText Glyphs Glyph @msg {width} × {height} pixels is too large for Targa (at most 65535 pixels a side): lower the resolution {width} × {height} điểm ảnh quá lớn cho Targa (tối đa 65535 điểm ảnh mỗi cạnh): hãy giảm độ phân giải @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} điểm ảnh quá lớn cho PSD (tối đa {MAX_SIDE} điểm ảnh mỗi cạnh): hãy giảm độ phân giải @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer phải là "singleLine", "everyLine", "standardSingleLine" hoặc "standardEveryLine" +@msg text.{key} `{v}`: use "{_1}" or "{_2}" text.{key} `{v}`: hãy dùng "{_1}" hoặc "{_2}" diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index c6696a9ec6..617b9ac1e8 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -68,6 +68,7 @@ Add Anchor Point 添加锚点 Add Anchor Point Tool 添加锚点工具 Add Anchor Points 添加锚点 + Add Around 围绕对象添加 Add Effect 添加效果 Add Freeform Line 添加自由曲线 Add Freeform Point 添加自由点 @@ -89,8 +90,12 @@ Add to Swatches 添加到色板 Add Used Colors 添加已用颜色 Additional Plug-ins Folder 附加增效工具文件夹 + Plug-in Instruction Budget 增效工具指令预算 Additional Fonts Folder 附加字体文件夹 Adjust Adjoining Width Points 调整相邻宽度点 + Incoming 入侧 + Outgoing 出侧 + Single Width Only 仅保留一个宽度 Adjust Color Balance… 调整色彩平衡… Adjust Colors 调整颜色 Adjust Options: 调整选项: @@ -144,6 +149,7 @@ Angle: 角度: Angles 角度 Animated Zoom 动画缩放 + Anti Alias 消除锯齿 Anti-alias 消除锯齿 Anti-Alias 消除锯齿 Anti-alias Rasters 栅格消除锯齿 @@ -311,6 +317,12 @@ antiAlias Sharp 锐利 Brush Definition 画笔定义 Brush Libraries 画笔库 Brush Options… 画笔选项… + Options of Selected Object… 所选对象的选项… + Options of Selected Object 所选对象的选项 +@msg no path painted with a brush is selected 未选择用画笔绘制的路径 +@msg the selected paths are painted with brushes of different types 所选路径使用了不同类型的画笔 +@msg give `params` or `reset`, not both 请提供 `params` 或 `reset`,不能同时提供 +@msg a bristle brush has no options of its own on a path 鬃毛画笔在路径上没有自己的选项 Brush Strokes 画笔描边 Brushes 画笔 Built-in Libraries 内置库 @@ -366,6 +378,12 @@ antiAlias Sharp 锐利 Character Alignment 字符对齐 Character / Paragraph 字符/段落 Character Rotation 字符旋转 + Chinese Big 5 繁体中文 Big 5 + Cyrillic 西里尔文 + Greek 希腊文 + Turkish 土耳其文 + Baltic 波罗的海文 + Central European 中欧文 Character Set: 字符集: Character Style 字符样式 Character Style Options 字符样式选项 @@ -428,6 +446,8 @@ antiAlias Sharp 锐利 Choose a folder 选择文件夹 Choose… 选择… Circle 圆形 + Circle Tool 圆形工具 + Circle too large 圆形过大 Classic Defaults 经典默认 Clean Up… 清理… Clear 清除 @@ -501,6 +521,7 @@ antiAlias Sharp 锐利 Color Mixer (Shift-click the chip) 颜色混合器 (Shift+单击色块) Color Mode 颜色模式 Color Mode: 颜色模式: + Color Model 颜色模型 Color Model: 颜色模型: Color Models 颜色模型 Color Picker 拾色器 @@ -521,12 +542,18 @@ antiAlias Sharp 锐利 Saturation and brightness 饱和度和亮度 Color field 颜色区域 {name1} {value1}, {name2} {value2} {name1} {value1},{name2} {value2} + Wheel View 色轮视图 + Box View 方块视图 + Box Channel 方块色版 + Color box 颜色方块 + Color Wheel Options 色轮选项 Color Type: 颜色类型: Color: 颜色: Colorize 上色 Colors 颜色数 Colors: 颜色: Column Graph Tool 柱形图工具 + Columns 列数 Columns: 列数: Column… 列… Combine Slices 组合切片 @@ -734,6 +761,8 @@ antiAlias Sharp 锐利 Delete Artboard 删除画板 Delete Artboards 删除画板 Delete Brush 删除画笔 + Delete Color 删除颜色 + Restore Generated Table 恢复生成的颜色表 Delete Character Style 删除字符样式 Delete Empty Artboards 删除空白画板 Delete Freeform Point 删除自由点 @@ -801,6 +830,7 @@ antiAlias Sharp 锐利 Direct Selection Tool 直接选择工具 Direction Handles 方向手柄 Disable Auto Add/Delete 禁用自动添加/删除锚点 + Interpolate Control Points When Moving Anchors 移动锚点时插值方向手柄 Disable Opacity Mask 禁用不透明度蒙版 Discard 不存储 Discard Empty Type 丢弃空文字 @@ -903,7 +933,7 @@ antiAlias Sharp 锐利 Drop Shadow 制作阴影 Drop Shadow… 阴影… Duotone Gradients 双色调渐变 - Duplicate 复制 + Duplicate 创建副本 Duplicate and Offset 10 pt 复制并偏移 10 pt Duplicate Artboard 复制画板 Copy Artboard 拷贝画板 @@ -984,6 +1014,9 @@ antiAlias Sharp 锐利 Cap Height 大写字母高度 x-Height x 字高 ICF Box ICF 框 + Ascent 上缘 + x Height x 字高 + Em Box Height 全角字框高度 Show Sample 显示样本 Hide Sample 隐藏样本 Max Ascent/Descent 最大上升/下降 @@ -1016,6 +1049,7 @@ antiAlias Sharp 锐利 Enable text access for screen readers 启用屏幕阅读器的文字访问 Enable Touch Gestures 启用触控手势 Switch Selection and Drawing Modes 切换选择与绘图模式 + Select Last Selection Tool 切换到上次使用的选择工具 Enable Touch Workspace 启用触控工作区 Encoding 编码 Encoding: 编码: @@ -1195,6 +1229,8 @@ antiAlias Sharp 锐利 Files 文件 Files of a PDF standard can't be password-protected. PDF 标准的文件无法设置密码保护。 Files of this standard tag their colours with ICC profiles. 此标准的文件会以 ICC 配置文件标记颜色。 + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. 此标准的文件会以 ICC 配置文件标记颜色,但输出意图配置文件中的 CMYK 颜色会写为 DeviceCMYK。 + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. 选择“不包含配置文件”且输出意图为 CMYK 时,除非转换为其他配置文件的 CMYK 目标,否则每种 CMYK 颜色都会写为 DeviceCMYK。 Fill 填色 Fill & Stroke 填色和描边 Fill (X), double-click for the Color Picker 填色 (X),双击打开拾色器 @@ -1245,6 +1281,8 @@ antiAlias Sharp 锐利 Reset Tracking and Kerning 重置字距和字偶距 Reset Horizontal Scale 重置水平缩放 Highlight Font Name 突出显示字体名称 + Highlight Font Size 突出显示字号 + Other… 其他… Highlight Kerning 突出显示字偶距 Highlight Tracking 突出显示字距 Spacing 间距 @@ -1939,6 +1977,7 @@ file-filter Templates 模板 Load SVG into Clipboard 将 SVG 载入剪贴板 Load Text into Clipboard 将文本载入剪贴板 Local Libraries 本地库 + Locate Layer 查找图层 Locate Object 查找对象 Locate Selected Objects 查找所选对象 Location 位置 @@ -2129,6 +2168,7 @@ file-filter Templates 模板 Scatter: 散布: Rotation: 旋转: Rotation relative to: 旋转相对于: + Hue Jitter: 色相抖动: Brush Scale Options 画笔缩放选项 Scale Proportionately 等比缩放 Stretch to Fit Stroke Length 伸展以适合描边长度 @@ -2155,6 +2195,7 @@ file-filter Templates 模板 Approximate path 近似路径 Colorization 着色 Key Color: 主色: + Roundness 圆度 Roundness: 圆度: Fixed 固定 Pressure 压力 @@ -2457,6 +2498,9 @@ file-filter Templates 模板 Overprint 叠印 Overprint and Transparency Flattener 叠印和透明度拼合器 Overprint and Transparency Flattener Options 叠印和透明度拼合器选项 + Custom… 自定义… + Custom Transparency Flattener Options 自定义透明度拼合器选项 + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS 没有 Alpha 透明度,“叠印”决定是否保留叠印。 Overprint Black… 黑色叠印… Overprint Fill 叠印填色 Overprint Preview 叠印预览 @@ -2507,6 +2551,11 @@ file-filter Templates 模板 Pathfinders: 路径查找器: Paths 路径 Path Length 路径长度 + Grid Size 网格大小 + Grid Colors 网格颜色 + Flattener Preset 拼合预设 + X X + Y Y Paths: {paths} Anchors: {anchors} Colors: {colors} 路径:{paths} 锚点:{anchors} 颜色:{colors} Pattern 图案 Pattern Editing 图案编辑 @@ -2566,6 +2615,7 @@ diagnostics ui 界面 Play Current Selection 播放当前选择项目 Save Actions… 存储动作… Load Actions… 载入动作… + Replace Actions… 替换动作… Reset Actions 重置动作 Replace the current actions with the default set? 要用默认动作组替换当前动作吗? Append adds the default set after the current sets instead. “追加”会改为将默认动作组添加到当前动作组之后。 @@ -2581,6 +2631,10 @@ diagnostics ui 界面 Polar Grid Tool 极坐标网格工具 Polygon 多边形 Polygon Properties: 多边形属性: + Line Properties: 直线属性: + Line Length: 直线长度: + Line Angle: 直线角度: + Constrain Pie Angle 约束扇形角度 Polygon Tool 多边形工具 Portrait 纵向 Portuguese 葡萄牙语 @@ -2743,6 +2797,9 @@ digits Malayalam 马拉雅拉姆数字 Real World: 真实世界: Real-time Drawing and Editing 实时绘图和编辑 Use Monitor Profile for Canvas 画布使用显示器配置文件 + Refresh Monitor Profile 刷新显示器配置文件 +@msg turn on Use Monitor Profile for Canvas first 请先打开“画布使用显示器配置文件” +@msg this build doesn't read display profiles 此版本不读取显示器配置文件 The canvas is drawn in sRGB. 画布以 sRGB 绘制。 Canvas display profile: 画布显示配置文件: The system matches the window to the display's colors. 系统会使窗口匹配显示器的颜色。 @@ -2933,6 +2990,8 @@ digits Malayalam 马拉雅拉姆数字 Reselect 重新选择 Reset 重置 Reset Bounding Box 重置定界框 + Rotate Bounding Box 旋转定界框 + Rotate Bounding Box… 旋转定界框… Reset Envelope Mesh 重置封套网格 Reset Envelope Shape 重置封套形状 Reset Essentials 重置基本功能 @@ -2973,6 +3032,7 @@ digits Malayalam 马拉雅拉姆数字 Reshape Segment 整形线段 Reshape Tool 整形工具 Reshape Type Area 调整区域文字轮廓 + Resolution 分辨率 Resolution: 分辨率: Responsive 响应式 Restore 恢复 @@ -2999,6 +3059,7 @@ digits Malayalam 马拉雅拉姆数字 The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. 按住 Cmd/Ctrl 滚动鼠标滚轮会横向滚动画布。 Dragging sideways on a numeric field's label changes the field's value. 在数值字段的标签上横向拖动可更改字段的值。 A two-finger rotate gesture on a trackpad rotates the canvas view. 在触控板上用双指旋转手势可旋转画布视图。 + When you move anchor points, each curve with one moved end keeps its shape relative to its ends. 移动锚点时,只有一端移动的每条曲线都会保持其相对于两端的形状。 Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. 按住工具的快捷键时选择该工具,松开后重新选择之前的工具。 Shows the bounding box while you move the selection or draw a shape. 移动所选对象或绘制形状时显示定界框。 Create Trim Marks draws Japanese-style marks instead of Roman ones. 创建裁切标记绘制日式标记,而不是西式标记。 @@ -3029,6 +3090,29 @@ digits Malayalam 马拉雅拉姆数字 The unit for East Asian type measurements, which no field uses yet. 用于东亚文字度量的单位,目前还没有字段使用。 When on, a number typed without a unit into a field in picas is read in points. 开启后,在以派卡为单位的字段中输入的不带单位的数字按点读取。 With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options. 选择 XML ID 时,图层、变量和图层选项中的对象名称显示为 XML ID。 + The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl. 文字大小和行距的步长:Cmd/Ctrl+Shift+. 和 Cmd/Ctrl+Shift+, 将字号改变一步,同时按 Alt 则改变五步;在横排文字中,Alt 加上下箭头将行距改变一步,同时按 Cmd/Ctrl 则改变五步。 + The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl. 字距调整和字偶间距的步长,单位为千分之一 em:在横排文字中,Alt 加左右箭头将插入点处的字偶间距或所选文字的字距调整改变一步,同时按 Cmd/Ctrl 则改变五步。 + The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. 基线偏移的步长:在横排文字中,Alt、Shift 加上下箭头将基线移动一步,同时按 Cmd/Ctrl 则移动五步。 + Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. 在字符、段落、OpenType 和字形面板中显示日文及其他东亚文字的选项,并显示复合字体命令。 + Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. 在字符和段落面板中显示阿拉伯文、希伯来文和印度系文字的选项,例如段落方向、卡希达和数字。 + The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. 选择工具只在文字的基线、区域文字的框架或其路径上选择文字,而不是在其框内任意位置。 + Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. 字体菜单以英文名称列出每种字体;关闭时,也有本国语言名称的字体会显示该名称。 + New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. 新的区域文字开启自动调整大小,因此横排文字的矩形框架会随文字增高或缩短。 + Font lists and the Type › Font menu show a sample of each font beside its name. 字体列表和字体菜单在每种字体的名称旁显示该字体的样本。 + Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on. 无论界面亮度如何,字体样本都以深色文字绘制在白色上;仅在菜单内字体预览开启时生效。 + How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is. 字体字段(例如字符面板中的字段)列表中每行的高度,也就是每个样本的大小。 + How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first. 最近字体和字体列表显示多少个最近使用的字体(1 到 15),最新的在前。 + When you change the font or font style of text, characters the new font has no glyph for keep the font they had. 更改文字的字体或字体样式时,新字体中没有字形的字符会保留原来的字体。 + A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export. 画布上的粉色高亮标出被 OpenType 功能替换的字形,例如连字;高亮不会打印或导出。 + With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from. 使用文字工具选中一个字符时,画布上会在其旁边显示一排可供选择的替代字形。 + A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export. 画布上的粉色高亮标出因缺少字体而用替代字体绘制的文字;高亮不会打印或导出。 + New type made with a Type tool starts with placeholder text, selected, so typing replaces it. 用文字工具新建的文字以选中的占位符文字开始,输入的内容会替换它。 + Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list. 在段落开头输入 1. 或 * 等列表标记再输入空格,该段落会变成列表。 + Fonts in this folder show in the font menus and can be used without being installed. 此文件夹中的字体会显示在字体菜单中,无需安装即可使用。 + Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows. 对文字应用图形样式时,样式有填色或描边的地方会移除字符自身的填色或描边,从而显示样式的颜色。 + Align and Distribute measure point type by the ink of its glyphs instead of its em box. 对齐和分布按字形的墨迹而不是全角框测量点文字。 + Align and Distribute measure area type by the ink of its glyphs instead of its frame. 对齐和分布按字形的墨迹而不是框架测量区域文字。 + The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box. 定界框和变换面板按字形的墨迹而不是全角框测量点文字。 Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply. 即使网格已隐藏,绘制、移动和缩放也会对齐到网格的细分;开启期间,“对齐像素”不起作用。 The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead. 未选中参考线的颜色;设置了参考线标签的画板会用标签颜色绘制自己的参考线。 Draws guides as solid lines or as dots, including the guides already in the document. 将参考线绘制为实线或点,包括文档中已有的参考线。 @@ -3107,6 +3191,7 @@ digits Malayalam 马拉雅拉姆数字 Rounded Rectangle 圆角矩形 Rounded Rectangle Tool 圆角矩形工具 Rounded Rectangle… 圆角矩形… + Rows 行数 Rows: 行数: Rule: 规则: Rulers 标尺 @@ -3254,6 +3339,9 @@ digits Malayalam 马拉雅拉姆数字 Search commands, tools, panels and effects… 搜索命令、工具、面板和效果… No commands match 没有匹配的命令 {pos} of {total}: {name} 第 {pos} 个,共 {total} 个:{name} + No menu item 无菜单项 + Toolbar 工具栏 + {toolbar}, in the {tool} group {toolbar},位于 {tool} 组中 @plural {n} result|{n} results {n} 个结果 @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. 共 {n} 个结果,显示 {shown} 个。继续输入以缩小范围。 Recent Commands 最近使用的命令 @@ -3331,6 +3419,7 @@ digits Malayalam 马拉雅拉姆数字 Set Slice Rectangle 设置切片矩形 Set Tab Stops 设置制表位 Set Text 设置文本 + Set the current fill or stroke to the selected color 将当前填色或描边设为选择的颜色 Set the selected color to the current color 将选择的颜色设为当前颜色 Set Zoom 设置缩放 Settings… 设置… @@ -3452,7 +3541,7 @@ digits Malayalam 马拉雅拉姆数字 Show Vivid/Muted 显示鲜艳/柔和 Show Warm/Cool 显示暖色/冷色 Show {kind} Brushes 显示{kind}画笔 - Show/hide plate (Alt-click: only this plate) 显示/隐藏色版 (Alt-单击:仅此色版) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) 显示/隐藏色版 (Alt-单击:仅此色版;再次 Alt-单击:所有色版) Show: 显示: Shown with the optimised preview. 与优化预览一起显示。 Side 1: 侧边 1: @@ -3761,7 +3850,7 @@ digits Malayalam 马拉雅拉姆数字 Composite Fonts 复合字体 Export Composite Fonts 导出复合字体 Import Composite Fonts 导入复合字体 -@msg each font must be {name, parts} 每个字体都必须是 {name, parts} +@msg each font must be {{name, parts}} 每个字体都必须是 {{name, parts}} @msg unknown key `{k}`; a font takes name and parts 未知键 `{k}`;字体可用的键为 name 和 parts @msg each font needs a name 每个字体都需要名称 @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` 不能用作复合字体的名称(1 到 {COMPOSITE_NAME_MAX} 个字符,不含控制字符) @@ -3774,7 +3863,7 @@ digits Malayalam 马拉雅拉姆数字 @msg two composite fonts are named `{_1}` 有两个复合字体都名为 `{_1}` @msg `{_1}` is the name of an installed font `{_1}` 是已安装字体的名称 @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`:{_2} 使用了复合字体 `{font}` -@msg give fonts: [{name, parts}…] 请指定 fonts:[{name, parts}…] +@msg give fonts: [{{name, parts}}…] 请指定 fonts:[{{name, parts}}…] @msg path is empty path 为空 @msg fonts must be a list of composite fonts fonts 必须是复合字体列表 @msg names must be strings names 必须是字符串 @@ -3856,6 +3945,13 @@ digits Malayalam 马拉雅拉姆数字 Threshold 阈值 Thumbnail View 缩略图视图 Tile 平铺 + Tile All Vertically 全部垂直平铺 + Tile All Horizontally 全部水平平铺 + 2-Up Layout 双联布局 + 3-Up Layout 三联布局 + 4-Up Layout 四联布局 + 6-Up Layout 六联布局 + Arrange Documents 排列文档 Tile Edge Color 拼贴边缘颜色 Tile Edge Color… 拼贴边缘颜色… Tile Full Pages 并排完整页面 @@ -4061,6 +4157,8 @@ digits Malayalam 马拉雅拉姆数字 V Spacing: 垂直间距: V: V: Variable Width Profile 变量宽度配置文件 + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. 描边的画笔保持其自身大小,因此宽度配置文件不会改变它。移除画笔即可使用配置文件。 +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. 描边的画笔保持其自身大小,因此宽度配置文件不会改变它。移除画笔即可使用配置文件。 Variables 变量 New Variable 新建变量 Delete Variable 删除变量 @@ -4070,6 +4168,13 @@ digits Malayalam 马拉雅拉姆数字 @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} 数据集超过 {MAX_CSV_ROWS} 个:“导入数据集”最多读取 {MAX_CSV_ROWS} 个 @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} 变量超过 {MAX_CSV_COLS} 个:“导入数据集”最多读取 {MAX_CSV_COLS} 个 @msg variables that aren't text were left out: {kinds} 已省略非文本变量:{kinds} +variable-kind Visibility 可见性 +variable-kind Linked File 链接文件 +variable-kind Graph Data 图表数据 +variable-kind Unknown 未知 +variable-list-two {0}, {1} {0}和{1} +variable-list-middle {0}, {1} {0}、{1} +variable-list-end {0}, {1} {0}和{1} @msg a new document won't read these variables back with their kind: {names} 新文档不会按原类型读回这些变量:{names} @msg a new document refuses this file because of these variables: {names} 新文档会因这些变量而拒绝此文件:{names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them `{name}` 的标题 `{header}` 会被读作变量 `{other}`:请重命名其中一个 @@ -4133,7 +4238,7 @@ digits Malayalam 马拉雅拉姆数字 Vertical: 垂直: Very High 极高 View 视图 - View Artboard Only 仅查看画板 + View Artboard Contents Only 仅查看画板内容 View Opacity Mask 查看不透明度蒙版 View PDF after saving 存储后查看 PDF View {n} 查看 {n} @@ -4394,6 +4499,7 @@ imageTrace Outline 轮廓 @msg Live Paint: select paths or compound paths 实时上色:请选择路径或复合路径 @msg Live Paint: these paths are too degenerate to paint 实时上色:这些路径过于退化,无法上色 @msg Shape Builder: no region under the pointer 形状生成器:指针下方没有区域 +@msg Shape Builder: select all paths you want to merge 形状生成器:请选择要合并的所有路径 @msg Shape Builder: select paths or compound paths 形状生成器:请选择路径或复合路径 @msg image data `{_1}` is missing 缺少图像数据 `{_1}` @msg no Live Paint edge near that point 该点附近没有实时上色边缘 @@ -4448,6 +4554,7 @@ imageTrace Outline 轮廓 @msg Expand: no gradient fills 扩展:没有渐变填色 @msg Expand: nothing to expand 扩展:没有可扩展的内容 @msg batch step {_1} (`{id}`) failed: {e} 批处理步骤 {_1} (`{id}`) 失败:{e} +@msg action step {_1} (`{id}`) failed: {reason} 动作步骤 {_1} (`{id}`) 失败:{reason} @msg BMP files are RGB or grayscale: colorModel rgb or gray BMP 文件为 RGB 或灰度:colorModel rgb 或 gray @msg Targa files are RGB: colorModel rgb Targa 文件为 RGB:colorModel rgb @msg antiAlias `{id}`: none, art or type antiAlias `{id}`:none、art 或 type @@ -4541,8 +4648,8 @@ imageTrace Outline 轮廓 @msg image would be too large; lower the resolution 图像将过大;请降低分辨率 @msg clipboard is empty 剪贴板为空 @msg no anchor points selected 未选择锚点 -@msg `points` must be three [x, y] pairs of numbers `points` 必须是三对数字 [x, y] -@msg direct-select three anchor points, or give `points` 请直接选择三个锚点,或提供 `points` +@msg `points` must be two or three [x, y] pairs of numbers `points` 必须是两对或三对数字 [x, y] +@msg direct-select two or three anchor points, or give `points` 请直接选择两个或三个锚点,或提供 `points` @msg no circle passes through these points: two are the same or all three lie on one line 没有圆经过这些点:有两点相同,或三点共线 @msg select at least two objects 请至少选择两个对象 @msg exit isolation mode first 请先退出隔离模式 @@ -4584,6 +4691,8 @@ imageTrace Outline 轮廓 @msg {label}: lost track of a shape's style {label}:丢失了某个形状的样式 @msg {label}: select paths {label}:请选择路径 @msg {label}: select paths, compound paths, groups or text {label}:请选择路径、复合路径、编组或文字 +@msg a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first 直线或其他不围成区域的开放路径不会改变结果的形状;要包含它,请先对其应用“对象 › 路径 › 轮廓化描边” +@msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first {label} 生成了空结果:直线或其他开放路径不围成区域;要包含它,请先对其应用“对象 › 路径 › 轮廓化描边” @msg already editing a pattern 已在编辑图案 @msg no pattern `{name}` 没有图案 `{name}` @msg not in pattern editing mode 不在图案编辑模式中 @@ -4659,6 +4768,7 @@ imageTrace Outline 轮廓 @msg Create Outlines: select text objects 创建轮廓:请选择文本对象 @msg paste unavailable 无法粘贴 @msg Save for Web: the image is empty 存储为 Web 所用格式:图像为空 +@msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted:颜色表中至少要保留一种颜色 @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}:`{h}` 不是颜色,例如 "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}:最多 {MAX_TABLE} 种颜色 @msg no artboard {i} (0-based; the document has {_1}) 没有画板 {i} (从 0 开始计数;文档有 {_1} 个) @@ -4895,6 +5005,12 @@ imageTrace Outline 轮廓 @msg no preset editor 没有预设编辑器 @msg no perspective grid preset named `{name}` 没有名为 `{name}` 的透视网格预设 @msg no active perspective plane 没有活动的透视平面 +@msg the perspective grid is hidden 透视网格已隐藏 +@msg Automatic Plane Positioning is off: turn on anchorPoint or gridlineIntersection (perspective.widget.options) 自动平面定位已关闭:请打开 anchorPoint 或 gridlineIntersection (perspective.widget.options) +@msg anchorPoint must be true or false anchorPoint 必须为 true 或 false +@msg gridlineIntersection must be true or false gridlineIntersection 必须为 true 或 false +@msg tolerance must be 0 or more tolerance 必须大于或等于 0 +@msg give `at` or `clear`, not both 请给出 `at` 或 `clear`,不能两者都给 @msg plane must be left, right or ground plane 必须是 left、right 或 ground @msg missing `id` (see plugin.list) 缺少 `id` (请参阅 plugin.list) @msg no plug-in {id} is installed 未安装增效工具 {id} @@ -4945,6 +5061,9 @@ imageTrace Outline 轮廓 @msg `{color}` is not a colour (#rrggbb or a preset name) `{color}` 不是颜色 (#rrggbb 或预设名称) @msg give the path `id` and the width point `index` 请给出路径的 `id` 和宽度点的 `index` @msg no such width point 没有此宽度点 +@msg `single` must be `incoming` or `outgoing` `single` 必须是 `incoming` 或 `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` 和 `outIndex` 必须是同一个不连续宽度点的两半 +@msg a discontinuous width point keeps its place 不连续宽度点保持原位 @msg onto must name a panel floating in another group onto 必须指定浮动在另一个组中的面板 @msg below and above must name a panel floating in another group below 和 above 必须指定浮动在另一个组中的面板 @msg give only one of onto, below and above onto、below 和 above 只能给出一个 @@ -4974,6 +5093,8 @@ imageTrace Outline 轮廓 @msg No saved views (View → New View…) 没有已保存的视图 (视图 → 新建视图…) @msg `command` must be a command whose menu item opens a dialog (see ui.menuDialog) `command` 必须是其菜单项会打开对话框的命令 (请参阅 ui.menuDialog) @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` 必须是 grayscale、rgb、hsb、cmyk 或 websafe +@msg `view` must be wheel or box `view` 必须是 wheel 或 box +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` 必须是 hue、saturation、brightness、red、green 或 blue @msg `{key}` must be true or false `{key}` 必须是 true 或 false @msg `top` and `below` can't both be true `top` 和 `below` 不能同时为 true @msg `select` must be true or false `select` 必须是 true 或 false @@ -5052,6 +5173,13 @@ imageTrace Outline 轮廓 Show External Script Warning 显示外部脚本警告 A Script Is Running 脚本正在运行 Script Alert 脚本提示 + Script File Access 脚本文件访问 + The script asks to read a file you choose. 脚本请求读取您选择的文件。 + The script asks to read and write a file you choose. 脚本请求读写您选择的文件。 + The script asks to read and write a folder you choose, with everything in it. 脚本请求读写您选择的文件夹及其中的所有内容。 + Allow Once 允许一次 + Always Allow This Script 始终允许此脚本 + Deny 拒绝 A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. 脚本可以更改打开的文档,并可通过其运行的命令写入文件。请只运行您信任的脚本。 Do not show this warning again 不再显示此警告 Stop the script and undo what it did? Then quit again. 要停止脚本并撤销其更改吗?然后请再次退出。 @@ -5068,6 +5196,8 @@ imageTrace Outline 轮廓 @msg the script is no longer in the Scripts folder 脚本已不在 Scripts 文件夹中 Some scripts were not listed 部分脚本未列出 The Scripts folder cannot be read 无法读取 Scripts 文件夹 + Loading scripts… 正在载入脚本… + The Scripts folder is still being read 仍在读取 Scripts 文件夹 @msg the script's run is no longer available 脚本运行已不可用 @msg a failed command changed undo steps that could not be put back, so the script was stopped 失败的命令更改了无法恢复的撤销步骤,因此脚本已停止 @msg a recovery copy could not be written, so the script was not run 无法写入恢复副本,因此未运行脚本 @@ -5080,8 +5210,6 @@ imageTrace Outline 轮廓 @msg Script file could not be read 无法读取脚本文件 @msg Script folder has more than 2,048 entries 脚本文件夹的条目超过 2,048 个 @msg Script file open mode must be r, w, e or a 脚本文件的打开模式必须是 r、w、e 或 a -@msg Script file writing is not available 脚本文件写入不可用 -@msg Script file dialogs are not available 脚本文件对话框不可用 @msg Script files cannot be opened in another application 脚本文件无法在其他应用程序中打开 @msg Script file access is unavailable on the web 网页版无法访问脚本文件 @msg Script has 256 files open 脚本已打开 256 个文件 @@ -5198,6 +5326,27 @@ liquify-list-end {0}, {1} {0}和{1} @msg there is no script engine named {name} 没有名为 {name} 的脚本引擎 @msg Running a script 正在运行脚本 @msg Copied the script report 已复制脚本报告 +@msg Script file access denied: {path} 脚本的文件访问被拒绝:{path} +@msg Script file access to the app's own folders is not allowed 不允许脚本访问应用自身的文件夹 +@msg Script file cannot encode the text 脚本的文件无法编码该文本 +@msg Script file could not be written 无法写入脚本的文件 +@msg Script file dialogs need a person to answer them 脚本的文件对话框需要有人回答 +@msg Script file is not open for writing 脚本的文件未以写入方式打开 +@msg Script file name is already in use 脚本的文件名已被使用 +@msg Script file name must be a name without a folder 脚本的文件名必须是不含文件夹的名称 +@msg Script file permission can be kept only for a script run from a file 只有从文件运行的脚本才能保留文件权限 +@msg Script file permission could not be saved 无法保存脚本的文件权限 +@msg Script folder is not empty 脚本的文件夹不为空 +@msg Script files cannot make aliases 脚本的文件无法创建别名 +@msg Script file hidden setting cannot be changed 无法更改脚本文件的隐藏设置 +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}:文件对话框不能在内置函数、getter、转换或 $.evalFile 运行的文件的回调中打开;请从脚本自身的代码中调用 +@msg the script wrote more file data than one run may write (32 MiB) 脚本写入的文件数据超过了一次运行可写入的上限 (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop 脚本文件对话框的 `answer` 必须是以下之一:once、always、deny、stop +@msg choose a file or folder first, or deny 请先选择文件或文件夹,或拒绝 +@msg the script file permissions could not be saved: {e} 无法保存脚本的文件权限:{e} +@msg this script's file access can be allowed only once 此脚本的文件访问只能允许一次 +@msg Only the person at the keyboard can allow a script's file access 只有键盘前的人才能允许脚本访问文件 +@msg A script is given at most 2,048 files: the files picked after them were left out 脚本最多获得 2,048 个文件:之后选择的文件已被略去 @msg Copied the link info 已复制链接信息 @msg Exported {path} 已导出 {path} @msg no CSS to copy: select objects with CSS of their own 没有可复制的 CSS:请选择带有自身 CSS 的对象 @@ -5234,6 +5383,8 @@ liquify-list-end {0}, {1} {0}和{1} @msg All colors are within the CMYK gamut 所有颜色皆在 CMYK 色域内 @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} 个颜色超出 CMYK 色域 @msg Unembedded to {_1} 已取消嵌入到 {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} 已将 {n} 张图像取消嵌入到 {folder} +@msg every numbered name for {name} is taken in that folder 该文件夹中 {name} 的所有带编号的名称均已被占用 @msg no swatch library `{l}` (see swatch.library.list) 没有色板库 `{l}` (请参阅 swatch.library.list) @msg no user library folder here 此处没有用户库文件夹 @msg Couldn't place {name}: the document it was dropped on was closed 无法置入 {name}:将它拖放到的文档已关闭 @@ -5259,6 +5410,9 @@ liquify-list-end {0}, {1} {0}和{1} @msgplural Discarded {n} recovered document|Discarded {n} recovered documents 已丢弃 {n} 个恢复的文档 @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them 已还原 {n} 个恢复的文档:请保存以保留它们 @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} 已打开,有 {n} 条注释:{first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} 已复制,有 {n} 条注释:{first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} 已剪切,有 {n} 条注释:{first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} 已描摹图像,有 {n} 条注释:{first} @msgplural {notice}. Opened with {n} note: {first}|{notice}. Opened with {n} notes: {first} {notice}。已打开,有 {n} 条注释:{first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} 已保存 {path},有 {n} 条注释:{first} @msg Saving recovery data for {_1} 正在保存 {_1} 的恢复数据 @@ -5286,6 +5440,8 @@ liquify-list-end {0}, {1} {0}和{1} @msg the {tool} tool has no options {tool} 工具没有选项 @msg unknown tool `{tool}` 未知工具 `{tool}` @msg {tool} isn't in a toolbar group of several tools {tool} 不在包含多个工具的工具栏组中 +@msg Presentation Mode hides the toolbars: change the screen mode to show them 演示模式会隐藏工具栏:请更改屏幕模式以显示工具栏 +@msg Tab has hidden the toolbars: press Tab to show them Tab 已隐藏工具栏:请按 Tab 以显示工具栏 @msg no such document 没有此文档 @msg {_1}: not saved, so not closed {_1}:未保存,因此未关闭 @msg `{name}` is a built-in workspace; choose another name `{name}` 是内置工作区;请选择其他名称 @@ -5333,6 +5489,9 @@ liquify-list-end {0}, {1} {0}和{1} @msg automation path rejected: outside the read root {root}: {path} 已拒绝自动化路径:位于读取根目录 {root} 之外:{path} @msg automation path rejected: outside the read roots {roots}: {path} 已拒绝自动化路径:位于所有读取根目录 {roots} 之外:{path} @msg a linked JavaScript file is outside the read roots 链接的 JavaScript 文件位于所有读取根目录之外 +@msg a linked image file is outside the read roots 链接的图像文件位于所有读取根目录之外 +@msg a linked file's export folder is outside the read roots 链接文件的导出文件夹位于所有读取根目录之外 +@msg a linked file's editing data can't be read to check it against the read roots 无法读取链接文件的编辑数据,因此无法对照读取根目录进行检查 @msg automation path rejected: outside the write root {root}: {path} 已拒绝自动化路径:位于写入根目录 {root} 之外:{path} @msg automation path rejected: outside the write roots {roots}: {path} 已拒绝自动化路径:位于所有写入根目录 {roots} 之外:{path} @msg automation path rejected: path is empty 已拒绝自动化路径:路径为空 @@ -5842,6 +6001,7 @@ font-technology Variable 可变 Bevel 斜角 Offset 偏移 Axis 轴 + Axis Angle 轴角度 axis Horizontal 水平 axis Vertical 垂直 axis Both 两者 @@ -5891,7 +6051,7 @@ axis Both 两者 Constrain 约束 Perspective Distort 透视扭曲 -# Photoshop-style raster effects (Effect menu, their dialogs). +# Raster effects (Effect menu, their dialogs). Radial Blur… 径向模糊… Blur Center 模糊中心 Smart Blur… 智能模糊… @@ -6103,6 +6263,7 @@ lighting Light 光源 Horizontal Guide 水平参考线 Move Guide to Layer 将参考线移至图层 Linux Display Server Linux 显示服务器 + Low-Latency Drawing 低延迟绘图 X11 (XWayland) When a Pen Is Attached 连接手写笔时使用 X11 (XWayland) If a drawing tablet's pen doesn't draw, choose an X11 (XWayland) option. 如果数位板的笔无法绘画,请选择一个 X11 (XWayland) 选项。 X11 (XWayland) X11 (XWayland) @@ -6154,6 +6315,7 @@ lighting Light 光源 Cove 凹圆 Depth 深度 Front 正面 + Side 侧面 Isometric Bottom 等角底部 Isometric Left 等角左侧 Isometric Right 等角右侧 @@ -6248,7 +6410,7 @@ lighting Light 光源 @msg each of `{GRAPHICS}` must be an object `{GRAPHICS}` 的每个条目必须是对象 @msg `{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}` `{GRAPHICS}` 的条目接受 symbol、face、x、y、scale 和 rotation,不接受 `{k}` @msg each of `{GRAPHICS}` needs `symbol`, the name of a symbol `{GRAPHICS}` 的每个条目都需要 `symbol`,即符号的名称 -@msg `{GRAPHICS}` face must be front or back `{GRAPHICS}` 的 face 必须是 front 或 back +@msg `{GRAPHICS}` face must be front, back or side `{GRAPHICS}` 的 face 必须是 front、back 或 side @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} `{GRAPHICS}` 的 {key} 必须是 {lo} 到 {hi} 之间的数字 @msg `{GRAPHICS}` must be an array `{GRAPHICS}` 必须是数组 @msg Graphics map onto the Plane, Extrude and Revolve object types 图形映射到平面、突出和回转对象类型上 @@ -7223,6 +7385,12 @@ anchor Points: 点: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` 必须是 "free"、"keepAngles" 或 "symmetric" @msg `{key}` must be [x, y] `{key}` 必须是 [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter 单位换算器 + Unit Converter Panel 单位换算器面板 + Copy with Units 复制时包含单位 + From Selection 从所选对象 + # Color Effects add-on: Select by Color Kind. Select by Color Kind 按颜色类型选择 Objects with Spot Colors 使用专色的对象 @@ -7447,6 +7615,14 @@ breakText Glyphs 字形 Remove Gaps 移除间隙 @msg that makes too many pieces (at most 100000): make the dashes longer 这会产生过多片段(最多 100000 个):请加长短划线 @msg select paths, or segments, to divide 请选择要分割的路径或线段 +# Path Precision Tools add-on: Smooth Bridge. + Smooth Bridge… 平滑桥接… + Smooth Bridge 平滑桥接 + Keep Originals 保留原稿 +@msg select two circles to bridge 请选择两个要桥接的圆 +@msg one circle is inside the other 一个圆位于另一个圆内部 +@msg the circles are too far apart for this radius: raise the radius 对于此半径,两个圆相距太远:请增大半径 +@msg the circles are too far apart for this radius 对于此半径,两个圆相距太远 # Path Precision Tools add-on: Common Tangents. Common Tangents… 公切线… Common Tangents 公切线 @@ -7819,6 +7995,14 @@ breakText Glyphs 字形 @msg `answers` has more than {MAX_ANSWERS} answers `answers` 中的回答超过 {MAX_ANSWERS} 个 @msg `answers` is larger than 1 MiB `answers` 大于 1 MiB @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` 仅用于无人可问的运行:在应用中,由用户回答每个对话框 +@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` 必须是 1 到 {_1} 之间的整数 +@msg `args{place}` is nested more than 64 levels deep `args{place}` 的嵌套超过 64 层 +@msg `args` must be an object `args` 必须是对象 +@msg `args` is larger than 1 MiB `args` 大于 1 MiB +@msg `path` is empty `path` 为空 +@msg `installed` takes a `path`, not a `source` `installed` 需要 `path`,而不是 `source` +@msg `path` must name a .js or .jsx file `path` 必须指向 .js 或 .jsx 文件 +@msg give exactly one of `path` and `source` `path` 和 `source` 中必须且只能给出一个 @msg `answers` must be a list of answers `answers` 必须是回答的列表 @msg `artboard` must be the index of an artboard of the document `artboard` 必须是文档中某个画板的索引 @msg `artboardsAt` must be [x, y] `artboardsAt` 必须是 [x, y] @@ -7862,7 +8046,7 @@ breakText Glyphs 字形 @msg `rows` must be lists of numbers or nulls, not {r} `rows` 必须是由数字或 null 组成的列表,不能是 {r} @msg `scale` must be a number from 0.001 to 1000 `scale` 必须是 0.001 到 1000 之间的数字 @msg `scope.{key}` must be a non-empty array `scope.{key}` 必须是非空数组 -@msg `scope` must be "document", {artboards} or {layers} `scope` 必须是 "document"、{artboards} 或 {layers} +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` 必须是 "document"、{{artboards: [index, …]}} 或 {{layers: [id, …]}} @msg `side` must be "left", "right", "top" or "bottom" `side` 必须是 "left"、"right"、"top" 或 "bottom" @msg `side` places the artboard: leave out x, y, width and height `side` 决定画板的位置:请不要给出 x、y、width 和 height @msg `source` is the only path in series group `target` `source` 是系列组 `target` 中唯一的路径 @@ -8048,7 +8232,7 @@ breakText Glyphs 字形 @msg not a regular expression 不是正则表达式 @msg not an action set: the text doesn't start with /version and a number 不是动作组:文本不是以 /version 和一个数字开头 @msg nothing to repeat 没有可重复的内容 -@msg numbers out of order in {_1} quantifier 量词 {_1} 中的数字顺序颠倒 +@msg numbers out of order in {{}} quantifier 量词 {{}} 中的数字顺序颠倒 @msg object {_1} needs a 3D effect 对象 {_1} 需要有 3D 效果 @msg object {_1}: a hollow Extrude & Bevel has no caps: turn on Cap to map a graphic 对象 {_1}:空心的突出与斜角没有端面:请打开“端点”后再贴图 @msg object {_1}: with a depth of 0 the object has one face: map its graphics onto the front 对象 {_1}:深度为 0 时对象只有一个面:请将图形贴到正面 @@ -8121,7 +8305,7 @@ breakText Glyphs 字形 @msg the library's file is outside the read roots 库文件位于可读取的根目录之外 @msg the line is too long, or the paths it passes too many, to check 线条过长,或它经过的路径过多,无法检查 @msg the method needs an XML value 此方法需要 XML 值 -@msg the paint is not a freeform gradient (apply one with paint.editGradient {kind}) 该上色不是自由渐变 (请用 paint.editGradient {kind} 应用一个) +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) 该上色不是自由渐变 (请用 paint.editGradient {{kind: "freeform"}} 应用一个) @msg the parameters or body do not form one function 参数或函数体不能构成一个函数 @msg the pasted SVG filter {name} draws differently from the document's filter of that name, and no free name fits it 粘贴的 SVG 滤镜 {name} 与文档中同名滤镜的绘制结果不同,且没有可用的空闲名称 @msg the paths are too many or too tangled to find where they cross 路径过多或过于交错,无法找出它们的交叉位置 @@ -8413,6 +8597,8 @@ breakText Glyphs 字形 @msg `{f}` is the copy of a document open now `{f}` 是当前已打开文档的副本 @msg `{id}` is no writable format (see document.formats) `{id}` 不是可写入的格式 (参见 document.formats) @msg `{id}` isn't a loaded library `{id}` 不是已载入的库 +@msg `{file}` has no swatches of its own `{file}` 没有自己的色板 +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` 含有图案色板,.vcswatches 文件无法保存 @msg `{key}` has no colours `{key}` 中没有颜色 @msg `{key}` is a design name `{key}` 是设计名称 @msg `{key}` is a design name or a list of them `{key}` 是一个设计名称或设计名称的列表 @@ -8635,7 +8821,13 @@ breakText Glyphs 字形 @msg colorModel must be {own} (the document's mode), grayscale or bitmap colorModel 必须是 {own} (文档的模式)、grayscale 或 bitmap @msg colour groups can't go into colour groups 颜色组不能放入颜色组 @msg colour, mode and spot apply to solid-colour swatches only colour、mode 和 spot 只适用于纯色色板 -@msg column {column}: `{cell}` is a `%` column of graph data files, which are not read 第 {column} 列:`{cell}` 是图表数据文件的 `%` 列,不会读取 +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path 第 {line} 行,第 {column} 列:`{var}` 的图表数据文件 `{path}` 是相对路径:请提供 `base` 或绝对路径 +@msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} 第 {line} 行,第 {column} 列:无法读取 `{var}` 的图表数据文件:{e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` isn't followed: {r} 第 {line} 行,第 {column} 列:未跟随 `{var}` 的图表数据文件 `{path}`:{r} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes 第 {line} 行,第 {column} 列:`{var}` 的图表数据文件 `{path}` 超过 {MAX_GRAPH_DATA_FILE} 字节 +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes 第 {line} 行,第 {column} 列:`{var}` 的图表数据文件 `{path}` 得到的图表值超过 {MAX_GRAPH_CSV} 字节 +@msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all 第 {line} 行,第 {column} 列:图表数据文件总计超过 {MAX_GRAPH_FILES_TOTAL} 字节 +@msg `base` is empty `base` 为空 @msg column {column}: `{cell}` names `{name}`, which is a {_1} variable 第 {column} 列:`{cell}` 指定了 `{name}`,而它是 {_1} 变量 @msg column {column}: `{cell}` names no variable 第 {column} 列:`{cell}` 没有对应的变量 @msg column {column}: the variable name is longer than {MAX_NAME} characters 第 {column} 列:变量名称超过 {MAX_NAME} 个字符 @@ -8646,6 +8838,7 @@ breakText Glyphs 字形 @msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes 复合形状接受路径、复合路径、编组、复合形状、文字、混合和封套 @msg compound {_1} must contain exactly one open path to join 复合对象 {_1} 必须恰好包含一条要连接的开放路径 @msg connect needs a path other than the one extended connect 需要一条不同于被延伸路径的路径 +@msg connect needs extend connect 需要 extend @msg connect needs id connect 需要 id @msg connect path has no open end connect 的路径没有开放的端点 @msg copy needs path: the file to copy into the document's folder copy 需要 path:即要复制到文档所在文件夹的文件 @@ -9757,4 +9950,14 @@ breakText Glyphs 字形 @msg A panel is not joined to the rest by a crease. 一个面板没有通过任何压痕线与其余部分相连。 @msg A fold line is on a non-printing layer. 一条折线位于不打印的图层上。 @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} 面板:{panels},铰链:{hinges},错误:{errors},警告:{warnings} + Fold Preview 折叠预览 + Fold 折叠 + Show Fold Lines 显示折线 + Three-Quarter 四分之三视图 + Open a document to preview its folded shape. 打开文档以预览其折叠后的形状。 +@msg Check the fold lines first. 请先检查折线。 +@msg Panels: {panels}, hinges: {hinges} 面板:{panels},铰链:{hinges} +@msg Other blanks not shown: {count} 未显示的其他展开图:{count} +@msg A joint does not close by {gap} pt. 有一处接缝相差 {gap} pt 未闭合。 +@msg Two panels pass through each other. 两个面板相互穿插。 @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} 像素对 PSD 而言过大 (每边最多 {MAX_SIDE} 像素):请降低分辨率 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 1480422931..ebcc33d25f 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -77,6 +77,7 @@ Add Anchor Point 增加錨點 Add Anchor Point Tool 增加錨點工具 Add Anchor Points 增加錨點 + Add Around 繞物件新增 Add Effect 新增效果 Add Freeform Line 新增任意線條 Add Freeform Point 新增任意形狀錨點 @@ -98,8 +99,12 @@ Add to Swatches 新增至色票 Add Used Colors 新增使用中的顏色 Additional Plug-ins Folder 額外的增效模組資料夾 + Plug-in Instruction Budget 增效模組指令預算 Additional Fonts Folder 額外的字體資料夾 Adjust Adjoining Width Points 調整相鄰寬度點 + Incoming 入側 + Outgoing 出側 + Single Width Only 僅保留一個寬度 Adjust Color Balance… 調整色彩平衡… Adjust Colors 調整顏色 Adjust Options: 調整選項: @@ -154,6 +159,7 @@ Angle: 角度: Angles 角度 Animated Zoom 動畫縮放 + Anti Alias 消除鋸齒 Anti-alias 消除鋸齒 Anti-Alias 消除鋸齒 Anti-alias Rasters 點陣影像消除鋸齒 @@ -325,6 +331,12 @@ font-technology Variable 可變 Brush Definition 筆刷定義 Brush Libraries 筆刷資料庫 Brush Options… 筆刷選項… + Options of Selected Object… 所選物件的選項… + Options of Selected Object 所選物件的選項 +@msg no path painted with a brush is selected 未選取以筆刷繪製的路徑 +@msg the selected paths are painted with brushes of different types 所選路徑使用了不同類型的筆刷 +@msg give `params` or `reset`, not both 請提供 `params` 或 `reset`,不能同時提供 +@msg a bristle brush has no options of its own on a path 鬃毛筆刷在路徑上沒有自己的選項 Brush Strokes 筆刷筆畫 Brushes 筆刷 Built-in Libraries 內建資料庫 @@ -381,6 +393,12 @@ font-technology Variable 可變 Character / Paragraph 字元/段落 Character Alignment 字元對齊 Character Rotation 字元旋轉 + Chinese Big 5 繁體中文 Big 5 + Cyrillic 西里爾文 + Greek 希臘文 + Turkish 土耳其文 + Baltic 波羅的海文 + Central European 中歐文 Character Set: 字元集: Character Style 字元樣式 Character Style Options 字元樣式選項 @@ -443,6 +461,8 @@ font-technology Variable 可變 Choose a folder 選擇資料夾 Choose… 選擇… Circle 圓形 + Circle Tool 圓形工具 + Circle too large 圓形過大 Classic Defaults 經典預設值 Clean Up… 清除… Clear 清除 @@ -518,6 +538,7 @@ font-technology Variable 可變 Color Mixer (Shift-click the chip) 混色器 (Shift-按一下色塊) Color Mode 色彩模式 Color Mode: 色彩模式: + Color Model 色彩模型 Color Model: 色彩模型: Color Models 色彩模型 Color Picker 顏色選擇器 @@ -538,12 +559,18 @@ font-technology Variable 可變 Saturation and brightness 飽和度和亮度 Color field 顏色區域 {name1} {value1}, {name2} {value2} {name1} {value1},{name2} {value2} + Wheel View 色輪檢視 + Box View 方塊檢視 + Box Channel 方塊色版 + Color box 顏色方塊 + Color Wheel Options 色輪選項 Color Type: 顏色類型: Color: 顏色: Colorize 上色 Colors 顏色 Colors: 顏色: Column Graph Tool 長條圖工具 + Columns 欄數 Columns: 欄數: Column… 欄… Combine Slices 合併切片 @@ -754,6 +781,8 @@ font-technology Variable 可變 Delete Artboard 刪除工作區域 Delete Artboards 刪除工作區域 Delete Brush 刪除筆刷 + Delete Color 刪除顏色 + Restore Generated Table 還原產生的色彩表 Delete Character Style 刪除字元樣式 Delete Empty Artboards 刪除空白工作區域 Delete Freeform Point 刪除任意形狀錨點 @@ -822,6 +851,7 @@ font-technology Variable 可變 Direct Selection Tool 直接選取工具 Direction Handles 控制把手 Disable Auto Add/Delete 停用自動增加/刪除 + Interpolate Control Points When Moving Anchors 移動錨點時內插控制把手 Disable Opacity Mask 停用不透明度遮色片 Discard 捨棄 Preserve 保留 @@ -1015,6 +1045,9 @@ font-technology Variable 可變 Cap Height 大寫字母高度 x-Height x 字高 ICF Box ICF 框 + Ascent 上緣 + x Height x 字高 + Em Box Height 全形字框高度 Show Sample 顯示樣本 Hide Sample 隱藏樣本 Max Ascent/Descent 最大上升/下降 @@ -1047,6 +1080,7 @@ font-technology Variable 可變 Enable text access for screen readers 啟用螢幕閱讀器的文字存取 Enable Touch Gestures 啟用觸控手勢 Switch Selection and Drawing Modes 切換選取與繪圖模式 + Select Last Selection Tool 切換到上次使用的選取工具 Enable Touch Workspace 啟用觸控工作區 Encoding 編碼 Encoding: 編碼: @@ -1229,6 +1263,8 @@ font-technology Variable 可變 Files 檔案 Files of a PDF standard can't be password-protected. PDF 標準的檔案無法設定密碼保護。 Files of this standard tag their colours with ICC profiles. 此標準的檔案會以 ICC 描述檔標記顏色。 + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. 此標準的檔案會以 ICC 描述檔標記顏色,但輸出目的描述檔中的 CMYK 顏色會寫為 DeviceCMYK。 + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. 選擇「不包含描述檔」且輸出目的為 CMYK 時,除非轉換為其他描述檔的 CMYK 目的地,否則每種 CMYK 顏色都會寫為 DeviceCMYK。 Fill 填色 Fill & Stroke 填色與筆畫 Fill (X), double-click for the Color Picker 填色 (X),按兩下開啟檢色器 @@ -1279,6 +1315,8 @@ font-technology Variable 可變 Reset Tracking and Kerning 重設字距與字距微調 Reset Horizontal Scale 重設水平縮放 Highlight Font Name 反白顯示字體名稱 + Highlight Font Size 反白顯示字體大小 + Other… 其他… Highlight Kerning 反白顯示字距微調 Highlight Tracking 反白顯示字距 Spacing 間距 @@ -1929,6 +1967,7 @@ file-filter Templates 範本 @msg Live Paint: select paths or compound paths 即時上色:請選取路徑或複合路徑 @msg Live Paint: these paths are too degenerate to paint 即時上色:這些路徑過度退化,無法上色 @msg Shape Builder: no region under the pointer 形狀建立:指標下方沒有區域 +@msg Shape Builder: select all paths you want to merge 形狀建立:請選取要合併的所有路徑 @msg Shape Builder: select paths or compound paths 形狀建立:請選取路徑或複合路徑 @msg image data `{_1}` is missing 找不到影像資料 `{_1}` @msg no Live Paint edge near that point 該點附近沒有即時上色邊緣 @@ -1983,6 +2022,7 @@ file-filter Templates 範本 @msg Expand: no gradient fills 展開:沒有漸層填色 @msg Expand: nothing to expand 展開:沒有可展開的內容 @msg batch step {_1} (`{id}`) failed: {e} 批次步驟 {_1} (`{id}`) 失敗:{e} +@msg action step {_1} (`{id}`) failed: {reason} 動作步驟 {_1} (`{id}`) 失敗:{reason} @msg BMP files are RGB or grayscale: colorModel rgb or gray BMP 檔案為 RGB 或灰階:colorModel rgb 或 gray @msg Targa files are RGB: colorModel rgb Targa 檔案為 RGB:colorModel rgb @msg antiAlias `{id}`: none, art or type antiAlias `{id}`:none、art 或 type @@ -2074,8 +2114,8 @@ file-filter Templates 範本 @msg image would be too large; lower the resolution 影像會過大;請降低解析度 @msg clipboard is empty 剪貼簿是空的 @msg no anchor points selected 未選取錨點 -@msg `points` must be three [x, y] pairs of numbers `points` 必須是三組數字 [x, y] -@msg direct-select three anchor points, or give `points` 請以直接選取方式選取三個錨點,或提供 `points` +@msg `points` must be two or three [x, y] pairs of numbers `points` 必須是兩組或三組數字 [x, y] +@msg direct-select two or three anchor points, or give `points` 請以直接選取方式選取兩個或三個錨點,或提供 `points` @msg no circle passes through these points: two are the same or all three lie on one line 沒有圓通過這些點:有兩點相同,或三點共線 @msg select at least two objects 請選取至少兩個物件 @msg exit isolation mode first 請先結束隔離模式 @@ -2117,6 +2157,8 @@ file-filter Templates 範本 @msg {label}: lost track of a shape's style {label}:遺失了某個形狀的樣式 @msg {label}: select paths {label}:請選取路徑 @msg {label}: select paths, compound paths, groups or text {label}:請選取路徑、複合路徑、群組或文字 +@msg a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first 直線或其他不圍成區域的開放路徑不會改變結果的形狀;若要納入,請先對其套用「物件 › 路徑 › 外框筆畫」 +@msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first {label} 產生了空的結果:直線或其他開放路徑不圍成區域;若要納入,請先對其套用「物件 › 路徑 › 外框筆畫」 @msg already editing a pattern 已在編輯圖樣 @msg no pattern `{name}` 沒有圖樣 `{name}` @msg not in pattern editing mode 不在圖樣編輯模式中 @@ -2192,6 +2234,7 @@ file-filter Templates 範本 @msg Create Outlines: select text objects 建立外框:請選取文字物件 @msg paste unavailable 無法貼上 @msg Save for Web: the image is empty 儲存為網頁用:影像是空的 +@msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted:色彩表中至少要保留一種顏色 @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}:`{h}` 不是像 "#ff8800" 這樣的顏色 @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}:最多 {MAX_TABLE} 種顏色 @msg no artboard {i} (0-based; the document has {_1}) 沒有工作區域 {i} (從 0 起算;文件有 {_1} 個) @@ -2431,6 +2474,12 @@ file-filter Templates 範本 @msg no preset editor 沒有預設集編輯器 @msg no perspective grid preset named `{name}` 沒有名為 `{name}` 的透視格點預設集 @msg no active perspective plane 沒有作用中的透視平面 +@msg the perspective grid is hidden 透視格點已隱藏 +@msg Automatic Plane Positioning is off: turn on anchorPoint or gridlineIntersection (perspective.widget.options) 「自動平面定位」已關閉:請開啟 anchorPoint 或 gridlineIntersection (perspective.widget.options) +@msg anchorPoint must be true or false anchorPoint 必須是 true 或 false +@msg gridlineIntersection must be true or false gridlineIntersection 必須是 true 或 false +@msg tolerance must be 0 or more tolerance 必須大於或等於 0 +@msg give `at` or `clear`, not both 請提供 `at` 或 `clear`,不能同時提供兩者 @msg plane must be left, right or ground plane 必須是 left、right 或 ground @msg missing `id` (see plugin.list) 未提供 `id` (請參閱 plugin.list) @msg no plug-in {id} is installed 未安裝增效模組 {id} @@ -2481,6 +2530,9 @@ file-filter Templates 範本 @msg `{color}` is not a colour (#rrggbb or a preset name) `{color}` 不是顏色 (#rrggbb 或預設集名稱) @msg give the path `id` and the width point `index` 請提供路徑的 `id` 和寬度點的 `index` @msg no such width point 沒有這個寬度點 +@msg `single` must be `incoming` or `outgoing` `single` 必須是 `incoming` 或 `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` 和 `outIndex` 必須是同一個不連續寬度點的兩半 +@msg a discontinuous width point keeps its place 不連續寬度點保持原位 @msg onto must name a panel floating in another group onto 必須指定浮動在另一個群組中的面板 @msg below and above must name a panel floating in another group below 和 above 必須指定浮動在另一個群組中的面板 @msg give only one of onto, below and above onto、below 和 above 只能提供其中一個 @@ -2510,6 +2562,8 @@ file-filter Templates 範本 @msg No saved views (View → New View…) 沒有已儲存的檢視 (檢視 → 新增檢視…) @msg `command` must be a command whose menu item opens a dialog (see ui.menuDialog) `command` 必須是選單項目會開啟對話框的指令 (請參閱 ui.menuDialog) @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` 必須是 grayscale、rgb、hsb、cmyk 或 websafe +@msg `view` must be wheel or box `view` 必須是 wheel 或 box +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` 必須是 hue、saturation、brightness、red、green 或 blue @msg `{key}` must be true or false `{key}` 必須是 true 或 false @msg `top` and `below` can't both be true `top` 和 `below` 不能同時為 true @msg `select` must be true or false `select` 必須是 true 或 false @@ -2588,6 +2642,13 @@ file-filter Templates 範本 Show External Script Warning 顯示外部指令碼警告 A Script Is Running 指令碼正在執行 Script Alert 指令碼提示 + Script File Access 指令碼檔案存取 + The script asks to read a file you choose. 指令碼要求讀取您選擇的檔案。 + The script asks to read and write a file you choose. 指令碼要求讀寫您選擇的檔案。 + The script asks to read and write a folder you choose, with everything in it. 指令碼要求讀寫您選擇的資料夾及其中的所有內容。 + Allow Once 允許一次 + Always Allow This Script 一律允許此指令碼 + Deny 拒絕 A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. 指令碼可以變更開啟的文件,並可透過其執行的命令寫入檔案。請只執行您信任的指令碼。 Do not show this warning again 不再顯示此警告 Stop the script and undo what it did? Then quit again. 要停止指令碼並還原其變更嗎?然後請再次結束。 @@ -2604,6 +2665,8 @@ file-filter Templates 範本 @msg the script is no longer in the Scripts folder 指令碼已不在 Scripts 資料夾中 Some scripts were not listed 部分指令碼未列出 The Scripts folder cannot be read 無法讀取 Scripts 資料夾 + Loading scripts… 正在載入指令碼… + The Scripts folder is still being read 仍在讀取 Scripts 資料夾 @msg the script's run is no longer available 指令碼執行已無法使用 @msg a failed command changed undo steps that could not be put back, so the script was stopped 失敗的命令變更了無法還原的復原步驟,因此指令碼已停止 @msg a recovery copy could not be written, so the script was not run 無法寫入復原副本,因此未執行指令碼 @@ -2616,8 +2679,6 @@ file-filter Templates 範本 @msg Script file could not be read 無法讀取指令碼檔案 @msg Script folder has more than 2,048 entries 指令碼資料夾的項目超過 2,048 個 @msg Script file open mode must be r, w, e or a 指令碼檔案的開啟模式必須是 r、w、e 或 a -@msg Script file writing is not available 無法使用指令碼檔案寫入 -@msg Script file dialogs are not available 無法使用指令碼檔案對話方塊 @msg Script files cannot be opened in another application 指令碼檔案無法在其他應用程式中開啟 @msg Script file access is unavailable on the web 網頁版無法存取指令碼檔案 @msg Script has 256 files open 指令碼已開啟 256 個檔案 @@ -2733,8 +2794,37 @@ liquify-list-end {0}, {1} {0}和{1} @msg the main script engine is new for each run and is never kept, so it cannot be dropped 主指令碼引擎在每次執行時都是新的,從不保留,因此無法捨棄 @msg there is no script engine named {name} 沒有名為 {name} 的指令碼引擎 @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` 僅適用於沒有人可詢問的執行:在應用程式中,由使用者回答每個對話框 +@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` 必須是 1 到 {_1} 之間的整數 +@msg `args{place}` is nested more than 64 levels deep `args{place}` 的巢狀層次超過 64 層 +@msg `args` must be an object `args` 必須是物件 +@msg `args` is larger than 1 MiB `args` 大於 1 MiB +@msg `path` is empty `path` 為空 +@msg `installed` takes a `path`, not a `source` `installed` 需要 `path`,而不是 `source` +@msg `path` must name a .js or .jsx file `path` 必須指向 .js 或 .jsx 檔案 +@msg give exactly one of `path` and `source` `path` 和 `source` 請只提供其中一個 @msg Running a script 正在執行指令碼 @msg Copied the script report 已複製指令碼報告 +@msg Script file access denied: {path} 指令碼的檔案存取遭拒:{path} +@msg Script file access to the app's own folders is not allowed 不允許指令碼存取應用程式本身的資料夾 +@msg Script file cannot encode the text 指令碼的檔案無法編碼該文字 +@msg Script file could not be written 無法寫入指令碼的檔案 +@msg Script file dialogs need a person to answer them 指令碼的檔案對話框需要有人回應 +@msg Script file is not open for writing 指令碼的檔案未以寫入方式開啟 +@msg Script file name is already in use 指令碼的檔案名稱已在使用中 +@msg Script file name must be a name without a folder 指令碼的檔案名稱必須是不含資料夾的名稱 +@msg Script file permission can be kept only for a script run from a file 只有從檔案執行的指令碼才能保留檔案權限 +@msg Script file permission could not be saved 無法儲存指令碼的檔案權限 +@msg Script folder is not empty 指令碼的資料夾不是空的 +@msg Script files cannot make aliases 指令碼的檔案無法建立別名 +@msg Script file hidden setting cannot be changed 無法變更指令碼檔案的隱藏設定 +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}:檔案對話框無法在內建函式、getter、轉換或 $.evalFile 執行的檔案的回呼中開啟;請從指令碼本身的程式碼中呼叫 +@msg the script wrote more file data than one run may write (32 MiB) 指令碼寫入的檔案資料超過一次執行可寫入的上限 (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop 指令碼檔案對話框的 `answer` 必須是下列之一:once、always、deny、stop +@msg choose a file or folder first, or deny 請先選擇檔案或資料夾,或拒絕 +@msg the script file permissions could not be saved: {e} 無法儲存指令碼的檔案權限:{e} +@msg this script's file access can be allowed only once 此指令碼的檔案存取只能允許一次 +@msg Only the person at the keyboard can allow a script's file access 只有鍵盤前的人才能允許指令碼存取檔案 +@msg A script is given at most 2,048 files: the files picked after them were left out 指令碼最多取得 2,048 個檔案:之後選擇的檔案已略去 @msg Copied the link info 已複製連結資訊 @msg Exported {path} 已匯出 {path} @msg no CSS to copy: select objects with CSS of their own 沒有可複製的 CSS:請選取有自己 CSS 的物件 @@ -2771,6 +2861,8 @@ liquify-list-end {0}, {1} {0}和{1} @msg All colors are within the CMYK gamut 所有顏色皆在 CMYK 色域內 @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} 個顏色超出 CMYK 色域 @msg Unembedded to {_1} 已取消內嵌至 {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} 已將 {n} 個影像取消內嵌至 {folder} +@msg every numbered name for {name} is taken in that folder 該資料夾中 {name} 的所有編號名稱都已被使用 @msg no swatch library `{l}` (see swatch.library.list) 沒有色票資料庫 `{l}` (請參閱 swatch.library.list) @msg no user library folder here 此處沒有使用者資料庫資料夾 @msg Couldn't place {name}: the document it was dropped on was closed 無法置入 {name}:放置它的文件已關閉 @@ -2796,6 +2888,9 @@ liquify-list-end {0}, {1} {0}和{1} @msgplural Discarded {n} recovered document|Discarded {n} recovered documents 已捨棄 {n} 份復原的文件 @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them 已還原 {n} 份復原的文件:請儲存以保留 @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} 已開啟,附有 {n} 則註解:{first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} 已複製,附有 {n} 則註解:{first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} 已剪下,附有 {n} 則註解:{first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} 已描圖影像,附有 {n} 則註解:{first} @msgplural {notice}. Opened with {n} note: {first}|{notice}. Opened with {n} notes: {first} {notice}。已開啟,附有 {n} 則註解:{first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} 已儲存 {path},附有 {n} 則註解:{first} @msg Saving recovery data for {_1} 正在儲存 {_1} 的復原資料 @@ -2823,6 +2918,8 @@ liquify-list-end {0}, {1} {0}和{1} @msg the {tool} tool has no options {tool} 工具沒有選項 @msg unknown tool `{tool}` 未知的工具 `{tool}` @msg {tool} isn't in a toolbar group of several tools {tool} 不在包含多個工具的工具列群組中 +@msg Presentation Mode hides the toolbars: change the screen mode to show them 簡報模式會隱藏工具列:請變更螢幕模式以顯示工具列 +@msg Tab has hidden the toolbars: press Tab to show them Tab 已隱藏工具列:請按 Tab 以顯示工具列 @msg no such document 沒有這個文件 @msg {_1}: not saved, so not closed {_1}:未儲存,因此未關閉 @msg `{name}` is a built-in workspace; choose another name `{name}` 是內建工作區;請選擇其他名稱 @@ -2862,6 +2959,9 @@ liquify-list-end {0}, {1} {0}和{1} @msg automation path rejected: outside the read root {root}: {path} 已拒絕自動化路徑:位於讀取根目錄 {root} 之外:{path} @msg automation path rejected: outside the read roots {roots}: {path} 已拒絕自動化路徑:位於所有讀取根目錄 {roots} 之外:{path} @msg a linked JavaScript file is outside the read roots 連結的 JavaScript 檔案位於所有讀取根目錄之外 +@msg a linked image file is outside the read roots 連結的影像檔案位於所有讀取根目錄之外 +@msg a linked file's export folder is outside the read roots 連結檔案的匯出資料夾位於所有讀取根目錄之外 +@msg a linked file's editing data can't be read to check it against the read roots 無法讀取連結檔案的編輯資料,因此無法對照讀取根目錄進行檢查 @msg automation path rejected: outside the write root {root}: {path} 已拒絕自動化路徑:位於寫入根目錄 {root} 之外:{path} @msg automation path rejected: outside the write roots {roots}: {path} 已拒絕自動化路徑:位於所有寫入根目錄 {roots} 之外:{path} @msg automation path rejected: path is empty 已拒絕自動化路徑:路徑是空的 @@ -3184,6 +3284,7 @@ liquify-list-end {0}, {1} {0}和{1} Load SVG into Clipboard 將 SVG 載入剪貼簿 Load Text into Clipboard 將文字載入剪貼簿 Local Libraries 本機資料庫 + Locate Layer 尋找圖層 Locate Object 尋找物件 Locate Selected Objects 尋找選取的物件 Location 位置 @@ -3394,6 +3495,7 @@ liquify-list-end {0}, {1} {0}和{1} Scatter: 散佈: Rotation: 旋轉: Rotation relative to: 旋轉相對於: + Hue Jitter: 色相抖動: Brush Scale Options 筆刷縮放選項 Scale Proportionately 等比例縮放 Stretch to Fit Stroke Length 延伸以符合筆畫長度 @@ -3430,6 +3532,7 @@ liquify-list-end {0}, {1} {0}和{1} Black becomes the stroke color and white stays white. Other colors become tints of the stroke color by their lightness. 黑色變為筆畫顏色,白色維持白色。其他顏色變為筆畫顏色的淺色,顏色越淺,淺色就越淺。 Black and white stay as they are. Dark colors become shades of the stroke color and light colors become tints of it. 黑色維持黑色,白色維持白色。其他顏色較暗時變為筆畫顏色的暗色,較亮時變為筆畫顏色的淺色。 The key color becomes the stroke color. The other colors shift their hue by the same amount and keep their saturation and brightness. 主要顏色變為筆畫顏色。其他顏色在色輪上移動與主要顏色相同的距離,並保留其飽和度和亮度。 + Roundness 圓度 Roundness: 圓度: Fixed 固定 Pressure 壓力 @@ -3736,6 +3839,9 @@ liquify-list-end {0}, {1} {0}和{1} Overprint 疊印 Overprint and Transparency Flattener 疊印與透明度平面化 Overprint and Transparency Flattener Options 疊印與透明度平面化選項 + Custom… 自訂… + Custom Transparency Flattener Options 自訂透明度平面化選項 + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS 沒有 Alpha 透明度,「疊印」決定是否保留疊印。 Overprint Black… 疊印黑色… Overprint Fill 疊印填色 Overprint Preview 疊印預視 @@ -3786,6 +3892,13 @@ liquify-list-end {0}, {1} {0}和{1} Pathfinders: 路徑管理員: Paths 路徑 Path Length 路徑長度 + Grid Size 格點大小 + Grid Colors 格點顏色 + Flattener Preset 平面化預設集 + X X + Y Y + Orange 橙色 + Purple 紫色 Paths: {paths} Anchors: {anchors} Colors: {colors} 路徑:{paths} 錨點:{anchors} 顏色:{colors} Pattern 圖樣 Pattern Editing 圖樣編輯 @@ -3845,6 +3958,7 @@ diagnostics ui 介面 Play Current Selection 播放目前選取項目 Save Actions… 儲存動作… Load Actions… 載入動作… + Replace Actions… 取代動作… Reset Actions 重設動作 Replace the current actions with the default set? 要用預設動作組取代目前的動作嗎? Append adds the default set after the current sets instead. 「附加」會改為將預設動作組加到目前動作組之後。 @@ -3860,6 +3974,10 @@ diagnostics ui 介面 Polar Grid Tool 極座標格點工具 Polygon 多邊形 Polygon Properties: 多邊形內容: + Line Properties: 直線內容: + Line Length: 直線長度: + Line Angle: 直線角度: + Constrain Pie Angle 強制扇形角度 Polygon Tool 多邊形工具 Portrait 直向 Power Saving (integrated) 節能 (內建顯示晶片) @@ -4024,6 +4142,9 @@ digits Malayalam 馬來亞拉姆數字 Real World: 真實世界: Real-time Drawing and Editing 即時繪圖與編輯 Use Monitor Profile for Canvas 畫布使用顯示器描述檔 + Refresh Monitor Profile 重新整理顯示器描述檔 +@msg turn on Use Monitor Profile for Canvas first 請先開啟「畫布使用顯示器描述檔」 +@msg this build doesn't read display profiles 此版本不讀取顯示器描述檔 The canvas is drawn in sRGB. 畫布以 sRGB 繪製。 Canvas display profile: 畫布顯示描述檔: The system matches the window to the display's colors. 系統會讓視窗符合顯示器的色彩。 @@ -4216,6 +4337,8 @@ digits Malayalam 馬來亞拉姆數字 Reselect 重新選取 Reset 重設 Reset Bounding Box 重設邊框 + Rotate Bounding Box 旋轉邊框 + Rotate Bounding Box… 旋轉邊框… Reset Envelope Mesh 重設封套網格 Reset Envelope Shape 重設封套形狀 Reset Essentials 重設基本功能 @@ -4257,6 +4380,7 @@ digits Malayalam 馬來亞拉姆數字 Reshape Segment 改變線段外框 Reshape Tool 改變外框工具 Reshape Type Area 改變區域文字外框 + Resolution 解析度 Resolution: 解析度: Responsive 回應式 Restore 還原 @@ -4283,6 +4407,7 @@ digits Malayalam 馬來亞拉姆數字 The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. 按住 Cmd/Ctrl 捲動滑鼠滾輪會橫向捲動畫布。 Dragging sideways on a numeric field's label changes the field's value. 在數值欄位的標籤上橫向拖曳可變更欄位的值。 A two-finger rotate gesture on a trackpad rotates the canvas view. 在觸控式軌跡板上以雙指旋轉手勢可旋轉畫布檢視。 + When you move anchor points, each curve with one moved end keeps its shape relative to its ends. 移動錨點時,只有一端移動的每條曲線都會保持其相對於兩端的形狀。 Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. 按住工具的快速鍵時選擇該工具,放開後重新選擇之前的工具。 Shows the bounding box while you move the selection or draw a shape. 移動選取範圍或繪製形狀時顯示邊框。 Create Trim Marks draws Japanese-style marks instead of Roman ones. 建立剪裁標記繪製日式標記,而不是西式標記。 @@ -4313,6 +4438,29 @@ digits Malayalam 馬來亞拉姆數字 The unit for East Asian type measurements, which no field uses yet. 用於東亞文字度量的單位,目前還沒有欄位使用。 When on, a number typed without a unit into a field in picas is read in points. 開啟後,在以派卡為單位的欄位中輸入的不含單位數字以點讀取。 With XML ID, object names show as XML IDs in the Layers panel, the Variables panel and Layer Options. 選擇 XML ID 時,圖層、變數和圖層選項中的物件名稱會顯示為 XML ID。 + The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl. 文字大小和行距的增量:Cmd/Ctrl+Shift+. 和 Cmd/Ctrl+Shift+, 會將字級改變一步,同時按 Alt 則改變五步;在橫排文字中,Alt 加上下方向鍵會將行距改變一步,同時按 Cmd/Ctrl 則改變五步。 + The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl. 字距調整和字距微調的增量,單位為千分之一 em:在橫排文字中,Alt 加左右方向鍵會將插入點的字距微調或所選文字的字距調整改變一步,同時按 Cmd/Ctrl 則改變五步。 + The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl. 基線位移的增量:在橫排文字中,Alt、Shift 加上下方向鍵會將基線移動一步,同時按 Cmd/Ctrl 則移動五步。 + Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts. 在字元、段落、OpenType 和字符面板中顯示日文及其他東亞文字的選項,並顯示複合字體指令。 + Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits. 在字元和段落面板中顯示阿拉伯文、希伯來文和印度系文字的選項,例如段落方向、卡希達和數字。 + The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box. 選取工具只在文字的基線、區域文字的外框或其路徑上選取文字,而不是在其框內任何位置。 + Font menus list each font by its English name; off, a font that also has a name in its own language shows that name. 字體選單以英文名稱列出每種字體;關閉時,也有本國語言名稱的字體會顯示該名稱。 + New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text. 新的區域文字會開啟自動調整大小,因此橫排文字的矩形外框會隨文字增高或縮短。 + Font lists and the Type › Font menu show a sample of each font beside its name. 字體清單和字體選單會在每種字體的名稱旁顯示該字體的樣本。 + Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on. 無論介面亮度如何,字體樣本都以深色文字繪製在白色上;僅在選單內字體預覽開啟時生效。 + How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is. 字體欄位(例如字元面板中的欄位)清單中每列的高度,也就是每個樣本的大小。 + How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first. 最近使用的字體和字體清單顯示多少個最近使用的字體(1 到 15),最新的在前。 + When you change the font or font style of text, characters the new font has no glyph for keep the font they had. 變更文字的字體或字體樣式時,新字體中沒有字符的字元會保留原來的字體。 + A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export. 畫布上的粉紅色醒目提示標出被 OpenType 功能取代的字符,例如連字;它不會列印或轉存。 + With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from. 使用文字工具選取一個字元時,畫布上會在其旁邊顯示一排可供選擇的替代字符。 + A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export. 畫布上的粉紅色醒目提示標出因找不到原字體而以替代字體繪製的文字;它不會列印或轉存。 + New type made with a Type tool starts with placeholder text, selected, so typing replaces it. 以文字工具新建的文字會以選取的預留位置文字開始,輸入的內容會取代它。 + Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list. 在段落開頭輸入 1. 或 * 等清單標記再輸入空格,該段落會變成清單。 + Fonts in this folder show in the font menus and can be used without being installed. 此資料夾中的字體會顯示在字體選單中,不需安裝即可使用。 + Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows. 對文字套用繪圖樣式時,樣式有填色或筆畫的地方會移除字元本身的填色或筆畫,以顯示樣式的顏色。 + Align and Distribute measure point type by the ink of its glyphs instead of its em box. 對齊和均分會依字符的墨跡而非全形框測量點狀文字。 + Align and Distribute measure area type by the ink of its glyphs instead of its frame. 對齊和均分會依字符的墨跡而非外框測量區域文字。 + The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box. 邊框和變形面板會依字符的墨跡而非全形框測量點狀文字。 Snaps drawing, moving and scaling to the grid's subdivisions, even while the grid is hidden; while it is on, Snap to Pixel does not apply. 即使格點已隱藏,繪製、移動和縮放仍會靠齊格點的細分;開啟期間,「靠齊像素」不會作用。 The color of guides that are not selected; an artboard with a Guide Label draws its own guides in the label's color instead. 未選取參考線的顏色;設定了參考線標籤的工作區域會以標籤顏色繪製自己的參考線。 Draws guides as solid lines or as dots, including the guides already in the document. 將參考線繪製為實線或點,包括文件中已有的參考線。 @@ -4394,6 +4542,7 @@ digits Malayalam 馬來亞拉姆數字 Rounded Rectangle Tool 圓角矩形工具 Rounded Rectangle… 圓角矩形… Row Size: 列尺寸: + Rows 列數 Rows: 列數: Rule: 規則線: Rulers 尺標 @@ -4568,6 +4717,11 @@ digits Malayalam 馬來亞拉姆數字 Search commands, tools, panels and effects… 搜尋指令、工具、面板與效果… No commands match 沒有符合的指令 {pos} of {total}: {name} 第 {pos} 個,共 {total} 個:{name} + No menu item 無選單項目 + Toolbar 工具列 + {toolbar}, in the {tool} group {toolbar},位於 {tool} 群組中 + Tool 工具 + Command 指令 @plural {n} result|{n} results {n} 個結果 @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. 共 {n} 個結果,顯示 {shown} 個。繼續輸入以縮小範圍。 Recent Commands 最近使用的指令 @@ -4648,6 +4802,7 @@ digits Malayalam 馬來亞拉姆數字 Set Slice Rectangle 設定切片矩形 Set Tab Stops 設定定位點 Set Text 設定文字 + Set the current fill or stroke to the selected color 將目前填色或筆畫設為選取的顏色 Set the selected color to the current color 將選取的顏色設為目前顏色 Set Zoom 設定縮放 Settings… 設定… @@ -4771,7 +4926,7 @@ digits Malayalam 馬來亞拉姆數字 Show Vivid/Muted 顯示鮮豔/柔和 Show Warm/Cool 顯示暖色/冷色 Show {kind} Brushes 顯示{kind}筆刷 - Show/hide plate (Alt-click: only this plate) 顯示/隱藏色版 (Alt-按一下:僅此色版) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) 顯示/隱藏色版 (Alt-按一下:僅此色版;再次 Alt-按一下:所有色版) Show: 顯示: Shown with the optimised preview. 於最佳化預覽時顯示。 Side 1: 側面 1: @@ -5081,7 +5236,7 @@ digits Malayalam 馬來亞拉姆數字 Composite Fonts 複合字體 Export Composite Fonts 匯出複合字體 Import Composite Fonts 匯入複合字體 -@msg each font must be {name, parts} 每個字體都必須是 {name, parts} +@msg each font must be {{name, parts}} 每個字體都必須是 {{name, parts}} @msg unknown key `{k}`; a font takes name and parts 未知的鍵 `{k}`;字體可用的鍵為 name 和 parts @msg each font needs a name 每個字體都需要名稱 @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` 不能作為複合字體的名稱(1 到 {COMPOSITE_NAME_MAX} 個字元,不含控制字元) @@ -5094,7 +5249,7 @@ digits Malayalam 馬來亞拉姆數字 @msg two composite fonts are named `{_1}` 有兩個複合字體都名為 `{_1}` @msg `{_1}` is the name of an installed font `{_1}` 是已安裝字體的名稱 @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`:{_2} 使用了複合字體 `{font}` -@msg give fonts: [{name, parts}…] 請指定 fonts:[{name, parts}…] +@msg give fonts: [{{name, parts}}…] 請指定 fonts:[{{name, parts}}…] @msg path is empty path 為空 @msg fonts must be a list of composite fonts fonts 必須是複合字體清單 @msg names must be strings names 必須是字串 @@ -5177,6 +5332,13 @@ digits Malayalam 馬來亞拉姆數字 Thumbnail View 縮圖檢視 Thumbnails: 縮圖: Tile 並排顯示 + Tile All Vertically 全部垂直並排顯示 + Tile All Horizontally 全部水平並排顯示 + 2-Up Layout 雙聯版面 + 3-Up Layout 三聯版面 + 4-Up Layout 四聯版面 + 6-Up Layout 六聯版面 + Arrange Documents 排列文件 Tile Edge Color 拼貼邊緣顏色 Tile Edge Color… 拼貼邊緣顏色… Tile Full Pages 並排完整頁面 @@ -5385,6 +5547,8 @@ digits Malayalam 馬來亞拉姆數字 V Spacing: 垂直間距: V: V: Variable Width Profile 可變寬度描述檔 + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. 筆畫的筆刷會保持自身大小,因此寬度描述檔不會改變它。移除筆刷即可使用描述檔。 +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. 筆畫的筆刷會保持自身大小,因此寬度描述檔不會改變它。移除筆刷即可使用描述檔。 Variables 變數 New Variable 新增變數 Delete Variable 刪除變數 @@ -5394,6 +5558,13 @@ digits Malayalam 馬來亞拉姆數字 @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} 資料集超過 {MAX_CSV_ROWS} 個:「匯入資料集」最多讀取 {MAX_CSV_ROWS} 個 @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} 變數超過 {MAX_CSV_COLS} 個:「匯入資料集」最多讀取 {MAX_CSV_COLS} 個 @msg variables that aren't text were left out: {kinds} 已略過非文字變數:{kinds} +variable-kind Visibility 可見性 +variable-kind Linked File 連結檔案 +variable-kind Graph Data 圖表資料 +variable-kind Unknown 未知 +variable-list-two {0}, {1} {0}和{1} +variable-list-middle {0}, {1} {0}、{1} +variable-list-end {0}, {1} {0}和{1} @msg a new document won't read these variables back with their kind: {names} 新文件不會以原類型讀回這些變數:{names} @msg a new document refuses this file because of these variables: {names} 新文件會因這些變數而拒絕此檔案:{names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them `{name}` 的標題 `{header}` 會被讀作變數 `{other}`:請重新命名其中一個 @@ -5457,7 +5628,7 @@ digits Malayalam 馬來亞拉姆數字 Vertical: 垂直: Very High 極高 View 檢視 - View Artboard Only 僅檢視工作區域 + View Artboard Contents Only 僅檢視工作區域內容 View Opacity Mask 檢視不透明度遮色片 View PDF after saving 儲存後檢視 PDF View {n} 檢視 {n} @@ -5511,7 +5682,7 @@ digits Malayalam 馬來亞拉姆數字 Zoom In 放大顯示 Zoom Out 縮小顯示 Zoom to Selection 縮放至選取範圍 - Zoom Tool 縮放工具 + Zoom Tool 縮放顯示工具 Zoom with Mouse Wheel 使用滑鼠滾輪縮放 Scroll Sideways with Cmd/Ctrl + Wheel 使用 Cmd/Ctrl + 滾輪水平捲動 Scrub Numeric Fields by Dragging 拖曳以調整數值欄位 @@ -5670,6 +5841,7 @@ imageTrace Outline 輪廓 Bevel 斜角 Offset 位移 Axis 軸 + Axis Angle 軸角度 axis Horizontal 水平 axis Vertical 垂直 axis Both 兩者 @@ -5722,7 +5894,7 @@ axis Both 兩者 Free Transform 任意變形 Perspective Distort 透視扭曲 -# Photoshop-style raster effects (Effect menu, their dialogs). +# Raster effects (Effect menu, their dialogs). Radial Blur… 放射狀模糊… Blur Center 模糊中心 Smart Blur… 智慧型模糊… @@ -5939,6 +6111,7 @@ lighting Light 光源 Horizontal Guide 水平參考線 Move Guide to Layer 將參考線移至圖層 Linux Display Server Linux 顯示伺服器 + Low-Latency Drawing 低延遲繪圖 X11 (XWayland) When a Pen Is Attached 連接觸控筆時使用 X11 (XWayland) If a drawing tablet's pen doesn't draw, choose an X11 (XWayland) option. 如果繪圖板的筆無法繪圖,請選擇一個 X11 (XWayland) 選項。 X11 (XWayland) X11 (XWayland) @@ -5990,6 +6163,7 @@ lighting Light 光源 Cove 凹圓 Depth 深度 Front 正面 + Side 側面 Isometric Bottom 等角底部 Isometric Left 等角左側 Isometric Right 等角右側 @@ -6084,7 +6258,7 @@ lighting Light 光源 @msg each of `{GRAPHICS}` must be an object `{GRAPHICS}` 的每個項目都必須是物件 @msg `{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}` `{GRAPHICS}` 的項目接受 symbol、face、x、y、scale 和 rotation,不接受 `{k}` @msg each of `{GRAPHICS}` needs `symbol`, the name of a symbol `{GRAPHICS}` 的每個項目都需要 `symbol`,也就是符號的名稱 -@msg `{GRAPHICS}` face must be front or back `{GRAPHICS}` 的 face 必須是 front 或 back +@msg `{GRAPHICS}` face must be front, back or side `{GRAPHICS}` 的 face 必須是 front、back 或 side @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} `{GRAPHICS}` 的 {key} 必須是介於 {lo} 到 {hi} 之間的數字 @msg `{GRAPHICS}` must be an array `{GRAPHICS}` 必須是陣列 @msg Graphics map onto the Plane, Extrude and Revolve object types 圖形會對應到「平面」、「突出」與「迴轉」物件類型 @@ -7031,6 +7205,12 @@ anchor Points: 點: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` 必須是 "free"、"keepAngles" 或 "symmetric" @msg `{key}` must be [x, y] `{key}` 必須是 [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter 單位換算器 + Unit Converter Panel 單位換算器面板 + Copy with Units 複製時包含單位 + From Selection 從選取範圍 + # Color Effects add-on: Select by Color Kind. Select by Color Kind 依顏色類型選取 Objects with Spot Colors 使用特別色的物件 @@ -7256,6 +7436,14 @@ breakText Glyphs 字符 Remove Gaps 移除間隙 @msg that makes too many pieces (at most 100000): make the dashes longer 這會產生過多片段(最多 100000 個):請加長短破折號 @msg select paths, or segments, to divide 請選取要分割的路徑或線段 +# Path Precision Tools add-on: Smooth Bridge. + Smooth Bridge… 平滑橋接… + Smooth Bridge 平滑橋接 + Keep Originals 保留原始物件 +@msg select two circles to bridge 請選取兩個要橋接的圓形 +@msg one circle is inside the other 一個圓形位於另一個圓形內 +@msg the circles are too far apart for this radius: raise the radius 就此半徑而言,兩個圓形相距太遠:請增加半徑 +@msg the circles are too far apart for this radius 就此半徑而言,兩個圓形相距太遠 # Path Precision Tools add-on: Common Tangents. Common Tangents… 公切線… Common Tangents 公切線 @@ -7791,7 +7979,7 @@ breakText Glyphs 字符 @msg `rows` must be lists of numbers or nulls, not {r} `rows` 必須是由數字或 null 組成的清單,而非 {r} @msg `scale` must be a number from 0.001 to 1000 `scale` 必須是 0.001 到 1000 之間的數字 @msg `scope.{key}` must be a non-empty array `scope.{key}` 必須是非空陣列 -@msg `scope` must be "document", {artboards} or {layers} `scope` 必須是 "document"、{artboards} 或 {layers} +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` 必須是 "document"、{{artboards: [index, …]}} 或 {{layers: [id, …]}} @msg `side` must be "left", "right", "top" or "bottom" `side` 必須是 "left"、"right"、"top" 或 "bottom" @msg `side` places the artboard: leave out x, y, width and height `side` 會決定工作區域的位置:請不要提供 x、y、width 和 height @msg `source` is the only path in series group `target` `source` 是系列群組 `target` 中唯一的路徑 @@ -7977,7 +8165,7 @@ breakText Glyphs 字符 @msg not a regular expression 不是正規表示式 @msg not an action set: the text doesn't start with /version and a number 不是動作組:文字的開頭不是 /version 和一個數字 @msg nothing to repeat 沒有可重複的內容 -@msg numbers out of order in {_1} quantifier {_1} 量詞中的數字順序錯誤 +@msg numbers out of order in {{}} quantifier {{}} 量詞中的數字順序錯誤 @msg object {_1} needs a 3D effect 物件 {_1} 需要 3D 效果 @msg object {_1}: a hollow Extrude & Bevel has no caps: turn on Cap to map a graphic 物件 {_1}:空心的「突出與斜角」沒有端面:請開啟「端點」才能對應圖形 @msg object {_1}: with a depth of 0 the object has one face: map its graphics onto the front 物件 {_1}:深度為 0 時物件只有一個面:請將圖形對應到正面 @@ -8050,7 +8238,7 @@ breakText Glyphs 字符 @msg the library's file is outside the read roots 資料庫的檔案位於讀取根目錄之外 @msg the line is too long, or the paths it passes too many, to check 線條過長,或經過的路徑過多,無法檢查 @msg the method needs an XML value 此方法需要 XML 值 -@msg the paint is not a freeform gradient (apply one with paint.editGradient {kind}) 此上色不是任意形狀漸層 (請以 paint.editGradient {kind} 套用) +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) 此上色不是任意形狀漸層 (請以 paint.editGradient {{kind: "freeform"}} 套用) @msg the parameters or body do not form one function 參數或主體無法構成一個函式 @msg the pasted SVG filter {name} draws differently from the document's filter of that name, and no free name fits it 貼上的 SVG 濾鏡 {name} 的繪製結果與文件中同名的濾鏡不同,而且找不到可用的名稱 @msg the paths are too many or too tangled to find where they cross 路徑過多或過於糾結,無法找出交叉處 @@ -8342,6 +8530,8 @@ breakText Glyphs 字符 @msg `{f}` is the copy of a document open now `{f}` 是目前開啟文件的副本 @msg `{id}` is no writable format (see document.formats) `{id}` 不是可寫入的格式 (請參閱 document.formats) @msg `{id}` isn't a loaded library `{id}` 不是已載入的資料庫 +@msg `{file}` has no swatches of its own `{file}` 沒有自己的色票 +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` 含有圖樣色票,.vcswatches 檔案無法儲存 @msg `{key}` has no colours `{key}` 沒有顏色 @msg `{key}` is a design name `{key}` 是設計名稱 @msg `{key}` is a design name or a list of them `{key}` 是設計名稱或設計名稱的清單 @@ -8564,7 +8754,13 @@ breakText Glyphs 字符 @msg colorModel must be {own} (the document's mode), grayscale or bitmap colorModel 必須是 {own} (文件的模式)、grayscale 或 bitmap @msg colour groups can't go into colour groups 顏色群組不能放入顏色群組 @msg colour, mode and spot apply to solid-colour swatches only colour、mode 和 spot 只適用於純色色票 -@msg column {column}: `{cell}` is a `%` column of graph data files, which are not read 第 {column} 欄:`{cell}` 是圖表資料檔案的 `%` 欄,不會讀取 +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path 第 {line} 行,第 {column} 欄:`{var}` 的圖表資料檔案 `{path}` 是相對路徑:請提供 `base` 或絕對路徑 +@msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} 第 {line} 行,第 {column} 欄:無法讀取 `{var}` 的圖表資料檔案:{e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` isn't followed: {r} 第 {line} 行,第 {column} 欄:未跟隨 `{var}` 的圖表資料檔案 `{path}` 的連結:{r} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes 第 {line} 行,第 {column} 欄:`{var}` 的圖表資料檔案 `{path}` 超過 {MAX_GRAPH_DATA_FILE} 位元組 +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes 第 {line} 行,第 {column} 欄:`{var}` 的圖表資料檔案 `{path}` 得到的圖表值超過 {MAX_GRAPH_CSV} 位元組 +@msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all 第 {line} 行,第 {column} 欄:圖表資料檔案合計超過 {MAX_GRAPH_FILES_TOTAL} 位元組 +@msg `base` is empty `base` 為空 @msg column {column}: `{cell}` names `{name}`, which is a {_1} variable 第 {column} 欄:`{cell}` 指定了 `{name}`,而它是 {_1} 變數 @msg column {column}: `{cell}` names no variable 第 {column} 欄:`{cell}` 未指定任何變數 @msg column {column}: the variable name is longer than {MAX_NAME} characters 第 {column} 欄:變數名稱超過 {MAX_NAME} 個字元 @@ -8575,6 +8771,7 @@ breakText Glyphs 字符 @msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes 複合形狀接受路徑、複合路徑、群組、複合形狀、文字、漸變物件和封套 @msg compound {_1} must contain exactly one open path to join 複合路徑 {_1} 必須剛好包含一條可連接的開放路徑 @msg connect needs a path other than the one extended connect 需要延伸路徑以外的另一條路徑 +@msg connect needs extend connect 需要 extend @msg connect needs id connect 需要 id @msg connect path has no open end connect 的路徑沒有開放的端點 @msg copy needs path: the file to copy into the document's folder copy 需要 path:要複製到文件資料夾的檔案 @@ -9567,4 +9764,14 @@ breakText Glyphs 字符 @msg A panel is not joined to the rest by a crease. 一個面板沒有透過任何壓痕線與其餘部分相連。 @msg A fold line is on a non-printing layer. 一條摺線位於不列印的圖層上。 @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} 面板:{panels},鉸鏈:{hinges},錯誤:{errors},警告:{warnings} + Fold Preview 摺疊預覽 + Fold 摺疊 + Show Fold Lines 顯示摺線 + Three-Quarter 四分之三視圖 + Open a document to preview its folded shape. 開啟文件以預覽其摺疊後的形狀。 +@msg Check the fold lines first. 請先檢查摺線。 +@msg Panels: {panels}, hinges: {hinges} 面板:{panels},鉸鏈:{hinges} +@msg Other blanks not shown: {count} 未顯示的其他展開圖:{count} +@msg A joint does not close by {gap} pt. 有一處接縫相差 {gap} pt 未閉合。 +@msg Two panels pass through each other. 兩個面板相互穿插。 @msg {what} would print on more than {MAX_TILES} tiles: scale it down {what} 會列印在超過 {MAX_TILES} 個拼貼上:請縮小 diff --git a/crates/ui-egui/src/icon_data.rs b/crates/ui-egui/src/icon_data.rs index f521e45c22..bc0cfe3510 100644 --- a/crates/ui-egui/src/icon_data.rs +++ b/crates/ui-egui/src/icon_data.rs @@ -58,6 +58,7 @@ pub static ICONS: &[(&str, &[u8])] = &[ ("dc-cap-square", include_bytes!("../../../assets/icons/dc-cap-square.svg")), ("dc-center-hide", include_bytes!("../../../assets/icons/dc-center-hide.svg")), ("dc-center-show", include_bytes!("../../../assets/icons/dc-center-show.svg")), + ("dc-circle-points", include_bytes!("../../../assets/icons/dc-circle-points.svg")), ("dc-clear", include_bytes!("../../../assets/icons/dc-clear.svg")), ("dc-color-guide", include_bytes!("../../../assets/icons/dc-color-guide.svg")), ("dc-contour", include_bytes!("../../../assets/icons/dc-contour.svg")), diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index e352653279..c4a67fdef6 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -44,6 +44,7 @@ pub fn tool_icon(name: &str) -> &'static str { "tool-rect" => "square", "tool-rounded-rect" => "dc-rounded-rect", "tool-ellipse" => "dc-ellipse", + "tool-circle" => "dc-circle-points", "tool-polygon" => "dc-polygon", "tool-star" => "star", "tool-flare" => "dc-flare", diff --git a/crates/ui-egui/src/io.rs b/crates/ui-egui/src/io.rs index a2b1cbebab..54f4c8b47d 100644 --- a/crates/ui-egui/src/io.rs +++ b/crates/ui-egui/src/io.rs @@ -36,7 +36,9 @@ pub use open::{ pub(crate) use open::{open_file, opened_with_notes}; pub(crate) use save::save_current; pub use save::{ask_format_options, ask_pdf_options, remember_active_artboard, remember_view, save, save_pdf}; -pub(crate) use save::{export_path, is_web, notes_of, report_saved, show_with_notes, target_path, write_named, write_reporting, write_to}; +pub(crate) use save::{ + clear_notes_left, export_path, is_web, notes_of, report_saved, show_with_notes, target_path, write_named, write_reporting, write_to, +}; #[cfg(test)] pub(crate) use save::{report_write_error, saved_status}; diff --git a/crates/ui-egui/src/io/export.rs b/crates/ui-egui/src/io/export.rs index 32733d855c..d7e37dd998 100644 --- a/crates/ui-egui/src/io/export.rs +++ b/crates/ui-egui/src/io/export.rs @@ -84,7 +84,7 @@ pub fn export(app: &mut VectorcraftApp, format: Option<&str>, path: Option std::sync::Arc::new(d), } }; - fileio::check_linked_images("file.exportAs", f.id, st, &doc, params).map_err(|e| e.to_string())?; + fileio::check_linked_images("file.exportAs", f.id, st, &doc, &checked).map_err(|e| e.to_string())?; // A PDF shows its title in the viewer's title bar only when it is the document's own, not the // file name it was titled after, as `document.export` writes it. let own_title = fileio::has_own_title(&doc); diff --git a/crates/ui-egui/src/io/save.rs b/crates/ui-egui/src/io/save.rs index e1f50fba45..3f5f7f80ca 100644 --- a/crates/ui-egui/src/io/save.rs +++ b/crates/ui-egui/src/io/save.rs @@ -501,6 +501,16 @@ pub(crate) fn show_with_notes(app: &mut VectorcraftApp, status: String, notes: V app.ui.status_notes = (!notes.is_empty()).then(|| (app.ui.status.clone(), notes)); } +/// Clear the status bar's message and its hover notes when `left` is still what the status bar +/// shows: a message with notes, and [`crate::state::UiState::status_sets`] when it was shown. +/// A message set since stays, one with the same text included. +pub(crate) fn clear_notes_left(app: &mut VectorcraftApp, left: Option<(String, u64)>) { + if left.is_some_and(|(status, sets)| status == app.ui.status && sets == app.ui.status_sets) { + app.status(""); + app.ui.status_notes = None; + } +} + /// [`report_saved`]'s message. pub(crate) fn saved_status(path: &str, r: &Value) -> String { let warnings = notes_of(r); diff --git a/crates/ui-egui/src/keymap.rs b/crates/ui-egui/src/keymap.rs index d32ae53d5d..79e53edfdd 100644 --- a/crates/ui-egui/src/keymap.rs +++ b/crates/ui-egui/src/keymap.rs @@ -216,7 +216,7 @@ fn catalogue(snapshot: &Snapshot, p: Platform) -> Vec { if TOGGLES.contains(&e.key.as_str()) { b = b.toggle(); } - if let Some(d) = shortcut_editor::default_of(&e.key).and_then(vc_binding) { + if let Some(d) = shortcut_editor::default_on(&e.key, p).and_then(vc_binding) { b = b.with_default(d); } for alias in default_aliases(&e.key, p) { @@ -639,6 +639,26 @@ mod tests { } } + /// Select Last Selection Tool is Ctrl+` on Windows and Linux. macOS takes Cmd+` to switch + /// between an app's windows, so there the command has no default and takes a chord the user + /// assigns. + #[test] + fn last_selection_tool_default_follows_the_platform() { + let snapshot = shortcut_editor::snapshot(); + let command = command_of("tool.selectLastSelection"); + let chord = vc_chord("Cmd+~").unwrap(); + for p in [Platform::Windows, Platform::Linux] { + let km = keymap_for(p, &snapshot); + assert_eq!(lookup(&km, &chord), Some(command.clone()), "{p:?}"); + assert_eq!(shortcut_editor::default_on("tool.selectLastSelection", p), Some("Cmd+~"), "{p:?}"); + } + let mut mac = keymap_for(Platform::Mac, &snapshot); + assert_eq!(mac.bindings(&command), vec![], "no default on macOS"); + assert_eq!(shortcut_editor::default_on("tool.selectLastSelection", Platform::Mac), None); + shortcut_editor::assign_in(&mut mac, "tool.selectLastSelection", Some("Alt+~"), true).unwrap(); + assert_eq!(lookup(&mac, &vc_chord("Alt+~").unwrap()), Some(command)); + } + #[test] fn panel_entries_bridge_to_window_panel() { let c = command_of("panel:layers"); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 0b8ee67183..c112f3ac8c 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1,4 +1,4 @@ -//! VectorCraft's egui frontend: an Illustrator-style UI over `vectorcraft-engine`. +//! VectorCraft's egui frontend: menus, tools, panels and dialogs over `vectorcraft-engine`. //! //! The UI is thin: every action goes through [`VectorcraftApp::run`], which dispatches UI commands //! (view/window) here and everything else to the engine. The same entry point serves menus, @@ -129,6 +129,7 @@ pub use services::{ }; use state::{GeometryStamp, InputGeneration, PendingScreenshot, QueuedScreenshot}; pub(crate) use state::{InputFrame, take_frame_once}; +pub use ui_fonts::on_missing_glyphs; pub struct VectorcraftApp { pub session: Session, @@ -345,6 +346,11 @@ pub struct VectorcraftApp { /// The plug-in install the approval dialog asks about, kept out of the dialog's fields, which /// `ui.dialog.set` writes. pub(crate) pending_plugin_install: Option, + /// The paths Choose… picked in a script's file dialog, kept out of the dialog's fields, which + /// `ui.dialog.set` writes. + pub(crate) script_picked: Vec, + /// Choose… left out files past the most a script is given. + pub(crate) script_picked_left_out: bool, /// The pen end the canvas saw last and the tool its eraser end stands in for /// ([`stylus::sync_eraser_tool`]). pub(crate) pen_end: stylus::PenEnd, diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 4e2d80bb45..6adb103f1f 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -1,4 +1,4 @@ -//! The menu bar (Illustrator's menu tree) and UI-level commands. +//! The menu bar (the full menu tree) and UI-level commands. //! //! Items bound to a command id run through [`VectorcraftApp::run`]. Items not implemented yet are //! listed (disabled, with their shortcut) so the full surface is visible and discoverable; the @@ -37,9 +37,6 @@ fn cp(label: &'static str, id: &'static str, p: Value) -> Item { fn todo(label: &'static str) -> Item { Item::Todo(label, "") } -fn todos(label: &'static str, sc: &'static str) -> Item { - Item::Todo(label, sc) -} fn sub(label: &'static str, items: Vec) -> Item { Item::Sub(label, items) } @@ -64,8 +61,11 @@ pub(crate) use bar::{home_key, home_showing}; #[cfg(test)] use bar::{menu_body, pointer_reaches_title}; pub use context::{context_items, context_menu_body, ruler_menu_body, ruler_unit_items}; +#[cfg(test)] +use entries::flatten; pub use entries::{ - InsertableItem, MenuEntry, Row, context_entries, entry, insertable, insertable_items, menu_entries, plays_in_app, pretty_shortcut, shown_shortcut, + InsertableItem, MenuEntry, Row, context_entries, entry, insertable, insertable_items, menu_entries, plays_in_app, pretty_shortcut, shown_label, + shown_shortcut, }; pub(crate) use invoke::graph_dialog; #[cfg(test)] @@ -80,6 +80,7 @@ pub(crate) use run::{normalize_panel, opt_bool, opt_index, opt_number}; use slots::RECENT_FONT_IDS; pub use state::{checked, enabled, plugin_revision, shortcut_of, shown_state}; pub(crate) use submenus::PATH_EFFECTS; +pub(crate) use tree::arrange_documents_items; pub use tree::{menu_tree, menu_tree_named}; pub use ui_commands::UI_COMMANDS; diff --git a/crates/ui-egui/src/menus/bar.rs b/crates/ui-egui/src/menus/bar.rs index 72cbc4535b..7694791af9 100644 --- a/crates/ui-egui/src/menus/bar.rs +++ b/crates/ui-egui/src/menus/bar.rs @@ -25,7 +25,7 @@ pub fn menu_bar(app: &mut VectorcraftApp, ui: &mut egui::Ui) -> f32 { let mut clicked: Option<(String, Value)> = None; let mut file_open = false; let tree = menu_tree_named(app.session.prefs.font_names_in_english); - // No application menu in the window (as in Illustrator): the bar starts at File on every + // No application menu in the window: the bar starts at File on every // platform. The VectorCraft menu stays in the tree: the native Mac bar takes it from there. let tree: Vec<(&str, Vec)> = tree.into_iter().filter(|(title, _)| *title != "VectorCraft").collect(); // A menu bar for its layout and menu-button style, but the titles use `Popup::menu` directly: diff --git a/crates/ui-egui/src/menus/entries.rs b/crates/ui-egui/src/menus/entries.rs index 953b5b58f4..8c92fbc071 100644 --- a/crates/ui-egui/src/menus/entries.rs +++ b/crates/ui-egui/src/menus/entries.rs @@ -53,11 +53,7 @@ pub fn entry<'a>(app: &VectorcraftApp, it: &'a Item) -> Option> { Entry::Item(Row { command: Some((id, p)), source: label, - label: effect_item_label(id, p) - .or_else(|| unlock_item_label(app, id, p, crate::i18n::current())) - .or_else(|| spelling_item_label(id, p)) - .unwrap_or_else(|| display_label(app, id, label)) - .into(), + label: shown_label(app, id, p, label).into(), shortcut: item_shortcut(id, p), enabled, checked, @@ -66,6 +62,16 @@ pub fn entry<'a>(app: &VectorcraftApp, it: &'a Item) -> Option> { }) } +/// The label of the menu item that runs `id` with `p` and reads `label` in English, as the menus +/// draw it in the UI language: an effect's own name (Pathfinder › Add), an object's name, a +/// spelling suggestion, or [`display_label`]. +pub fn shown_label(app: &VectorcraftApp, id: &str, p: &Value, label: &str) -> String { + effect_item_label(id, p) + .or_else(|| unlock_item_label(app, id, p, crate::i18n::current())) + .or_else(|| spelling_item_label(id, p)) + .unwrap_or_else(|| display_label(app, id, label)) +} + /// `Cmd+Shift+]` → `⇧⌘]` on macOS, `Ctrl+Shift+]` elsewhere. pub fn pretty_shortcut(s: &str) -> String { if s.is_empty() { @@ -109,13 +115,17 @@ pub struct MenuEntry { pub params: Value, pub enabled: bool, pub shortcut: String, + /// `path` as the menus draw it in the UI language: a plug-in's submenu and a Scripts folder + /// keep their names. + #[serde(skip)] + pub shown_path: Vec, } /// Flattened menu for `ui.menu.list`. pub fn menu_entries(app: &VectorcraftApp) -> Vec { let mut out = vec![]; for (title, items) in menu_tree_named(app.session.prefs.font_names_in_english) { - flatten(app, vec![title.to_string()], &items, &mut out); + flatten(app, vec![title.to_string()], vec![crate::i18n::t(title).to_string()], &items, &mut out); } out } @@ -123,7 +133,7 @@ pub fn menu_entries(app: &VectorcraftApp) -> Vec { /// Flattened canvas context menu for `ui.contextMenu.list` (paths are its submenus). pub fn context_entries(app: &VectorcraftApp) -> Vec { let mut out = vec![]; - flatten(app, vec![], &context_items(app), &mut out); + flatten(app, vec![], vec![], &context_items(app), &mut out); out } @@ -245,7 +255,7 @@ pub fn insertable_items(english_names: bool) -> Vec { out } -fn flatten(app: &VectorcraftApp, path: Vec, items: &[Item], out: &mut Vec) { +pub(super) fn flatten(app: &VectorcraftApp, path: Vec, shown: Vec, items: &[Item], out: &mut Vec) { for it in items { match it { Item::Cmd(l, id, p) => { @@ -266,6 +276,7 @@ fn flatten(app: &VectorcraftApp, path: Vec, items: &[Item], out: &mut Ve params: p.clone(), enabled, shortcut: item_shortcut(id, p).or_else(|| shortcut_of(id)).unwrap_or("").to_string(), + shown_path: shown.clone(), }) } Item::Todo(l, sc) => out.push(MenuEntry { @@ -275,11 +286,16 @@ fn flatten(app: &VectorcraftApp, path: Vec, items: &[Item], out: &mut Ve params: Value::Null, enabled: false, shortcut: sc.to_string(), + shown_path: shown.clone(), }), Item::Sub(l, ch) => { let mut p = path.clone(); p.push(l.to_string()); - flatten(app, p, ch, out); + // The menus draw a plug-in's submenu and a Scripts folder by their own names ([`entry`]). + let mut s = shown.clone(); + let own = super::labels::holds_plugin_commands(ch) || crate::scripts_menu::is_folder(ch); + s.push(if own { l.to_string() } else { crate::i18n::t(l).to_string() }); + flatten(app, p, s, ch, out); } _ => {} } diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 845ea7102a..29cb15df0b 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -17,10 +17,12 @@ pub fn click_target(label: &str, id: &str, p: &Value) -> (String, Value) { /// What an in-window menu click on `target` (a [`click_target`]) runs with `held` held: Object › /// Unlock All and Object › Show All chosen with Shift+Alt (Shift+Option) act only inside the groups /// that hold the selected objects (`scope: "group"`); Select Linked, Embedded, Missing and Modified -/// chosen with Shift add to the selection (`add: true`). +/// chosen with Shift add to the selection (`add: true`); Object › Expand… chosen with Alt (Option) +/// expands at once with the choices its dialog last expanded with (`immediate: true`). pub(crate) fn with_held_keys(target: (String, Value), held: egui::Modifiers) -> (String, Value) { match target.0.as_str() { "object.unlockAll" | "object.showAll" if held.shift && held.alt => (target.0, json!({"scope": "group"})), + "ui.expandDialog" if held.alt => (target.0, json!({"immediate": true})), // Select Linked, Embedded, Missing and Modified with Shift add to the selection. crate::addons::select::link_status::COMMAND if held.shift => (target.0, crate::addons::select::link_status::with_shift(target.1)), _ => target, @@ -53,7 +55,7 @@ pub(super) fn menu_dialog(app: &VectorcraftApp, id: &str) -> Option<(&'static st // Transform Each opens on the values it was last confirmed with (#1732). "object.transformEach" => (crate::dialogs::transform_each::KIND, crate::dialogs::transform_each::open_fields(app)), "object.reflect" => ("reflect", json!({"axis": "vertical", "angle": 90})), - "object.shear" => ("shear", json!({"angle": 0, "axis": "horizontal"})), + "object.shear" => ("shear", json!({"angle": 0, "axis": "horizontal", "axisAngle": 0})), "path.average" => ("average", json!({"axis": "both"})), // Average & Join opens on the joined anchor chosen last (Corner the first time). "path.averageJoin" if app.ui.average_join.is_object() => ("averageJoin", app.ui.average_join.clone()), @@ -77,6 +79,7 @@ pub(super) fn menu_dialog(app: &VectorcraftApp, id: &str) -> Option<(&'static st (crate::addons::pathtools::set_corners::KIND, crate::addons::pathtools::set_corners::fields(app)) } crate::addons::pathtools::dashes::COMMAND => (crate::addons::pathtools::dashes::KIND, crate::addons::pathtools::dashes::fields()), + crate::addons::pathtools::bridge::COMMAND => (crate::addons::pathtools::bridge::KIND, crate::addons::pathtools::bridge::fields()), crate::addons::pathtools::tangent_circle::COMMAND => { (crate::addons::pathtools::tangent_circle::KIND, crate::addons::pathtools::tangent_circle::fields(app)) } diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index b4e1c668ac..d5ec92b934 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -115,6 +115,7 @@ pub fn run_ui_command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option Option app.display_profile.request_read(app.session.prefs.monitor_profile_display).map(|()| { + if let Some(ctx) = &app.ui_ctx { + ctx.request_repaint(); + } + json!({ "requested": true }) + }), // Outline or Preview is a setting of the active document's view. "view.outline" => match app.view_mut() { Some(v) => flag(&mut v.outline), @@ -322,6 +330,7 @@ fn run_ui_part3(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::panels::character::toggle_face(app, Face::Bold), "type.italic" => crate::panels::character::toggle_face(app, Face::Italic), "type.highlightFontName" => crate::panels::character::highlight(app, crate::panels::character::Field::FontName), + "type.highlightFontSize" => crate::panels::character::highlight(app, crate::panels::character::Field::FontSize), "type.highlightKerning" => crate::panels::character::highlight(app, crate::panels::character::Field::Kerning), "type.highlightTracking" => crate::panels::character::highlight(app, crate::panels::character::Field::Tracking), "type.underline" => crate::panels::character::toggle_underline(app), @@ -672,7 +681,7 @@ fn run_ui_part6(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::doc_windows::new_window(app), "window.arrange.cascade" => crate::doc_windows::cascade(app), - "window.arrange.tile" => crate::canvas::tile(app), + "window.arrange.tile" => crate::canvas::tile(app, p), "window.arrange.floatInWindow" => crate::doc_windows::float_in_window(app, p), "window.arrange.floatAllInWindows" => crate::doc_windows::float_all(app), "window.arrange.consolidateAllWindows" if p.get("index").is_some_and(|i| !i.is_null()) => crate::doc_windows::dock(app, p), @@ -684,6 +693,11 @@ fn run_ui_part6(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option Err(format!("unknown tool `{t}`")), None => Err("missing `tool`".into()), }, + "tool.selectLastSelection" => { + let id = app.session.last_selection_tool(); + let switched = if app.session.tool_id() == id { Ok(()) } else { app.try_select_tool(id) }; + switched.map(|()| json!({"tool": app.session.tool_id()})) + } crate::touch::TOGGLE_MODE => crate::touch::toggle_mode(app), crate::addons::pathtools::corner::COMMAND => crate::addons::pathtools::corner::open(app), crate::addons::pathtools::shared_edge::COMMAND => crate::addons::pathtools::shared_edge::open(app), @@ -781,14 +795,22 @@ fn run_ui_part7(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option edit.unwrap_or(false), Err(e) => return Some(Err(e)), }; + let keep_art = match opt_bool(p, "keepArt") { + Ok(keep) => keep.unwrap_or(false), + Err(e) => return Some(Err(e)), + }; if edit || name.is_some() { + if keep_art { + return Some(Err("`keepArt` applies only to a new symbol".into())); + } crate::dialogs::symbol_options::open_edit(app, name.as_deref()) } else { - crate::dialogs::symbol_options::open(app) + crate::dialogs::symbol_options::open(app, keep_art) } } "ui.newBrush" => crate::dialogs::new_brush::open(app, p.get("ids").cloned()), "ui.brushOptions" => crate::dialogs::brush_options::open(app, s("name").as_deref()), + "ui.brushObjectOptions" => crate::dialogs::brush_options::open_object(app), "tool.options" => crate::toolbar::open_options(app, &s("tool").unwrap_or_default()), _ => return None, }; @@ -860,6 +882,7 @@ fn run_ui_part9(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::dialogs::trace_presets::open(app, p), "ui.flattenerPreview" => crate::panels::flattener_preview::command(app, p), + "ui.foldPreview" => crate::addons::packaging::preview::command(app, p), "ui.copyScriptConsole" => crate::panels::script_console::copy(app, p), "window.graphicStyleLibrary" => crate::panels::graphic_styles::open_library(app, p), "ui.libraryPanel" => crate::panels::library_panel::command(app, p), @@ -905,7 +928,11 @@ fn run_ui_part9(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option Option> { let s = |k: &str| p.get(k).and_then(Value::as_str).map(str::to_string); let r = match id { - "ui.expandDialog" => crate::dialogs::expand::open(app), + "ui.expandDialog" => match opt_bool(p, "immediate") { + Ok(Some(true)) => crate::dialogs::expand::expand_now(app), + Ok(_) => crate::dialogs::expand::open(app), + Err(e) => Err(e), + }, "ui.simplifyAuto" => crate::dialogs::simplify_slider::auto(app), "ui.simplifyMoreOptions" => crate::dialogs::simplify_slider::more_options(app), "ui.smoothAuto" => crate::dialogs::smooth_slider::auto(app), @@ -939,6 +966,7 @@ fn run_ui_part10(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::panels::color_guide::set_limit(app, p), "ui.colorPanel" => crate::panels::color::command(app, p), "ui.colorRgbPercent" => crate::panels::color::rgb_percent_command(app, p), + "ui.colorWheel" => crate::panels::color_wheel::command(app, p), "ui.savePdfDialog" => crate::dialogs::open_save_pdf(app, p), "file.exportAs" if s("path").is_none() => { crate::dialogs::open_export_as(app, s("format").as_deref(), p); @@ -1002,6 +1030,7 @@ fn run_ui_part11(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::panels::actions::save_set(app, p), crate::panels::actions::LOAD_SET => crate::panels::actions::load_set(app, p), + crate::panels::actions::REPLACE_SET => crate::panels::actions::replace_set(app, p), crate::panels::actions::DELETE_SETS => crate::panels::actions::delete_sets(app, p), crate::panels::actions::DUPLICATE => crate::panels::actions::duplicate(app, p), crate::panels::actions::RESET => crate::panels::actions::reset(app, p), diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index d4dda4698b..36dcdfc1d4 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -99,6 +99,8 @@ pub fn checked(app: &VectorcraftApp, id: &str, p: &Value) -> Option { } "window.collapseDock" => crate::panel_docking::dock_collapsed(&app.ui), "window.workspace" => p.get("name").and_then(Value::as_str) == Some(app.ui.workspace.as_str()), + // The Tile layout the panes show. + "window.arrange.tile" => app.ui.tiled && crate::canvas::TileLayout::from_params(p) == Ok(app.ui.tile_layout), "window.brightness" => p.get("brightness").and_then(Value::as_str).and_then(Brightness::parse) == Some(app.ui.brightness), "view.slices.lock" => app.session.slices_locked(), "object.slice.clipToArtboard" => app.session.active().is_some_and(|d| d.doc.slices_clip_to_artboard), @@ -219,7 +221,7 @@ pub fn enabled(app: &VectorcraftApp, id: &str) -> bool { match id { // Save is off for a clean document that already has its own file. "file.save" => app.session.active().is_some_and(|d| d.path.is_none() || d.converted || d.is_dirty()), - "type.bold" | "type.italic" | "type.underline" | "type.lineComposer" | "type.hyphenate" => { + "type.bold" | "type.italic" | "type.underline" | "type.lineComposer" | "type.hyphenate" | "type.highlightFontSize" => { crate::panels::character::text_style(app).is_some() } id if crate::panels::paragraph::ALIGN_COMMANDS.iter().any(|c| c.0 == id) => crate::panels::character::text_style(app).is_some(), @@ -286,6 +288,7 @@ pub fn enabled(app: &VectorcraftApp, id: &str) -> bool { "ui.sampleScreenColor" => crate::screen_color::available(app), "ui.newBrush" => app.session.active().is_some(), "ui.brushOptions" => crate::dialogs::brush_options::available(app), + "ui.brushObjectOptions" => crate::dialogs::brush_options::object_available(app), "ui.hyphenation" | "ui.justification" | "ui.tateChuYokoSettings" | "ui.warichuSettings" => { crate::panels::character::text_style(app).is_some() } @@ -321,6 +324,7 @@ pub fn enabled(app: &VectorcraftApp, id: &str) -> bool { "file.exportSelection" => app.session.active().is_some_and(|d| !d.selection.is_empty()), "css.copy" | "css.exportFile" => app.session.active().is_some(), "print.printerSetup" => app.services.print.as_ref().is_some_and(|s| s.has_setup()), + "view.refreshMonitorProfile" => app.session.prefs.monitor_profile_display && app.display_profile.has_reader(), "plugin.dialog" => app.session.active().is_some(), "ui.perspectiveGridDialog" | "ui.savePerspectivePreset" => app.session.active().is_some(), id if id.starts_with(crate::dialogs::perspective_presets::SLOT) => { diff --git a/crates/ui-egui/src/menus/submenus.rs b/crates/ui-egui/src/menus/submenus.rs index 469c40e7c7..1f8facea4c 100644 --- a/crates/ui-egui/src/menus/submenus.rs +++ b/crates/ui-egui/src/menus/submenus.rs @@ -111,7 +111,7 @@ pub(super) fn font_items(english_names: bool) -> Vec { /// The catalogue's menu path of the effects in 3D and Materials › 3D (Classic). const CLASSIC_3D: &[&str] = &["Effect", "3D and Materials", "3D (Classic)"]; -/// The raster effects' submenus of the Effect menu (the Photoshop-style effects, below the +/// The raster effects' submenus of the Effect menu (the pixel effects, below the /// vector effects): (submenu, the catalogue's menu path of its effects). /// The raster Stylize submenu shares its path with the vector one and lists only the effects at /// that path that [`vectorcraft_effects::PIXEL_EFFECTS`] names. @@ -157,13 +157,13 @@ pub(super) fn effect_menu() -> Vec { "Warp", ]; let top_level = |e: &vectorcraft_effects::EffectInfo| e.menu == ["Effect"] && order.contains(&e.label); - // An effect goes in the vector submenu its path names unless it is a Photoshop-style effect, + // An effect goes in the vector submenu its path names unless it is a pixel effect, // which goes in the raster submenu of the same name when `RASTER_MENUS` has one (Stylize › // Glowing Edges). let in_vector_menu = |e: &vectorcraft_effects::EffectInfo| order.iter().any(|s| e.menu == ["Effect", *s]) && !vectorcraft_effects::PIXEL_EFFECTS.contains(&e.id); let item = |e: &vectorcraft_effects::EffectInfo| match e.defaults.as_object().is_some_and(|o| o.is_empty()) { - // No options (Effect → Pathfinder, Crop Marks): apply directly, like Illustrator. + // No options (Effect → Pathfinder, Crop Marks): apply directly. true => Item::Cmd(e.label, "effect.apply", json!({ "effect": e.id })), false => Item::Cmd(e.label, "effect.dialog", json!({ "effect": e.id })), }; diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index 3e2673a651..4cc93d02ca 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -1,6 +1,290 @@ use super::*; use crate::theme; +#[test] +fn help_f1_opens_discover_without_a_document() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let (_, help) = menu_tree().into_iter().find(|(title, _)| *title == "Help").unwrap(); + assert!(help.iter().any(|item| matches!(item, Item::Cmd("VectorCraft Help…", "help.discover", _)))); + assert_eq!(shortcut_of("help.discover"), Some("F1")); + assert!(enabled(&app, "help.discover")); + let ctx = egui::Context::default(); + theme::install_fonts(&ctx); + let key = |key| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + ctx.run_ui(egui::RawInput { events: vec![key(egui::Key::F1)], ..Default::default() }, |ui| { + crate::shortcuts::handle(&mut app, ui.ctx()); + }) + .textures_delta + .clear(); + assert!(crate::panel_docking::showing(&app.ui, "discover")); + assert!(app.session.active().is_none()); + app.run("help.discover", json!({})).unwrap(); + assert!(crate::panel_docking::showing(&app.ui, "discover")); + + let tools = app.run("help.discover.search", json!({"query": "rectangle"})).unwrap(); + let tool = tools["results"].as_array().unwrap().iter().position(|hit| hit["kind"] == "tool" && hit["id"] == "rectangle").unwrap(); + let active_tool = app.session.tool_id(); + let picked = app.run("help.discover.choose", json!({"index": tool})).unwrap(); + assert_eq!(picked["result"]["id"], "rectangle"); + assert!(app.ui.learn_locate.is_some()); + assert_eq!(app.session.tool_id(), active_tool); + for _ in 0..2 { + ctx.run_ui(egui::RawInput::default(), |ui| crate::panels::discover::show(&mut app, ui)).textures_delta.clear(); + } + ctx.run_ui(egui::RawInput { events: vec![key(egui::Key::Escape)], ..Default::default() }, |ui| { + crate::shortcuts::handle(&mut app, ui.ctx()); + crate::panels::discover::show(&mut app, ui); + }) + .textures_delta + .clear(); + assert!(!crate::panel_docking::showing(&app.ui, "discover")); + app.run("help.discover", json!({})).unwrap(); + app.run("help.discover.back", json!({})).unwrap(); + assert_eq!(app.ui.discover.query, "rectangle"); + assert!(app.ui.discover.selected.is_none()); + crate::keymap::set_override(&mut app.ui.shortcut_overrides, "tool:rectangle", "Shift+9"); + crate::shortcut_editor::sync(&app.ui); + let tools = app.run("help.discover.search", json!({"query": "rectangle"})).unwrap(); + assert!(tools["results"].as_array().unwrap().iter().any(|hit| hit["kind"] == "tool" && hit["id"] == "rectangle" && hit["shortcut"] == "Shift+9")); + crate::shortcut_editor::sync(&crate::state::UiState::default()); + + let commands = app.run("help.discover.search", json!({"query": "file.newDialog"})).unwrap(); + let command = commands["results"].as_array().unwrap().iter().position(|hit| hit["id"] == "file.newDialog").unwrap(); + app.run("help.discover.choose", json!({"index": command})).unwrap(); + assert!(app.ui.dialog.is_none()); + assert!(app.session.active().is_none()); + + let tutorial = crate::panels::learn::catalog::SKILLS[0].tutorials.first().unwrap(); + let found = app.run("help.discover.search", json!({"query": tutorial.title})).unwrap(); + let index = found["results"].as_array().unwrap().iter().position(|hit| hit["kind"] == "tutorial" && hit["id"] == tutorial.id).unwrap(); + app.run("help.discover.choose", json!({"index": index})).unwrap(); + assert!(app.session.active().is_none()); + let text = crate::tests_labels::painted_text(&mut app, crate::panels::discover::show); + assert!(text.contains(tutorial.title), "{text}"); + app.ui.discover.focus = true; + ctx.run_ui(egui::RawInput::default(), |ui| crate::panels::discover::show(&mut app, ui)).textures_delta.clear(); + ctx.run_ui(egui::RawInput { events: vec![key(egui::Key::Escape)], ..Default::default() }, |ui| { + crate::shortcuts::handle(&mut app, ui.ctx()); + crate::panels::discover::show(&mut app, ui); + }) + .textures_delta + .clear(); + assert!(!crate::panel_docking::showing(&app.ui, "discover")); + + app.run("file.new", json!({})).unwrap(); + app.run("help.discover", json!({})).unwrap(); + app.select_tool(vectorcraft_tools::addons::polygonal_lasso::ID); + let view = app.view_info(); + for (x, y) in [(40.0, 40.0), (80.0, 40.0)] { + let down = vectorcraft_tools::PointerEvent::new(vectorcraft_tools::PointerKind::Down, x, y); + let up = vectorcraft_tools::PointerEvent::new(vectorcraft_tools::PointerKind::Up, x, y); + app.session.pointer(&down, view).unwrap(); + app.session.pointer(&up, view).unwrap(); + } + assert!(app.session.tool_ends_on_escape(view)); + let canvas_ctx = egui::Context::default(); + canvas_ctx + .run_ui(egui::RawInput { events: vec![key(egui::Key::Escape)], ..Default::default() }, |ui| { + crate::shortcuts::handle(&mut app, ui.ctx()); + }) + .textures_delta + .clear(); + assert!(!app.session.tool_ends_on_escape(view)); + assert!(crate::panel_docking::showing(&app.ui, "discover")); +} + +/// With the toolbars hidden by Tab, choosing a tool in Help, or a tool's link in a tutorial Help +/// shows, marks nothing and the status bar says why. +#[test] +fn discover_says_why_a_tool_cannot_be_marked() { + fn texts(ctx: &egui::Context, app: &mut VectorcraftApp, events: Vec) -> Vec<(String, egui::Rect)> { + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| crate::panels::discover::show(app, ui)); + out.textures_delta.clear(); + fn collect(s: &egui::Shape, out: &mut Vec<(String, egui::Rect)>) { + match s { + egui::Shape::Text(t) => out.push((t.galley.text().to_string(), t.visual_bounding_rect())), + egui::Shape::Vec(v) => v.iter().for_each(|s| collect(s, out)), + _ => {} + } + } + let mut texts = vec![]; + for c in &out.shapes { + collect(&c.shape, &mut texts); + } + texts + } + fn click(ctx: &egui::Context, app: &mut VectorcraftApp, label: &str) { + texts(ctx, app, vec![]); + let drawn = texts(ctx, app, vec![]); + let pos = drawn.iter().find(|(t, _)| t == label).unwrap_or_else(|| panic!("`{label}` not drawn: {drawn:?}")).1.center(); + let button = |pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + for e in [egui::Event::PointerMoved(pos), button(true), button(false)] { + texts(ctx, app, vec![e]); + } + } + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + app.run("window.dock", json!({})).unwrap(); + assert!(app.ui.tab_hid.is_some() && !app.ui.toolbar); + let reason = app.run("learn.locateTool", json!({"tool": "rectangle"})).unwrap()["reason"].as_str().unwrap().to_string(); + let ctx = egui::Context::default(); + theme::install_fonts(&ctx); + + let found = app.run("help.discover.search", json!({"query": "rectangle"})).unwrap(); + let hit = found["results"].as_array().unwrap().iter().find(|hit| hit["kind"] == "tool" && hit["id"] == "rectangle").unwrap().clone(); + app.status(""); + click(&ctx, &mut app, hit["label"].as_str().unwrap()); + assert_eq!(app.ui.discover.selected.map(|i| app.ui.discover.results[i].id.as_str()), Some("rectangle")); + assert!(app.ui.learn_locate.is_none()); + assert_eq!(app.ui.status, reason); + + let (tutorial, tool) = crate::panels::learn::catalog::SKILLS + .iter() + .flat_map(|skill| skill.tutorials.iter()) + .find_map(|t| t.steps.iter().find_map(|s| s.tool).map(|tool| (t, tool))) + .unwrap(); + let found = app.run("help.discover.search", json!({"query": tutorial.title})).unwrap(); + let index = found["results"].as_array().unwrap().iter().position(|hit| hit["kind"] == "tutorial" && hit["id"] == tutorial.id).unwrap(); + app.run("help.discover.choose", json!({"index": index})).unwrap(); + app.status(""); + click(&ctx, &mut app, vectorcraft_tools::tool_info(tool).unwrap().label); + assert!(app.ui.learn_locate.is_none()); + assert_eq!(app.ui.status, reason); +} + +#[test] +fn discover_rejects_invalid_search_and_selection_parameters() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + app.run("help.discover.search", json!({"query": "rectangle"})).unwrap(); + let before = app.ui.discover.query.clone(); + for params in + [json!({}), json!({"query": null}), json!({"query": false}), json!({"query": "rectangle", "unknown": 1}), json!({"query": "a".repeat(1025)})] + { + assert!(app.run("help.discover.search", params).is_err()); + assert_eq!(app.ui.discover.query, before); + } + for index in [json!(-1), json!(1.5), json!(1000000), json!("0"), Value::Null] { + assert!(app.run("help.discover.choose", json!({"index": index})).is_err()); + } + for params in [json!(5), json!("rectangle"), json!([1]), json!(true)] { + for id in ["help.discover", "help.discover.search", "help.discover.choose", "help.discover.back"] { + assert!(app.run(id, params.clone()).is_err(), "{id} {params}"); + } + assert_eq!(app.ui.discover.query, before); + } + app.run("help.discover.search", json!({"query": " "})).unwrap(); + assert!(app.ui.discover.results.is_empty()); + assert!(app.run("help.discover.choose", json!({"index": 0})).is_err()); +} + +/// A kept command result follows its menu item: Show Grid reads Hide Grid once the grid shows. +#[test] +fn discover_command_results_follow_their_menu_label() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let found = app.run("help.discover.search", json!({"query": "view.grid"})).unwrap(); + let index = found["results"].as_array().unwrap().iter().position(|hit| hit["id"] == "view.grid" && hit["path"][0] == "View").unwrap(); + assert_eq!(found["results"][index]["label"], "Show Grid"); + app.run("help.discover.choose", json!({"index": index})).unwrap(); + app.run("view.grid", json!({})).unwrap(); + let back = app.run("help.discover", json!({})).unwrap(); + assert_eq!(back["selected"], index); + assert_eq!(back["results"][index]["label"], "Hide Grid"); +} + +/// A menu entry's shown path translates the menus' own names and keeps a Scripts folder's name, as +/// the menus draw it; Help shows that path. +#[test] +fn menu_entry_shown_paths_keep_script_folder_names() { + let app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let de = crate::i18n::Lang::from_code("de").unwrap(); + assert_ne!(crate::i18n::tr(de, "File"), "File"); + let script = json!({"path": "File/a.jsx"}); + let folder = vec![Item::Cmd("a", crate::scripts_menu::COMMAND, script)]; + let items = vec![Item::Sub("Scripts", vec![Item::Sub("File", folder), Item::Cmd("Other Script…", "ui.runScript", Value::Null)])]; + let mut out = vec![]; + crate::i18n::set_current(de); + flatten(&app, vec!["File".into()], vec![crate::i18n::t("File").into()], &items, &mut out); + crate::i18n::set_current(crate::i18n::Lang::EN); + let script = out.iter().find(|e| e.command.as_deref() == Some(crate::scripts_menu::COMMAND)).unwrap(); + assert_eq!(script.path, ["File", "Scripts", "File"]); + assert_eq!(script.shown_path, [crate::i18n::tr(de, "File"), crate::i18n::tr(de, "Scripts"), "File"]); +} + +/// Outside macOS the window's menu bar has no VectorCraft menu, so Help lists no command under it. +#[test] +fn discover_leaves_out_menus_the_window_does_not_show() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let app_menu: Vec = + menu_entries(&app).into_iter().filter(|e| e.path.first().is_some_and(|t| t == "VectorCraft")).filter_map(|e| e.command).collect(); + assert!(!app_menu.is_empty()); + for id in app_menu { + let found = app.run("help.discover.search", json!({"query": id})).unwrap(); + let listed = found["results"].as_array().unwrap().iter().any(|hit| hit["path"][0] == "VectorCraft"); + assert_eq!(listed, cfg!(target_os = "macos"), "{id}: {found}"); + } +} + +/// Help finds a command by the label its menu shows in the UI language, also where the menu names +/// an effect by its own id (Effect › Pathfinder › Add reads Réunion in French). +#[test] +fn discover_finds_commands_by_their_shown_menu_label() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let fr = crate::i18n::Lang::from_code("fr").unwrap(); + let shown = crate::i18n::tr_id(fr, "pathfinder.add", "Add"); + assert_ne!(shown, crate::i18n::tr(fr, "Add")); + crate::i18n::set_current(fr); + let found = app.run("help.discover.search", json!({"query": shown})); + let effect = crate::i18n::tr(fr, "Effect").to_string(); + crate::i18n::set_current(crate::i18n::Lang::EN); + let found = found.unwrap(); + let hits = found["results"].as_array().unwrap(); + assert!( + hits.iter().any(|hit| hit["kind"] == "command" + && hit["id"].as_str().is_some_and(|id| id.starts_with("effect.")) + && hit["label"] == shown + && hit["path"][0] == effect), + "{found}" + ); +} + +#[test] +fn discover_results_show_the_current_shortcut_and_language_after_a_change() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let found = app.run("help.discover.search", json!({"query": "file.newDialog"})).unwrap(); + let index = found["results"].as_array().unwrap().iter().position(|hit| hit["id"] == "file.newDialog").unwrap(); + assert_eq!(found["results"][index]["shortcut"], "Cmd+N"); + app.run("help.discover.choose", json!({"index": index})).unwrap(); + app.run("window.panel.close", json!({"panel": "discover"})).unwrap(); + app.run("shortcuts.set", json!({"id": "file.newDialog", "shortcut": "Cmd+Alt+Shift+F9"})).unwrap(); + + let reopened = app.run("help.discover", json!({})).unwrap(); + assert_eq!(reopened["query"], "file.newDialog"); + assert_eq!(reopened["selected"], index); + assert_eq!(reopened["results"][index]["id"], "file.newDialog"); + assert_eq!(reopened["results"][index]["shortcut"], "Cmd+Alt+Shift+F9"); + let picked = app.run("help.discover.choose", json!({"index": index})).unwrap(); + assert_eq!(picked["result"]["shortcut"], "Cmd+Alt+Shift+F9"); + assert_eq!(picked["location"]["shortcut"], "Cmd+Alt+Shift+F9"); + + app.run("shortcuts.set", json!({"id": "file.newDialog", "shortcut": "Cmd+Alt+Shift+F8"})).unwrap(); + let text = crate::tests_labels::painted_text(&mut app, crate::panels::discover::show); + assert!(text.contains(&pretty_shortcut("Cmd+Alt+Shift+F8")), "{text}"); + assert!(!text.contains(&pretty_shortcut("Cmd+Alt+Shift+F9")), "{text}"); + + let de = crate::i18n::Lang::from_code("de").unwrap(); + assert_ne!(crate::i18n::tr(de, "New…"), "New…"); + crate::i18n::set_current(de); + let back = app.run("help.discover.back", json!({})).unwrap(); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert_eq!(back["query"], "file.newDialog"); + assert_eq!(back["results"][index]["label"], crate::i18n::tr(de, "New…")); + assert_eq!(back["results"][index]["path"][0], crate::i18n::tr(de, "File")); + crate::shortcut_editor::sync(&crate::state::UiState::default()); +} + #[test] fn help_bar_toggle_is_independent_and_saved_in_workspaces() { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); @@ -442,6 +726,39 @@ fn center_on_top_and_bottom_are_type_on_a_path_items() { assert!((start - 0.625).abs() < 1e-6, "{start}"); } +/// Type › Size ends with a separator and Other…, which runs `type.highlightFontSize`: dimmed +/// without selected type, enabled with it, and never checked. +#[test] +fn type_size_ends_with_other() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let id = "type.highlightFontSize"; + assert!(!enabled(&app, id), "no document"); + app.run("file.new", json!({})).unwrap(); + let items: Vec = menu_tree() + .into_iter() + .filter(|(menu, _)| *menu == "Type") + .flat_map(|(_, items)| items) + .filter_map(|item| match item { + Item::Sub("Size", children) => Some(children), + _ => None, + }) + .flatten() + .collect(); + let n = items.len(); + assert!(n > 2, "{n} items"); + assert!(matches!(items[n - 2], Item::Sep), "a separator comes before Other…"); + assert!(matches!(&items[n - 1], Item::Cmd("Other…", c, p) if *c == id && p.is_null()), "Other… comes last"); + assert!(items[..n - 2].iter().all(|i| matches!(i, Item::Cmd(_, "text.setStyle", _))), "the sizes come first"); + assert!(!enabled(&app, id), "nothing selected"); + let path = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [path]})).unwrap(); + assert!(!enabled(&app, id), "a path selected"); + let text = app.run("text.create", json!({"x": 10, "y": 100, "text": "Size"})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [text]})).unwrap(); + assert!(enabled(&app, id), "type selected"); + assert_eq!(checked(&app, id, &Value::Null), None); +} + /// Type › Dynamic Text Presets › Circle, Arch and Bow run `type.dynamicTextPreset` with their /// preset, enabled for point type and type on a path but not for area type alone. #[test] @@ -572,6 +889,30 @@ fn color_settings_and_assign_profile_show_the_separations_panel() { } } +/// Edit › Refresh Monitor Profile, after Assign Profile…, asks the desktop app's next frame to read +/// the display's profile; it is off and refused with the preference off or nothing to read it. +#[test] +fn refresh_monitor_profile_asks_for_a_reading_of_the_display_profile() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let entries = menu_entries(&app); + let at = |label: &str| entries.iter().position(|e| e.label == label && e.path == ["Edit"]); + assert_eq!(at("Refresh Monitor Profile"), at("Assign Profile…").map(|i| i + 1)); + let e = &entries[at("Refresh Monitor Profile").unwrap()]; + assert_eq!((e.command.as_deref(), e.shortcut.as_str()), (Some("view.refreshMonitorProfile"), "")); + // Nothing reads the display's profile (the web build, tests). + assert!(!enabled(&app, "view.refreshMonitorProfile")); + assert_eq!(app.run("view.refreshMonitorProfile", json!({})).unwrap_err(), "this build doesn't read display profiles"); + app.display_profile.attach_reader(); + assert!(enabled(&app, "view.refreshMonitorProfile")); + assert_eq!(app.run("view.refreshMonitorProfile", json!({})).unwrap(), json!({"requested": true})); + assert!(app.display_profile.take_request()); + // With the preference off nothing is asked for. + app.session.prefs.monitor_profile_display = false; + assert!(!enabled(&app, "view.refreshMonitorProfile")); + assert_eq!(app.run("view.refreshMonitorProfile", json!({})).unwrap_err(), "turn on Use Monitor Profile for Canvas first"); + assert!(!app.display_profile.read_requested()); +} + #[test] fn saved_views_store_and_restore_the_view() { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index 617d0d403e..137c3b5758 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -1,6 +1,6 @@ use super::slots::{PERSPECTIVE_SLOTS, RECENT_FONT_IDS, RECENT_IDS, SAVED_SELECTION_IDS, SAVED_VIEW_IDS}; use super::submenus::{INSERT_BREAK, INSERT_SPECIAL, INSERT_WHITESPACE, PATH_EFFECTS, TYPE_SIZES, effect_menu, font_items, insert_items}; -use super::{Item, Sep, c, cp, json, sub, todos}; +use super::{Item, Sep, c, cp, json, sub}; /// The in-window and native menu tree. The in-window bar skips the VectorCraft menu (see /// `menu_bar`); the native Mac bar is composed from the whole tree (see `native_menu`). @@ -15,7 +15,7 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { vec![ ( // The application menu: About and Discord only. The in-window bar never shows it (File - // is first there, as in Illustrator); on macOS `native_menu::mac_layout` composes the + // is first there); on macOS `native_menu::mac_layout` composes the // App menu from this entry and the other menus (About from Help, Settings from Edit, // Quit from File, Language and Appearance synthesized). It stays first: `from_tree` // gives the first menu the App role. @@ -141,6 +141,7 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { Sep, c("Color Settings…", "edit.colorSettings"), c("Assign Profile…", "edit.assignProfile"), + c("Refresh Monitor Profile", "view.refreshMonitorProfile"), Sep, c("Keyboard Shortcuts…", "edit.keyboardShortcuts"), c("Preferences…", "edit.preferences"), @@ -397,7 +398,14 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { vec![ sub("Font", font_items(english_names)), sub("Recent Fonts", RECENT_FONT_IDS.iter().map(|id| c("Recent Font", id)).collect()), - sub("Size", TYPE_SIZES.iter().map(|(l, n)| cp(l, "text.setStyle", json!({ "size": n }))).collect()), + sub( + "Size", + TYPE_SIZES + .iter() + .map(|(l, n)| cp(l, "text.setStyle", json!({ "size": n }))) + .chain([Sep, c("Other…", "type.highlightFontSize")]) + .collect(), + ), c("Bold", "type.bold"), c("Italic", "type.italic"), Sep, @@ -648,16 +656,16 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { ("Window", { let mut window_items = vec![ c("New Window", "window.newWindow"), - sub( - "Arrange", - vec![ - c("Cascade", "window.arrange.cascade"), - c("Tile", "window.arrange.tile"), + sub("Arrange", { + let mut arrange = vec![c("Cascade", "window.arrange.cascade")]; + arrange.extend(tile_items()); + arrange.extend([ c("Float in Window", "window.arrange.floatInWindow"), c("Float All in Windows", "window.arrange.floatAllInWindows"), c("Consolidate All Windows", "window.arrange.consolidateAllWindows"), - ], - ), + ]); + arrange + }), sub("Workspace", crate::workspaces::menu_items()), Sep, c("Control", "window.control"), @@ -745,7 +753,7 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { c("VectorCraft on getartcraft.com", "help.appPage"), c("VectorCraft on GitHub", "help.github"), Sep, - todos("VectorCraft Help…", "F1"), + c("VectorCraft Help…", "help.discover"), c("Safe Mode…", "help.safeMode"), c("Copy Troubleshooting Info", "help.copyTroubleshootingInfo"), Sep, @@ -770,9 +778,31 @@ pub(super) fn transform_items() -> Vec { c("Transform Each…", "object.transformEach"), Sep, c("Reset Bounding Box", "object.resetBoundingBox"), + cp("Rotate Bounding Box…", "object.rotateBoundingBox", json!({"angle": 0})), ] } +/// Window → Arrange's Tile layouts, one `window.arrange.tile` `layout` each (also under the +/// application bar's Arrange Documents button). +fn tile_items() -> Vec { + vec![ + c("Tile", "window.arrange.tile"), + cp("Tile All Vertically", "window.arrange.tile", json!({"layout": "vertical"})), + cp("Tile All Horizontally", "window.arrange.tile", json!({"layout": "horizontal"})), + cp("2-Up Layout", "window.arrange.tile", json!({"layout": "2up"})), + cp("3-Up Layout", "window.arrange.tile", json!({"layout": "3up"})), + cp("4-Up Layout", "window.arrange.tile", json!({"layout": "4up"})), + cp("6-Up Layout", "window.arrange.tile", json!({"layout": "6up"})), + ] +} + +/// The application bar's Arrange Documents menu: Consolidate All Windows, then the Tile layouts. +pub(crate) fn arrange_documents_items() -> Vec { + let mut items = vec![c("Consolidate All Windows", "window.arrange.consolidateAllWindows"), Sep]; + items.extend(tile_items()); + items +} + /// Object → Arrange (also in the canvas context menu). pub(super) fn arrange_items() -> Vec { vec![ diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 677b804720..87091ef8a9 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -144,7 +144,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} opens SVG Options; with params = document.export {path?, svg?: {…SVG options}, range?…} (a .svgz path writes it gzipped)", ), - ("file.export.png", "Export As PNG…", "", "{path?, …document.export options}; no path: pick the file, then PNG Options"), + ( + "file.export.png", + "Export As PNG…", + "", + "{path?, …document.export options}; no path: pick the file, then PNG Options with supplied options retained and defaults for omitted options", + ), ( "file.exportForScreens", "Export for Screens…", @@ -162,6 +167,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ ("app.home", "Home", "", "{} shows the Home screen (new file presets, Open) over the open documents; choosing a document tab returns to it"), ("edit.preferences", "Preferences…", "Cmd+K", "{category?} open Preferences (engine: prefs.get / prefs.set / prefs.list)"), ("edit.keyboardShortcuts", "Keyboard Shortcuts…", "Cmd+Alt+Shift+K", "{}"), + ( + "view.refreshMonitorProfile", + "Refresh Monitor Profile", + "", + "{} read the display's profile for Use Monitor Profile for Canvas (monitorProfileDisplay) again on the next frame, without waiting for the 10-second reading or the 1-second display check; while a reading runs, the request waits for it to end → {requested: true}, before the profile is read (ui.inspect › displayProfile reports the reading, and readRequested while it waits); an error while the preference is off, and where nothing reads the display's profile (the web build)", + ), ( "edit.autoSpellCheck", "Auto Spell Check", @@ -234,7 +245,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} toggle drawing the gaps of the selected Live Paint groups (those livePaint.info lists) in each group's Gap Preview Color while edges show → true when on", ), - ("type.hiddenCharacters", "Show Hidden Characters", "Cmd+Alt+I", "{} toggle markers for spaces, paragraph ends and story ends"), + ( + "type.hiddenCharacters", + "Show Hidden Characters", + "Cmd+Alt+I", + "{} toggle markers for spaces, tabs, nonbreaking and fixed-width spaces, discretionary hyphens, forced line breaks, paragraph ends and story ends", + ), ("type.alignLeft", "Align left", "Cmd+Shift+L", "{} align the selected type's paragraphs (or those the Type tool's selection touches) left"), ( "type.alignCenter", @@ -261,7 +277,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.bulletsAndNumbering", "Bullets and Numbering…", "", - "{tab?: \"bullets\"|\"numbers\"} open Bullets and Numbering (More Options in the Paragraph panel's Bullets and Numbered List presets) on the paragraphs the Paragraph panel acts on, filled in with the values it shows, on that tab (without it, Numbers when the paragraphs are a numbered list, else Bullets) (dialog `bulletsAndNumbering`: tab (bullets|numbers), list (none|bullet|number: the kind of the preset picked), bullet (dot|dash|circle|square), number (arabic|upperLetters|lowerLetters|upperRoman|lowerRoman|twoDigits|threeDigits), listAlign (left|right), listLevel (1..9; 1 for paragraphs in no list), leftIndent, firstLineIndent (pt)): the type shows the dialog's values while it is open, OK runs text.setFormat with the values that changed (and the indents it shows when a preset puts the paragraphs in a list), as one undo step, and Cancel puts the type back; a preset picked for paragraphs in no list whose indents are 0 fills in 18 and -18 pt; an error with no type selected or an unknown tab", + "{tab?: \"bullets\"|\"numbers\"} open Bullets and Numbering (More Options in the Paragraph panel's Bullets and Numbered List presets) on the paragraphs the Paragraph panel acts on, filled in with the values it shows, on that tab (without it, Numbers when the paragraphs are a numbered list, else Bullets) (dialog `bulletsAndNumbering`: tab (bullets|numbers), list (none|bullet|number: the kind of the preset picked), bullet (dot|dash|circle|square), number (arabic|upperLetters|lowerLetters|upperRoman|lowerRoman|twoDigits|threeDigits), listAlign (left|right), listLevel (1..9; 1 for paragraphs in no list), leftIndent, firstLineIndent (pt), startAt (bool: the Numbers tab's Start at box, on when the paragraphs have the same number of their own, blank when those differ; on sends startNumber, off sends restartNumbering false), startNumber (1..999999999: its number, 1 until one is typed)): the type shows the dialog's values while it is open, OK runs text.setFormat with the values that changed (and the indents it shows when a preset puts the paragraphs in a list), as one undo step, and Cancel puts the type back; a preset picked for paragraphs in no list whose indents are 0 fills in 18 and -18 pt; an error with no type selected or an unknown tab", ), ( "type.convertListToText", @@ -377,6 +393,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "Cmd+Alt+Shift+F", "{} show the Character panel if it is hidden and open its font family menu, whose search field takes the keyboard focus: type to search, Enter applies the highlighted font → {field: \"fontName\"}. Without selected type (or text the Type tool edits) the panel shows, and the error says to select type first", ), + ( + "type.highlightFontSize", + "Highlight Font Size", + "", + "{} (Type › Size › Other…) show the Character panel if it is hidden and give its Font Size field the keyboard focus with its value selected (blank where the selected sizes differ): type a size and press Enter → {field: \"fontSize\"}. Without selected type (or text the Type tool edits) the panel shows, and the error says to select type first", + ), ( "type.highlightKerning", "Highlight Kerning", @@ -507,7 +529,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "window.toolsBesideCanvas", "Keep Tools Beside the Canvas", "", - "{on?: bool} dock the Tools panel between the left-side panels and the canvas (true) or at the window's left edge (false, the default), or toggle (omitted or null; any other value is an error); a floating Tools panel stays floating and docks at the chosen place when it is docked again. Kept with the workspace; a workspace saved without it docks Tools at the window's edge. Returns the new state", + "{on?: bool} dock the Tools panel between the left-side panels and the canvas (true) or at the window's left edge (false, the default), or toggle (omitted or null; any other value is an error); a floating Tools panel stays floating and docks at the chosen place when it is docked again. Dropping a floating Tools panel on the canvas's left edge, right of panels docked on the left, turns it on, and on the window's left edge turns it off; with no panels docked on the left, or in the column both edges share beside panels collapsed to icons, a drop leaves it as it is. Kept with the workspace; a workspace saved without it docks Tools at the window's edge. Returns the new state", ), ( "window.floatTools", @@ -793,7 +815,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "window.arrange.tile", "Tile", "", - "{} show every open document and each further view of one (window.newWindow) at once, edge to edge in the document area, one pane each in a grid (columns: the square root of the number of panes, rounded up), each fitted to its pane; the current window's pane takes the tools, a click in another pane makes its window the current one; the tabs stay; windows floating come back under the tabs first; with fewer than two windows open the view stays as it is; returns {tiled, panes}", + "{layout?: grid|vertical|horizontal|2up|3up|4up|6up} show the open documents and each further view of one (window.newWindow) at once, edge to edge in the document area, one pane each, each fitted to its pane: `grid` (the default) in a grid (columns: the square root of the number of panes, rounded up), `vertical` side by side in one row (Tile All Vertically), `horizontal` stacked in one column (Tile All Horizontally), `2up`, `3up`, `4up` and `6up` at most that many panes (2up and 3up side by side, 4up two by two, 6up three by two) with the other windows under their tabs: the first windows in tab order, the current window in the last pane when it is not among them; the current window's pane takes the tools, a click in another pane makes its window the current one; the tabs stay; windows floating come back under the tabs first; with fewer than two windows open the view and the layout stay as they are; any other `layout` is an error; returns {tiled, panes, layout}", ), ( "window.arrange.floatInWindow", @@ -826,11 +848,17 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "{} make the open document before the current one in tab order the current one, as a click on its tab does (before the first document it goes to the last, and from the Home screen to the last); each view window.newWindow opened is a step of its own; returns {index}, with `view` for a document with more than one view", ), ("tool.select", "Select Tool", "", "{tool: id} (see tools) → {tool}; a tool that cannot be chosen returns the error"), + ( + "tool.selectLastSelection", + "Select Last Selection Tool", + "Cmd+~", + "{} choose the selection tool chosen last (Selection, Direct Selection or Group Selection; none yet: the Selection tool), keeping the active tool when it is that tool; choosing Magic Wand, Lasso or any other tool does not change which one it chooses → {tool}. Default shortcut Ctrl+` on Windows and Linux, none on macOS, where Cmd+` switches windows", + ), ( "tool.setOption", "Tool Option", "", - "{key, value} | {values: {key: value…}}, tool?: id (default: the active tool) → the tool's options (`{}` reads them). The options a tool keeps (Liquify brush and tool options, Mirror & Cut, Puppet Warp, drawing tools…) last across tool switches and are saved with the preferences; another tool's are stored for when it is chosen", + "{key, value} | {values: {key: value…}}, tool?: id (default: the active tool) → the tool's options (`{}` or no params reads them; params that are not an object are an error). The options a tool keeps (Liquify brush and tool options, Mirror & Cut, Puppet Warp, drawing tools…) last across tool switches and are saved with the preferences; another tool's are stored for when it is chosen. Every option is checked before any is set: an option the tool doesn't have, a value of the wrong type, a number out of the tool's range or an unknown choice is an error naming the tool and the option, and nothing changes. The Live Paint tools' width and the Shape Builder's gapLength are set to the nearest end of their range instead", ), ( crate::touch::TOGGLE_MODE, @@ -873,6 +901,25 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ ("help.about", "About VectorCraft", "", "{}"), ("help.checkForUpdates", "Check for Updates…", "", "{}"), ("help.commandPalette", "Search Commands…", "Cmd+Shift+/", "{}"), + ( + "help.discover", + "VectorCraft Help…", + "F1", + "{query?: string (at most 1024 characters, VectorCraft's limit)} show the Help panel without toggling it closed; a supplied query searches tools, menu commands, and built-in tutorials; omission keeps the current search. Returns {query, results: [{kind: tool|command|tutorial, id, label, path, shortcut}], selected: index|null}", + ), + ( + "help.discover.search", + "Search", + "", + "{query: string (at most 1024 characters, VectorCraft's limit)} search tools, menu commands, and built-in tutorials and show the Help panel; empty or whitespace-only text clears the results. Returns the help.discover result", + ), + ( + "help.discover.choose", + "Select", + "", + "{index: zero-based result index} show a tool's location, a tutorial's steps in Help, or a command's menu path and shortcut without running it; an invalid index is an error. Returns {result: chosen result, location: tool location, tutorial id, or command path}", + ), + ("help.discover.back", "Back", "", "{} return from a Help result to its search results without changing the query"), ( "help.safeMode", "Safe Mode…", @@ -926,7 +973,13 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.brushOptions", "Brush Options…", "", - "{name?} (default: the selected path's brush, else the current brush) open its Brush Options, what double-clicking a brush in the Brushes panel opens (dialog `brushOptions`): Calligraphic (fields name, angle −180..180, roundness 0..100, size 0..1296 pt, angleMode/roundnessMode/sizeMode: fixed|random|pressure, angleVariation/roundnessVariation/sizeVariation), Bristle (fields name, shape, size, length, density, thickness, opacity, stiffness), Scatter (fields sizeMin/sizeMax/sizeMode, spacingMin/spacingMax/spacingMode, scatterMin/scatterMax/scatterMode, rotationMin/rotationMax/rotationMode with modes fixed|random|pressure, rotationRelativeTo: page|path), Art (fields width %, scaleMode: proportional|stretch|betweenGuides, guideStart/guideEnd % of the art length, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flipAlong, flipAcross) or Pattern (fields scale %, spacing %, fit: stretch|addSpace|approximate, flipAlong, flipAcross); Scatter, Art and Pattern also colorization: none|tints|tintsAndShades|hueShift, keyColor, and tips: true opens Colorization Tips (what each method does, beside a sample of the brush painted with it), as the Tips button beside Method does; OK runs brush.options", + "{name?} (default: the selected path's brush, else the current brush) open its Brush Options, what double-clicking a brush in the Brushes panel opens (dialog `brushOptions`): Calligraphic (fields name, angle −180..180, roundness 0..100, size 0..1296 pt, angleMode/roundnessMode/sizeMode: fixed|random|pressure, angleVariation/roundnessVariation/sizeVariation), Bristle (fields name, shape, size, length, density, thickness, opacity, stiffness), Scatter (fields sizeMin/sizeMax/sizeMode, spacingMin/spacingMax/spacingMode, scatterMin/scatterMax/scatterMode, rotationMin/rotationMax/rotationMode with modes fixed|random|pressure, rotationRelativeTo: page|path, hueJitter 0..180°), Art (fields width %, scaleMode: proportional|stretch|betweenGuides, guideStart/guideEnd % of the art length, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flipAlong, flipAcross) or Pattern (fields scale %, spacing %, fit: stretch|addSpace|approximate, flipAlong, flipAcross); Scatter, Art and Pattern also colorization: none|tints|tintsAndShades|hueShift, keyColor, and tips: true opens Colorization Tips (what each method does, beside a sample of the brush painted with it), as the Tips button beside Method does; OK runs brush.options", + ), + ( + "ui.brushObjectOptions", + "Options of Selected Object…", + "", + "{} open the Brushes panel menu's Options of Selected Object (dialog `brushOptions` with `__object`): the Brush Options of the brush that the first selected brushed path paints with, at that path's own settings, without the name field; Art shows width, widthMax/widthMode, flipAlong, flipAcross and overlap, and Pattern scale, spacing, flipAlong, flipAcross and fit, each with colorization; OK runs brush.objectOptions on the brushed paths selected when it opened, with the values changed since it opened (one end of a range or one colorization field changed leaves each path's other values as they are), and the brush stays as it is. An error with nothing painted with a brush selected, for paths painted with brushes of different types and for a bristle brush", ), ( "ui.graphicStyleOptions", @@ -974,7 +1027,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.symbolOptions", "Symbol Options…", "F8", - "{name?} open Symbol Options (dialog `symbolOptions`, fields `name`, `exportType`: movieClip|graphic, `registration` 0..8). Without `name` and with a selection: New Symbol (default name the first free \"New Symbol\"/\"New Symbol N\", Export Type Movie Clip, Registration centre); OK runs symbol.new {name, exportType, registration}. With `edit: true` or `name`: edit that symbol; OK runs symbol.options {name, newName?, exportType, registration}", + "{name?, edit?, keepArt?: false} open Symbol Options (dialog `symbolOptions`, fields `name`, `exportType`: movieClip|graphic, `registration` 0..8). Without `name` and with a selection: New Symbol (default name the first free \"New Symbol\"/\"New Symbol N\", Export Type Movie Clip, Registration centre); OK runs symbol.new {name, exportType, registration}, with keepArt: true when it was opened with keepArt: true (the selection stays ordinary art). With `edit: true` or `name`: edit that symbol; OK runs symbol.options {name, newName?, exportType, registration}; keepArt: true is then an error", ), ( "tool.options", @@ -1098,7 +1151,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.navigatorPanelOptions", "Panel Options…", "", - "{color?: #rrggbb or a preset name (Light Red, the default, then the layer colors such as \"Light Blue\"), solidDashes?: bool (Draw Dashed Lines as Solid Lines, off by default: the Navigator's thumbnail draws dashed strokes without their dashes; the canvas, printing and exports keep them)} set the Navigator panel's options, the color its view box is drawn in and solid dashes (kept with the UI state) → {color, solidDashes}; with neither, open its Panel Options (dialog `navigatorPanelOptions`, fields color, solidDashes; OK sets them); an error for a value that is not a color or not true or false, which changes nothing", + "{color?: #rrggbb or a preset name (Light Red, the default, then the layer colors such as \"Light Blue\"), solidDashes?: bool (Draw Dashed Lines as Solid Lines, off by default: the Navigator's thumbnail draws dashed strokes without their dashes; the canvas, printing and exports keep them), viewArtboardContentsOnly?: bool (View Artboard Contents Only in the panel menu, on by default and for UI state saved without it: the thumbnail fits the artboards and draws only the art inside them, cut at each artboard's edges; off, it also shows the art on the pasteboard)} set the Navigator panel's options, the color its view box is drawn in, solid dashes and artboard contents only (kept with the UI state) → {color, solidDashes, viewArtboardContentsOnly}; with none, open its Panel Options (dialog `navigatorPanelOptions`, fields color, solidDashes; OK sets them); an error for a value that is not a color or not true or false, which changes nothing", ), ( "ui.layersExpand", @@ -1148,6 +1201,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{highlight?: none|rasterizedRegions|transparentObjects|allAffected|expandedPatterns|outlinedStrokes|outlinedText|allRasterized, overprints?: preserve|simulate|discard, preset?: name (loads its options), options?: {option keys, over the preset's}, showOptions?} set the Flattener Preview panel (ui.inspect: ui.flattener_preview), show it and refresh its snapshot → what flattener.preview answers for it", ), + ( + "ui.foldPreview", + "Fold Preview", + "", + "{amount?: 0..1 (how far the blank is folded), view?: front|back|left|right|top|bottom|threeQuarter, rotateX?: deg -180..180 (the top toward the viewer), rotateY?: deg -180..180 (the right side toward the viewer), zoom?: 0.1..8 (1 fits the folded blank), perspective?: deg 0..160 (field of view; 0 for none), inside?: #rrggbb, the name of a swatch with a plain color, or empty for white (the board's inside), showFoldLines?: bool, base?: [x, y] (the panel under this point stays in place; an error when it is in no panel) or null (the largest panel)} set the Fold Preview window (ui.inspect: ui.fold_preview), which folds the blank that the document's shown fold lines make (addon.packaging.fold) with the document's art printed on the outside, show it and draw it again; view and zoom also center the view. A value of the wrong kind or out of range is an error and sets nothing → the window's settings and frame: the last frame's {width, height (pixels), foldMs, drawMs} or null", + ), ( "ui.copyScriptConsole", "Copy Script Console", @@ -1265,7 +1324,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.expandDialog", "Expand…", "", - "{} open Expand for the selection (dialog `expand`, fields object, fill, stroke (all on; one the selection has nothing for is disabled, see object.expand.info), gradient: objects|mesh, steps 1..1000 (255)): OK runs object.expand with them as one undo step; dimmed, and an error, while the selection has an appearance effect.expandAppearance expands (object.expand.info's appearance)", + "{immediate?: bool (false)} open Expand for the selection (dialog `expand`, fields object, fill, stroke (all on; one the selection has nothing for is disabled, see object.expand.info), gradient: objects|mesh, steps 1..1000 (255), or the choices OK last expanded with since the app started): OK runs object.expand with them as one undo step and keeps them until the app quits; immediate: true (the menu item chosen with Alt/Option) runs object.expand at once with those choices (the defaults before any OK), and opens the dialog instead when none of them has something to expand in the selection; dimmed, and an error, while the selection has an appearance effect.expandAppearance expands (object.expand.info's appearance)", ), ( "attributes.openUrl", @@ -1381,6 +1440,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} switch the Color panel's R, G and B between percent and 0 to 255, as a double-click right of an RGB field does (ui.colorPanel {rgbPercent}); the color does not change, and the choice is kept with the preferences; a parameter is an error and changes nothing → true when they show in percent", ), + ( + "ui.colorWheel", + "Color Wheel Options", + "", + "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, and pick the box's channel, as Box Channel does: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); keys left out keep their values, params that are not an object, another key or a value off the list are an error and change nothing, both are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel}", + ), ( "ui.savePdfDialog", "Save PDF Dialog", @@ -1636,6 +1701,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{path? | data?: the file's text} read an action set file (.vcactions) at path, else a picked one, and add its set after the Actions panel's sets; a set named like one in the panel gets the next free number (Print 2), and the other sets stay. Files of another version, over 8 MiB, with more than 1,000 actions or with an action of more than 10,000 steps are refused, and so is any set, .aia ones too, that Save Actions… would write larger than 8 MiB (a file with less white space, or a name that gets a number); the panel menu's Load Actions… (disabled where there is no open dialog, the web) → {set: index, name, actions: n}. An action set another app saved as text (.aia, starting /version; read with actionSet.read) comes in with its actions. A step with a label and no recorded values comes in when exactly one menu command has that label (in English or the interface language, any case, no final …), and that command is directly in a top menu, can be recorded in actions, is what its menu bar item runs with no values and opens no dialog (never a submenu's item, a file or document command, Paste, Undo, Redo or an add-on's command), with no params and excluded from playback when it is off in the file. A Set Selection step (found by its internal name, whatever its label) comes in as select.byNote {note, caseSensitive, wholeWord} when it has exactly three recorded values: text (ustring, UTF-8; 1 to 1,024 bytes once trimmed), word and case (boolean, 0 or 1); with any other values it is left out. The other steps, every other step with no label and every other step recorded with values (a recorded menu item too) among them, are left out → {set, name, actions, skipped: [{action, step: its label, else its name}] (the first 1,000), leftOut: n}, and the status bar says how many were left out; a set with no name takes the file's name, else Actions; a file actionSet.read marks truncated is refused, and text that starts /version and isn't an action set gives \"not an action set file\"", ), + ( + crate::panels::actions::REPLACE_SET, + "Replace Actions…", + "", + "{path? | data?: the file's text} read an action set file at path, else a picked one, as ui.actionSet.load reads it (.vcactions and .aia, with the same limits, errors and reports of left-out steps and unknown commands), and replace every set in the Actions panel, the built-in Default Actions set included, with the file's set, which keeps its name. The set becomes current and selected, the panel's selected action and step and its expanded actions are cleared, and an open Set Options, New Action, Batch or step dialog that names a set closes; when the panel already holds only a set that saves alike, in that state, nothing changes, the set keeps its ids and changed is false. Omitted params count as {}. Params of another type, another key, a path or data that is not a string, a file that can't be read or is refused, a canceled pick, or a replace while an action records or plays (also while it waits at a stop) is an error and changes nothing. No undo step is recorded. The panel menu's Replace Actions… (disabled where there is no open dialog, the web, and while an action records or plays) → {changed, set: 0, name, actions: n, unknownCommands?, unknownCount?, skipped?, leftOut?}", + ), ( crate::panels::actions::DELETE_SETS, "Delete Action Sets", @@ -1665,7 +1736,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.epsOptionsDialog", "EPS Options Dialog", "", - "{path?, useArtboards?, range?, …document.exportEps options} open EPS Options (dialog `epsOptions`: fields = these options over the ones used last); OK checks them, remembers them and writes path (else asks). Export As… → EPS opens it too", + "{path?, useArtboards?, range?, …document.exportEps options} open EPS Options (dialog `epsOptions`: fields = these options over the ones used last; Custom… sets `flattener`, which a flattenerPreset given without it drops); OK checks them, remembers them and writes path (else asks). Export As… → EPS opens it too", ), ( "file.saveForWeb", diff --git a/crates/ui-egui/src/native_menu.rs b/crates/ui-egui/src/native_menu.rs index 510131be0e..abe15ab2a0 100644 --- a/crates/ui-egui/src/native_menu.rs +++ b/crates/ui-egui/src/native_menu.rs @@ -3,12 +3,12 @@ //! [`Backend`] (the desktop app's, through muda). //! //! Pure and platform-free, so it is tested everywhere and builds for the web; only the backend -//! touches AppKit. What the layout does ([`mac_layout`], Illustrator on the Mac as the reference): +//! touches AppKit. What the layout does ([`mac_layout`]): //! - an **app menu** named VectorCraft: About; Settings, a submenu with one item per Preferences //! page (General… ⌘K first); Language; Appearance (the UI brightness); Services; Hide VectorCraft //! ⌃⌘H (⌘H stays View › Hide Edges), Hide Others ⌥⌘H, Show All; and Quit ⌘Q, still the app's own //! `app.quit`, so documents with unsaved changes are asked about. Language and Appearance have -//! no in-window menu (as in PhotoCraft) and are synthesized here; Quit is File › Exit in the +//! no in-window menu and are synthesized here; Quit is File › Exit in the //! window and reads as Quit in the App menu. These leave the other menus (Edit › Preferences…, //! Help › About), and Join Our Discord stays under Help only; //! - **Window** gets Minimize ⌃⌘M, Zoom and Bring All to Front, and **Help** the system's search @@ -299,7 +299,7 @@ pub struct Layout { } /// The Mac menu bar of `bar` (the in-window menus, [`from_tree`]): see the module docs. -/// Language and Appearance have no in-window menu (as in PhotoCraft); when the tree doesn't +/// Language and Appearance have no in-window menu; when the tree doesn't /// carry them they are synthesized below, so the App menu keeps them. pub fn mac_layout(app: &VectorcraftApp, bar: &MenuBar, lang: Lang) -> Layout { let mut bar = bar.clone(); @@ -400,7 +400,7 @@ fn native_item(app: &VectorcraftApp, label: &'static str, command: &'static str, } /// Settings ▸: one item per page of the Preferences dialog (its own list), each opening it there; -/// the first (General…) has Preferences' shortcut (⌘K), as in Illustrator. +/// the first (General…) has Preferences' shortcut (⌘K). fn settings_pages(preferences: &Item, lang: Lang) -> Vec { vectorcraft_engine::cmd::prefscmds::PREF_CATEGORIES .iter() @@ -610,7 +610,7 @@ pub fn sync(app: &mut VectorcraftApp, ctx: &egui::Context) { /// interaction is open (for example a move, scale or shape drag, a dialog's or the font menu's /// preview, or a typing session), the revision, which each of its previews changes, is left out: /// the hash changes as the interaction begins and as it ends. -fn state_hash(app: &VectorcraftApp, input: Option) -> u64 { +pub(crate) fn state_hash(app: &VectorcraftApp, input: Option) -> u64 { let mut h = DefaultHasher::new(); input.hash(&mut h); app.run_count.hash(&mut h); diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index 5c531019ce..9832567689 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -9,6 +9,7 @@ use crate::theme::Tokens; use crate::{VectorcraftApp, menus}; mod search; +pub(crate) mod words; /// Engine commands the palette leaves out, each with the UI command of the same name that runs it /// the way the panels and menus do: (engine id, UI command id). The Layers panel's Delete @@ -20,6 +21,7 @@ const WRAPPED: &[(&str, &str)] = &[ ("layer.delete", "ui.layerDelete"), ("brush.new", "ui.newBrush"), ("brush.options", "ui.brushOptions"), + ("brush.objectOptions", "ui.brushObjectOptions"), ("symbol.options", "ui.symbolOptions"), ("svgFilter.import", "ui.importSvgFilter"), ("text.convertListToText", "type.convertListToText"), @@ -285,6 +287,12 @@ pub(crate) struct Entry { menu_item: &'static str, /// The entry's kind, in the order [`search::kind`] ranks kinds. kind: u8, + /// Where the row's label starts in `shown`: after the menu path, which the row shows as the + /// entry's home instead ([`home_text`]), or 0. + label_at: usize, + /// Does the row's home name the item of the menu bar after its menu path, since the item's + /// label differs from the entry's? + names_item: bool, } /// The palette's entries, the index a query is looked up in, and the last query's ranked results. @@ -337,10 +345,27 @@ fn catalog(lang: crate::i18n::Lang, native: bool) -> Catalog { let list = build_in(lang, native); let shown_homes: Vec> = list.iter().map(|e| e.home.as_deref().map(|h| format!("{} › {}", shown_label(lang, h), crate::i18n::tr(lang, e.menu_item)))).collect(); - let index = search::Index::build(&list, &shown_homes); + // A group's row in the `search` context gives its words in `lang`; a plain row is not read. + let search_row = |key: &str| crate::i18n::tr_ctx_row(lang, words::CONTEXT, key).map(str::to_string); + let index = search::Index::build(&list, &shown_homes, ¶ms_texts(&list), search_row); Catalog { list, index, ranked: std::sync::Mutex::new(None) } } +/// The params text of each entry's command, which the index reads a description from +/// ([`search::description`]): an engine or plug-in command's, a UI command's (the one it wraps +/// keeps its own) and an effect's. A tool, a panel and a filter plug-in have none. +fn params_texts(list: &[Entry]) -> Vec<&'static str> { + let engine = vectorcraft_engine::command_specs().iter().chain(vectorcraft_engine::cmd::plugin::command_specs()); + let mut by_id: std::collections::HashMap<&str, &'static str> = engine.map(|c| (c.id, c.params)).collect(); + by_id.extend(menus::UI_COMMANDS.iter().map(|c| (c.0, c.3))); + list.iter() + .map(|e| match e.id.strip_prefix("effect:") { + Some(effect) => vectorcraft_effects::effect_info(effect).map_or("", |info| info.params), + None => by_id.get(e.id.as_str()).copied().unwrap_or(""), + }) + .collect() +} + /// The palette's entries in `lang` with the in-window menu bar. #[cfg(test)] fn build(lang: crate::i18n::Lang) -> Vec { @@ -373,7 +398,16 @@ fn build_in(lang: crate::i18n::Lang, native: bool) -> Vec { } let (home, menu_item) = homes.get(&d.id).map_or((None, ""), |(path, item)| (Some(path.clone()), *item)); let kind = search::kind(&d.id, home.as_deref()); - Entry { id: d.id, shortcut: d.shortcut, shown, haystack, home, menu_item, kind } + // A row with a home shows its label without the menu path in front of it. A path that + // makes the name distinct ([`distinct_names`]) stays, unless the row's home shows that + // same path or it is the Tools in front of a tool's name, which the tool's kind and + // toolbar show. + let tool = d.id.starts_with("tool:"); + let drop = if d.in_context { home.as_deref() == Some(d.path.as_str()) || (tool && d.path == "Tools") } else { home.is_some() || tool }; + let prefix = format!("{} › ", shown_label(lang, &d.path)); + let label_at = if drop && !d.path.is_empty() && shown.starts_with(&prefix) { prefix.len() } else { 0 }; + let names_item = !menu_item.is_empty() && menu_item != d.label; + Entry { id: d.id, shortcut: d.shortcut, shown, haystack, home, menu_item, kind, label_at, names_item } }) .collect() } @@ -444,10 +478,87 @@ const TOP: f32 = 90.0; /// The space kept between the popup and the bottom of the window, in points. const BOTTOM_GAP: f32 = 8.0; -/// What a result row shows and screen readers read: its name, and its shortcut after a comma. -fn row_label(e: &Entry) -> String { +/// The point size of the kind icon at the start of a result row. +const KIND_ICON: f32 = 14.0; +/// The point size of the home's text after a row's label. +const HOME_TEXT: f32 = 11.0; + +/// The kind of result `e` is: the icon its row starts with and the word screen readers read +/// first, in the UI language. A tool shows its own icon. +fn kind_of(e: &Entry) -> (&'static str, &'static str) { + match e.id.split_once(':') { + Some(("tool", tool)) => (vectorcraft_tools::tool_info(tool).map_or("square-dashed", |t| crate::icons::tool_icon(t.icon)), tl!("Tool")), + Some(("panel", _)) => ("layout-grid", tl!("Panel")), + Some(("effect", _)) => ("dc-fx", tl!("Effect")), + Some(("plugin", _)) => ("dc-filter", tl!("Filter")), + _ => ("menu", tl!("Command")), + } +} + +/// The label a result row shows: its name without the menu path its home shows. +fn label_of(e: &Entry) -> &str { + e.shown.get(e.label_at..).unwrap_or(&e.shown) +} + +/// Where result `e` lives, as its row shows it: a tool's place on the toolbars ([`tool_home`]), +/// the menu path of the item of the menu bar that runs it (with the item's label when it differs +/// from the result's), or "No menu item". +fn home_text(app: &VectorcraftApp, e: &Entry) -> String { + let lang = crate::i18n::current(); + if let Some(tool) = e.id.strip_prefix("tool:") { + return tool_home(app, tool); + } + match &e.home { + Some(path) if e.names_item => format!("{} › {}", shown_label(lang, path), crate::i18n::tr(lang, e.menu_item)), + Some(path) => shown_label(lang, path), + None => tl!("No menu item").to_string(), + } +} + +/// Where `tool` is in the current layout: "Toolbar" for its button on the Tools panel, or the name +/// of the toolbar made with New Toolbar that holds it, followed by ", in the group", naming +/// the tool its slot's button shows, when the tool is hidden in that slot's group; "All Tools" +/// when no toolbar holds it. A toolbar shown now comes first: the Tools panel, then the toolbars +/// made with New Toolbar; then a hidden Tools panel, then hidden toolbars made with New Toolbar. +/// Toolbars are hidden in Presentation Mode and while Tab hides the panels. +fn tool_home(app: &VectorcraftApp, tool: &str) -> String { + let lang = crate::i18n::current(); + let place = |name: &str, shown: Option<&str>| match shown.filter(|s| *s != tool).and_then(vectorcraft_tools::tool_info) { + // The tool goes in first, so a toolbar named with a placeholder keeps its name. + Some(t) => crate::i18n::fmt(tl!("{toolbar}, in the {tool} group"), &[("tool", crate::i18n::tr(lang, t.label)), ("toolbar", name)]), + None => name.to_string(), + }; + let toolbars_shown = app.ui.screen_mode < 3 && app.ui.tab_hid.is_none(); + let main = crate::toolbar::slots(app).into_iter().map(|(_, s)| s).find(|s| s.contains(&tool)); + let main = main.map(|slot| place(tl!("Toolbar"), Some(crate::toolbar::shown_tool(app, &slot)))); + let active = app.session.tool_id(); + let custom = |shown: bool| { + app.ui.custom_toolbars.iter().filter(|b| b.shown == shown).find_map(|bar| { + let slot = bar.slots.iter().find(|s| s.iter().any(|t| t == tool))?; + let tools: Vec<&'static str> = slot.iter().filter_map(|id| vectorcraft_tools::tool_info(id).map(|t| t.id)).collect(); + Some(place(&bar.name, crate::custom_toolbars::shown_tool(bar, active, &tools))) + }) + }; + if toolbars_shown { + if app.ui.toolbar + && let Some(main) = &main + { + return main.clone(); + } + if let Some(bar) = custom(true) { + return bar; + } + } + main.or_else(|| custom(true)).or_else(|| custom(false)).unwrap_or_else(|| tl!("All Tools").to_string()) +} + +/// What screen readers read for a result row, and its hover text: its kind, its label, where it +/// lives (`home`) and its shortcut, after commas. +fn row_label(e: &Entry, home: &str) -> String { let shortcut = menus::shown_shortcut(&e.shortcut); - if shortcut.is_empty() { e.shown.clone() } else { format!("{}, {shortcut}", e.shown) } + let kind = kind_of(e).1; + let start = format!("{kind}, {}, {home}", label_of(e)); + if shortcut.is_empty() { start } else { format!("{start}, {shortcut}") } } /// The line under the results: how many results matched, how many of them the list holds when it @@ -501,6 +612,41 @@ fn name_galley(painter: &egui::Painter, name: &str, font: egui::FontId, color: e painter.layout_job(job) } +/// A result row's label and home laid out in `width` points, and whether either was cut short. The +/// home goes after the label in the smaller dim text and is cut first; when the label alone does +/// not fit, the home is left out and the label is cut before the id it shows after its name +/// ([`distinct_names`]), which stays whole unless the id alone is wider than the row. +fn row_galleys( + painter: &egui::Painter, + e: &Entry, + home: &str, + font: egui::FontId, + color: egui::Color32, + dim: egui::Color32, + width: f32, +) -> (Arc, Option>, bool) { + let label = label_of(e); + let full = name_galley(painter, label, font.clone(), color, f32::INFINITY); + let room = width - full.size().x - 10.0; + if full.size().x <= width { + if room < HOME_TEXT { + return (full, None, !home.is_empty()); + } + let home = name_galley(painter, home, egui::FontId::new(HOME_TEXT, font.family), dim, room); + let cut = home.elided; + return (full, Some(home), cut); + } + let suffix = format!(" ({})", e.id); + let (head, suffix) = match label.strip_suffix(suffix.as_str()) { + Some(head) => (head, suffix), + None => (label, String::new()), + }; + let suffix_width = name_galley(painter, &suffix, font.clone(), color, f32::INFINITY).size().x; + let cut_head = name_galley(painter, head, font.clone(), color, width - suffix_width); + let shown: String = cut_head.rows.iter().flat_map(|r| r.glyphs.iter().map(|g| g.chr)).collect(); + (name_galley(painter, &format!("{shown}{suffix}"), font, color, width), None, true) +} + /// The scroll offset that keeps row `sel` in a list `view` points tall that was scrolled to `offset`. fn offset_showing(sel: usize, offset: f32, view: f32) -> f32 { let top = sel as f32 * ROW_HEIGHT; @@ -563,8 +709,9 @@ pub(crate) fn recent_list_open(ctx: &egui::Context) -> bool { pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { // The widget that had the keyboard focus when the palette opened takes it back when the palette - // closes, unless a pick opened a dialog, which focuses its own first field, or the press that - // closed it focused another widget, such as a field in a window above the backdrop. + // closes, unless a modal window is up (a pick opened a dialog, which focuses its own first + // field, or a window that opened closed the palette), or the press that closed it focused + // another widget, such as a field in a window above the backdrop. let focus_id = egui::Id::unique("palette-focus-before"); let field_id = egui::Id::unique("palette-field"); if !app.ui.palette_open { @@ -575,7 +722,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { }); let now = ctx.memory(|m| m.focused()); if let Some(Some(before)) = ctx.data_mut(|d| d.remove_temp::>(focus_id)) - && app.ui.dialog.is_none() + && !crate::panel_docking::modal_window_up(app, ctx) && (now.is_none() || now == field) { ctx.memory_mut(|m| m.request_focus(before)); @@ -738,7 +885,8 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let rank = if sel + 1 == matches.len() { kept.unwrap_or(sel) } else { sel }; let pos = (rank + 1).to_string(); let of = total.to_string(); - let said = crate::i18n::fmt(tl!("{pos} of {total}: {name}"), &[("pos", &pos), ("total", &of), ("name", &row_label(e))]); + let name = row_label(e, &home_text(app, e)); + let said = crate::i18n::fmt(tl!("{pos} of {total}: {name}"), &[("pos", &pos), ("total", &of), ("name", &name)]); ui.ctx().accesskit_node_builder(r.id, |node| node.set_description(said)); } if n > 0 { @@ -763,16 +911,29 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { } let font = egui::TextStyle::Body.resolve(ui.style()); let shortcut = menus::shown_shortcut(&e.shortcut); + let home = home_text(app, e); + let said = row_label(e, &home); let p = ui.painter(); let shortcut_at = rect.right_center() - egui::vec2(8.0, 0.0); let used = p.text(shortcut_at, egui::Align2::RIGHT_CENTER, &shortcut, font.clone(), t.text_dim); let name_end = if shortcut.is_empty() { rect.right() - 8.0 } else { used.left() - 12.0 }; - let name_at = rect.left() + 8.0; - let name = name_galley(p, &e.shown, font, t.text, name_end - name_at); - p.galley(egui::pos2(name_at, rect.center().y - name.size().y / 2.0), name, t.text); + let icon = egui::Rect::from_center_size( + egui::pos2(rect.left() + 8.0 + KIND_ICON / 2.0, rect.center().y), + egui::Vec2::splat(KIND_ICON), + ); + crate::icons::paint(ui, kind_of(e).0, icon, t.icon); + let name_at = icon.right() + 6.0; + let (label, home, cut) = row_galleys(p, e, &home, font, t.text, t.text_dim, name_end - name_at); + let home_at = name_at + label.size().x + 10.0; + p.galley(egui::pos2(name_at, rect.center().y - label.size().y / 2.0), label, t.text); + if let Some(home) = home { + p.galley(egui::pos2(home_at, rect.center().y - home.size().y / 2.0), home, t.text_dim); + } + // A row whose text is cut short shows all of it while the pointer rests on it. + let resp = if cut { resp.on_hover_text(said.clone()) } else { resp }; // `WidgetInfo::selected` reaches screen readers as a toggled state, so the // row sets the selected state on its node itself. - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ListItem, true, row_label(e))); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ListItem, true, said.clone())); ui.ctx().accesskit_node_builder(resp.id, |node| node.set_selected(on)); if resp.clicked() { run = Some(e.id.clone()); @@ -1764,10 +1925,12 @@ mod tests { assert_eq!(panels.len(), crate::state::all_panels().count()); // Many results hold "layers" in their menu path; the panel, named Layers, is shown first, and "color guide" shows the Color Guide panel first too. for (query, want) in [("layers", "panel:layers"), ("color guide", "panel:colorGuide"), ("Layers ", "panel:layers")] { - let all = entries.iter().filter(|e| query.to_lowercase().split_whitespace().all(|w| e.haystack.contains(w))).count(); + let all: Vec<&str> = + entries.iter().filter(|e| query.to_lowercase().split_whitespace().all(|w| e.haystack.contains(w))).map(|e| e.id.as_str()).collect(); let shown: Vec<&str> = matching(&entries, &query.to_lowercase()).into_iter().map(|e| e.id.as_str()).collect(); assert_eq!(shown.first(), Some(&want), "{query}: {shown:?}"); - assert_eq!(shown.len(), all, "{query}"); + // English plural and verb forms can find more results than the text alone. + assert!(all.iter().all(|id| shown.contains(id)), "{query}"); } let layers = entries.iter().find(|e| e.id == "panel:layers").unwrap(); assert_eq!(layers.shown, "Window › Show Panel › Layers"); @@ -1804,8 +1967,16 @@ mod tests { /// does, and changes nothing until the dialog is confirmed. #[test] fn an_effect_is_a_result_whose_pick_runs_its_menu_item() { - let entries = build(Lang::EN); - let effects = crate::shortcut_editor::effect_items(); + // Both reads see the same plug-in revision: another test may install or remove a live + // effect plug-in between them. + let (entries, effects) = loop { + let revision = menus::plugin_revision(); + let entries = build(Lang::EN); + let effects = crate::shortcut_editor::effect_items(); + if menus::plugin_revision() == revision { + break (entries, effects); + } + }; for e in effects.iter() { let key = format!("effect:{}", e.effect); assert_eq!(entries.iter().filter(|r| r.id == key).count(), 1, "{key}"); @@ -1922,6 +2093,12 @@ mod tests { self.ctx.memory(|m| m.area_rect(egui::Id::unique("palette"))).unwrap() } + /// What screen readers read for result `id`'s row. + fn said(&self, id: &str) -> String { + let entries = entries(&self.ctx, Lang::EN); + entries.iter().find(|e| e.id == id).map(|e| row_label(e, &home_text(&self.app, e))).unwrap() + } + /// The results the palette lists for its query. fn listed(&self) -> Vec { let entries = entries(&self.ctx, Lang::EN); @@ -2030,8 +2207,7 @@ mod tests { let nodes = open.press(egui::Key::ArrowDown, 15); assert_eq!(open.highlighted(), 15); let lit: Vec<_> = rows(&nodes).into_iter().filter(|r| r.1).collect(); - let entries = entries(&open.ctx, Lang::EN); - let want = entries.iter().find(|e| e.id == listed[15]).map(row_label).unwrap(); + let want = open.said(&listed[15]); assert_eq!(lit.len(), 1, "{lit:?}"); assert_eq!(lit[0].0, want); let popup = open.popup(); @@ -2106,7 +2282,7 @@ mod tests { let lit: Vec<_> = rows(&nodes).into_iter().filter(|r| r.1).collect(); assert_eq!(lit.len(), 1, "{lit:?}"); assert!(lit[0].2 >= f64::from(popup.top()) && lit[0].3 <= f64::from(popup.bottom()), "{lit:?} in {popup:?}"); - assert_eq!(lit[0].0, row_label(entries(&open.ctx, Lang::EN).iter().find(|e| e.id == open.listed()[sel]).unwrap())); + assert_eq!(lit[0].0, open.said(&open.listed()[sel])); } /// Page Down, Up and Enter pressed in one frame move the highlight in that order, and Enter @@ -2199,7 +2375,7 @@ mod tests { assert!(open.repaint, "the frame that moved the highlight asks for another"); let nodes = open.frame(vec![]); let lit: Vec = rows(&nodes).into_iter().filter(|r| r.1).map(|r| r.0).collect(); - let label = entries.iter().find(|e| e.id == listed[3]).map(row_label).unwrap(); + let label = open.said(&listed[3]); assert_eq!(lit, std::slice::from_ref(&label)); assert_eq!(field_description(&nodes), format!("4 of {}: {label}", matching(&entries, "select").len())); } @@ -2221,6 +2397,206 @@ mod tests { out.textures_delta.clear(); } + /// The label and home of English result `id`'s row with the app's current layout. + fn label_and_home(app: &VectorcraftApp, id: &str) -> (String, String) { + crate::i18n::set_current(Lang::EN); + let entries = build(Lang::EN); + let e = entries.iter().find(|e| e.id == id).unwrap_or_else(|| panic!("{id} is listed")); + (label_of(e).to_string(), home_text(app, e)) + } + + /// A row shows its label without the menu path, and the menu path of the item of the menu bar + /// that runs it after it: with that item's label when it differs, and "No menu item" for a + /// command no item runs. + #[test] + fn rows_show_where_each_result_lives() { + let app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let row = |id: &str| label_and_home(&app, id); + assert_eq!(row("effect:stylize.roundCorners"), ("Round Corners…".into(), "Effect › Stylize".into())); + assert_eq!(row("panel:layers"), ("Layers".into(), "Window".into())); + assert_eq!(row("object.group"), ("Group".into(), "Object".into())); + assert_eq!(row("app.quit").1, "File › Exit"); + // Window › Learn runs the Learn command as well as showing the Learn panel. + assert_eq!(row("window.learn").1, "Window"); + let entries = build(Lang::EN); + let learn = entries.iter().find(|e| e.id == "window.learn").expect("the Learn command"); + assert_eq!(learn.kind, search::kind("object.group", Some("Object")), "the Learn command ranks as a command of the menu bar"); + let none = entries.iter().find(|e| e.home.is_none() && !e.id.starts_with("tool:")).expect("a command with no menu item"); + assert_eq!((label_of(none), home_text(&app, none).as_str()), (none.shown.as_str(), "No menu item")); + // A path that keeps two names apart stays, unless the home shows it: the Knife tool's row + // drops the Tools in front of its name, and an Other Library… row shows its library menu + // as its home only. + assert_eq!(row("tool:knife").0, "Knife"); + let other: Vec<(&str, String)> = + entries.iter().filter(|e| e.shown.ends_with("Other Library…")).map(|e| (label_of(e), home_text(&app, e))).collect(); + assert!(other.len() >= 2 && other.iter().all(|(label, home)| *label == "Other Library…" && home.starts_with("Window › ")), "{other:?}"); + let kept = entries.iter().find(|e| e.label_at == 0 && e.shown.contains(" › ")).expect("a row that keeps its path"); + assert!(kept.home.as_deref().is_none_or(|h| !kept.shown.starts_with(&format!("{h} › "))), "{}", kept.shown); + for e in entries.iter().filter(|e| e.label_at > 0) { + assert!(e.home.is_some() || e.id.starts_with("tool:"), "{} has no home but drops its path", e.id); + } + } + + /// No two results' rows show the same kind, label and home, in any language, with the menu bar + /// in the window or the native one. + #[test] + fn no_two_rows_read_alike() { + let app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let mut alike = vec![]; + for lang in Lang::all() { + crate::i18n::set_current(lang); + for native in [false, true] { + let mut seen = std::collections::HashMap::new(); + for e in &build_in(lang, native) { + let row = (kind_of(e).1, label_of(e).to_string(), home_text(&app, e)); + if let Some(other) = seen.insert(row.clone(), e.id.clone()) + && other != e.id + { + alike.push(format!("{} (native {native}): {other} and {}: {row:?}", lang.code(), e.id)); + } + } + } + } + crate::i18n::set_current(Lang::EN); + assert!(alike.is_empty(), "{}", alike.join("\n")); + } + + /// Every catalog translates the words a row's kind and home are read with. + #[test] + fn catalogs_translate_the_kind_and_home_words() { + let words = ["Tool", "Panel", "Effect", "Filter", "Command", "Toolbar", "{toolbar}, in the {tool} group", "All Tools", "No menu item"]; + let missing: Vec = Lang::all() + .filter(|l| *l != Lang::EN) + .flat_map(|l| words.iter().filter(move |w| !crate::i18n::has(l, w)).map(move |w| format!("{}: {w}", l.code()))) + .collect(); + assert!(missing.is_empty(), "{missing:?}"); + } + + /// A tool's row names the toolbar it is on, and the tool its slot's button shows while it is + /// hidden in that slot's group. A toolbar shown now comes before a hidden Tools panel, which + /// comes before a hidden toolbar made with New Toolbar. + #[test] + fn a_tool_row_names_its_toolbar_slot() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let home = |app: &VectorcraftApp, id: &str| label_and_home(app, id).1; + assert_eq!(home(&app, "tool:groupSelection"), "Toolbar, in the Direct Selection Tool group"); + assert_eq!(home(&app, "tool:directSelection"), "Toolbar"); + app.select_tool("groupSelection"); + assert_eq!(home(&app, "tool:groupSelection"), "Toolbar"); + assert_eq!(home(&app, "tool:directSelection"), "Toolbar, in the Group Selection Tool group"); + let bar = |name: &str, slot: &[&str], shown: bool| crate::state::CustomToolbar { + name: name.into(), + slots: vec![slot.iter().map(|t| t.to_string()).collect()], + shown, + pos: [0.0, 0.0], + dock: None, + dock_right: false, + slot_tool: Default::default(), + double: false, + floating: vec![], + }; + // Window › Tools hides the Tools panel while a toolbar made with New Toolbar holds the Pen + // Tool: the row names that toolbar. + app.ui.toolbar = false; + assert_eq!(home(&app, "tool:pen"), "Toolbar"); + app.ui.custom_toolbars.push(bar("Drawing", &["pen", "curvature"], true)); + assert_eq!(home(&app, "tool:pen"), "Drawing"); + assert_eq!(home(&app, "tool:curvature"), "Drawing, in the Pen Tool group"); + app.ui.custom_toolbars[0].name = "{tool}".into(); + assert_eq!(home(&app, "tool:curvature"), "{tool}, in the Pen Tool group"); + app.ui.custom_toolbars[0].name = "Drawing".into(); + // Tab hides the toolbars made with New Toolbar too: the hidden Tools panel comes first. + app.ui.tab_hid = Some(crate::state::TabHid { dock: true, toolbar: true, control_bar: true }); + assert_eq!(home(&app, "tool:pen"), "Toolbar"); + app.ui.tab_hid = None; + // The Tools panel shown again comes first. + app.ui.toolbar = true; + assert_eq!(home(&app, "tool:pen"), "Toolbar"); + // In Presentation Mode no toolbar shows; the tool still lives on the Tools panel. + app.ui.screen_mode = 3; + assert_eq!(home(&app, "tool:pen"), "Toolbar"); + app.ui.screen_mode = 0; + // A tool that only a hidden toolbar made with New Toolbar holds is named on it, and one no + // toolbar holds is in All Tools. + let on_tools: Vec<&str> = crate::toolbar::slots(&app).into_iter().flat_map(|(_, s)| s).collect(); + let loose = vectorcraft_tools::catalog::all_tools().map(|t| t.id).find(|t| !on_tools.contains(t)).expect("a tool not on the Tools panel"); + let id = format!("tool:{loose}"); + assert_eq!(home(&app, &id), "All Tools"); + app.ui.custom_toolbars.push(bar("Cutting", &[loose], false)); + assert_eq!(home(&app, &id), "Cutting"); + } + + /// A row too narrow for its label and home cuts the home first; a label that does not fit + /// alone is cut before the id it shows after its name, which stays whole. + #[test] + fn a_narrow_row_cuts_the_home_first_and_keeps_the_id() { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let entries = build(Lang::EN); + let keyed = entries.iter().find(|e| e.shown.ends_with(&format!(" ({})", e.id))).expect("a result that shows its id"); + let copy = entries.iter().find(|e| e.id == "edit.copy").expect("Copy"); + let app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + let font = egui::TextStyle::Body.resolve(ui.style()); + let p = ui.painter(); + let lay = |e: &Entry, home: &str, width: f32| row_galleys(p, e, home, font.clone(), egui::Color32::WHITE, egui::Color32::GRAY, width); + let text = |g: &egui::Galley| g.rows.iter().flat_map(|r| r.glyphs.iter().map(|g| g.chr)).collect::(); + let (label, home, cut) = lay(copy, "Edit", 400.0); + assert_eq!((text(&label), home.map(|h| text(&h)), cut), ("Copy".into(), Some("Edit".into()), false)); + let long = "A Menu › A Submenu With A Long Name › Another Submenu"; + let (label, home, cut) = lay(copy, long, 160.0); + let home = home.expect("some of the home fits"); + assert!(cut && home.elided && text(&label) == "Copy", "{}", text(&home)); + assert!(label.size().x + 10.0 + home.size().x <= 160.0 + 0.5); + // A long German menu path is cut before the label. + crate::i18n::set_current(Lang::from_code("de").expect("German")); + let german = build_in(crate::i18n::current(), false); + let deep = german + .iter() + .filter(|e| e.label_at > 0) + .max_by_key(|e| e.home.as_ref().map_or(0, |h| shown_label(crate::i18n::current(), h).chars().count())); + let deep = deep.expect("a German row with a home"); + let path = home_text(&app, deep); + crate::i18n::set_current(Lang::EN); + let label_width = name_galley(p, label_of(deep), font.clone(), egui::Color32::WHITE, f32::INFINITY).size().x; + let (label, home, cut) = lay(deep, &path, label_width + 60.0); + assert!(cut && text(&label) == label_of(deep) && home.is_some_and(|h| h.elided), "{path}"); + let suffix = format!(" ({})", keyed.id); + let suffix_width = name_galley(p, &suffix, font.clone(), egui::Color32::WHITE, f32::INFINITY).size().x; + let full = name_galley(p, label_of(keyed), font.clone(), egui::Color32::WHITE, f32::INFINITY).size().x; + assert!(full - 5.0 > suffix_width + 20.0, "{}", label_of(keyed)); + for width in [full - 5.0, suffix_width + 20.0, suffix_width / 2.0] { + let (label, home, cut) = lay(keyed, long, width); + let shown = text(&label); + assert!(cut && home.is_none(), "{width}"); + assert!(label.size().x <= width + 0.5, "{width}: {shown} is {} wide", label.size().x); + // An id wider than the row is cut too. + assert_eq!(shown.ends_with(&format!("…{suffix}")), width > suffix_width, "{width}: {shown}"); + } + }); + out.textures_delta.clear(); + } + + /// Screen readers read a row as its kind, label, home and shortcut, and the field's + /// description names them too; the row's height is unchanged. + #[test] + fn screen_readers_hear_the_kind_and_home() { + let mut open = Open::new("round corners", WINDOW); + let nodes = open.frame(vec![]); + let said = open.said("effect:stylize.roundCorners"); + assert_eq!(said, "Effect, Round Corners…, Effect › Stylize"); + let row = rows(&nodes).into_iter().find(|r| r.0 == said).expect("its row is drawn"); + assert!((row.3 - row.2 - f64::from(ROW_HEIGHT)).abs() < 0.01, "{row:?}"); + assert!(field_description(&nodes).ends_with(&said), "{}", field_description(&nodes)); + let open = Open::new("group selection", WINDOW); + assert_eq!(open.said("tool:groupSelection"), "Tool, Group Selection Tool, Toolbar, in the Direct Selection Tool group"); + let mut open = Open::new("layers", WINDOW); + let said = open.said("panel:layers"); + assert!(said.starts_with("Panel, Layers, Window"), "{said}"); + let nodes = open.frame(vec![]); + assert!(rows(&nodes).iter().any(|r| r.0 == said)); + } + /// The popup stays inside a short window, showing fewer rows when 12 don't fit; a page is the /// rows shown. #[test] @@ -2271,7 +2647,8 @@ mod tests { let mut open = Open::new("show panel", WINDOW); let listed = open.listed(); let entries = entries(&open.ctx, Lang::EN); - let label = |i: usize| entries.iter().find(|e| e.id == listed[i]).map(row_label).unwrap(); + let said: Vec = listed.iter().map(|id| open.said(id)).collect(); + let label = |i: usize| said[i].clone(); let nodes = open.frame(vec![]); // More results match than the list holds: the place counts every match, as the footer does. let total = matching(&entries, "show panel").len(); @@ -2283,15 +2660,47 @@ mod tests { let nodes = open.press(egui::Key::ArrowDown, 1); assert_eq!(field_description(&nodes), format!("2 of {total}: {}", label(1))); // Fewer results match than the list holds. - let mut open = Open::new("copy", WINDOW); + let mut open = Open::new("eyedropper", WINDOW); let n = open.listed().len(); assert!((1..MAX_RESULTS).contains(&n), "{n}"); - let first = entries.iter().find(|e| e.id == open.listed()[0]).map(row_label).unwrap(); + let first = open.said(&open.listed()[0]); let nodes = open.frame(vec![]); assert_eq!(field_description(&nodes), format!("1 of {n}: {first}")); assert!(labels(&nodes).contains(&footer(n, n)), "{:?}", labels(&nodes)); } + /// When a modal window that is not a dialog, such as the About window, closes the palette, the + /// widget under the window's backdrop does not get the keyboard focus back. + #[test] + fn a_modal_window_that_closes_the_palette_keeps_the_focus_from_the_widget_under_it() { + let ctx = egui::Context::default(); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let mut text = String::new(); + let field = egui::Id::unique("other field"); + let mut frame = |app: &mut VectorcraftApp, focus: bool| { + ctx.run_ui(egui::RawInput::default(), |ui| { + let r = ui.add(egui::TextEdit::singleline(&mut text).id(field)); + if focus { + r.request_focus(); + } + show(app, ui.ctx()); + }) + .textures_delta + .clear(); + }; + frame(&mut app, true); + frame(&mut app, false); + app.ui.palette_open = true; + frame(&mut app, false); + frame(&mut app, false); + // As `panel_docking::close_overlays_for_modal` does when the About window opens. + app.ui.about = true; + app.ui.palette_open = false; + frame(&mut app, false); + frame(&mut app, false); + assert_ne!(ctx.memory(|m| m.focused()), Some(field), "the field under the About window does not take the focus"); + } + /// The widget that had the keyboard focus when the palette opened has it again once the /// palette closes. #[test] @@ -2387,6 +2796,9 @@ mod tests { /// app, as a progress window is drawn, and count its clicks. above: Option, above_clicks: usize, + /// Draw a modal window over the backdrop before the app's windows, as a progress window + /// of a plug-in, trace or open run is drawn. + progress: bool, } impl Window { @@ -2398,7 +2810,7 @@ mod tests { assert!(!app.session.doc().unwrap().selection.is_empty()); let ctx = egui::Context::default(); ctx.enable_accesskit(); - let mut window = Window { app, ctx, time: 0.0, above: None, above_clicks: 0 }; + let mut window = Window { app, ctx, time: 0.0, above: None, above_clicks: 0, progress: false }; window.frame(vec![]); window.frame(vec![]); window @@ -2410,9 +2822,13 @@ mod tests { let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, WINDOW); let input = egui::RawInput { time: Some(self.time), screen_rect: Some(screen), events, ..Default::default() }; let app = &mut self.app; - let (above, clicks) = (self.above, &mut self.above_clicks); + let (above, clicks, progress) = (self.above, &mut self.above_clicks, self.progress); let mut out = self.ctx.run_ui(input, |ui| { app.logic(ui.ctx()); + if progress { + let id = egui::Id::unique("test-progress"); + crate::dialogs::modal::show_at(ui.ctx(), "Progress", id, egui::Vec2::ZERO, 12, |ui| ui.label("Working")); + } app.ui(ui); if let Some(at) = above { let area = egui::Area::new(egui::Id::unique("test-above")).order(egui::Order::Foreground).fixed_pos(at); @@ -2484,6 +2900,150 @@ mod tests { assert_eq!(window.selection(), before, "the click does not reach the canvas"); } + /// #7906: a pick in the macOS menu bar that opens a dialog closes the palette, and the search + /// field does not keep the keyboard from the dialog. + #[test] + fn a_dialog_opened_from_the_system_menu_closes_the_palette() { + let mut window = Window::new(); + window.app.ui.palette_open = true; + window.frame(vec![]); + window.frame(vec![]); + let field = window.ctx.data(|d| d.get_temp::(egui::Id::unique("palette-field"))).expect("the search field is drawn"); + assert_eq!(window.ctx.memory(|m| m.focused()), Some(field), "the search field has the keyboard"); + menus::invoke_from_system_menu(&mut window.app, &window.ctx, "object.move", json!({})); + assert!(window.app.ui.dialog.is_some(), "Move… opens its dialog: {}", window.app.ui.status); + window.frame(vec![]); + assert!(!window.app.ui.palette_open, "the dialog closes the palette"); + window.frame(vec![]); + assert!(window.app.ui.dialog.is_some(), "the dialog stays open"); + assert_ne!(window.ctx.memory(|m| m.focused()), Some(field), "the search field does not keep the keyboard"); + } + + /// #7906: with the palette open, the About window that opens without a press closes the palette. + #[test] + fn the_about_window_closes_the_palette() { + let mut window = Window::new(); + window.app.ui.palette_open = true; + window.frame(vec![]); + menus::invoke_from_system_menu(&mut window.app, &window.ctx, "help.about", json!({})); + assert!(window.app.ui.about, "About opens"); + window.frame(vec![]); + assert!(!window.app.ui.palette_open, "the About window closes the palette"); + } + + /// #7906: a window drawn over the modal backdrop, as a plug-in, trace or open run's progress + /// window is, closes the palette in the pass it first draws. + #[test] + fn a_progress_window_closes_the_palette() { + let mut window = Window::new(); + window.app.ui.palette_open = true; + window.frame(vec![]); + assert!(window.app.ui.palette_open, "the palette is open"); + window.progress = true; + window.frame(vec![]); + assert!(!window.app.ui.palette_open, "the progress window closes the palette"); + } + + /// #7906: the palette opened from the macOS menu bar while a dialog is open closes again, and its + /// search field does not take the keyboard from the dialog. + #[test] + fn the_palette_opened_over_a_dialog_closes() { + let mut window = Window::new(); + menus::invoke(&mut window.app, "object.move", json!({})); + assert!(window.app.ui.dialog.is_some(), "Move… opens its dialog: {}", window.app.ui.status); + window.frame(vec![]); + window.frame(vec![]); + let before = window.ctx.memory(|m| m.focused()); + menus::invoke_from_system_menu(&mut window.app, &window.ctx, "help.commandPalette", json!({})); + assert!(window.app.ui.palette_open, "the command opens the palette"); + window.frame(vec![]); + window.frame(vec![]); + assert!(!window.app.ui.palette_open, "the dialog keeps the palette closed"); + assert!(window.app.ui.dialog.is_some(), "the dialog stays open"); + let field = window.ctx.data(|d| d.get_temp::(egui::Id::unique("palette-field"))); + let now = window.ctx.memory(|m| m.focused()); + assert!(field.is_none() || now != field, "the search field does not take the keyboard"); + assert_eq!(now, before, "the dialog keeps its focus"); + } + + /// #7906 as reported: with the palette open, a click on the Effect menu in the window's menu bar + /// closes the palette, and a dialog opened afterwards is not under it. + #[test] + fn a_click_on_the_menu_bar_closes_the_palette_before_a_dialog_opens() { + let mut window = Window::new(); + window.app.ui.palette_open = true; + let nodes = window.frame(vec![]); + window.click(button_at(&nodes, "Effect")); + assert!(!window.app.ui.palette_open, "the click on the menu bar closes the palette"); + menus::invoke(&mut window.app, "object.move", json!({})); + assert!(window.app.ui.dialog.is_some(), "Move… opens its dialog: {}", window.app.ui.status); + window.frame(vec![]); + window.frame(vec![]); + assert!(!window.app.ui.palette_open, "the palette stays closed over the dialog"); + } + + /// Opens `overlay` ("flyout", "drawer" or "menu") in a new window, then opens Move… without a + /// press, as the macOS menu bar or an automation command does: whether the overlay is still open. + fn overlay_open_after_a_dialog_opens(overlay: &str) -> bool { + let mut window = Window::new(); + match overlay { + "flyout" => { + window.app.ui.flyout = Some(0); + let tools = vec!["rectangle".to_string(), "ellipse".to_string()]; + window.ctx.data_mut(|d| d.insert_temp(egui::Id::unique("flyout-tools"), tools)); + } + "drawer" => window.app.ui.tools_drawer = true, + _ => { + let nodes = window.frame(vec![]); + window.click(button_at(&nodes, "Object")); + } + } + window.frame(vec![]); + let open = |w: &Window| w.app.ui.flyout.is_some() || w.app.ui.tools_drawer || egui::Popup::is_any_open(&w.ctx); + assert!(open(&window), "the {overlay} is open"); + menus::invoke(&mut window.app, "object.move", json!({})); + assert!(window.app.ui.dialog.is_some(), "Move… opens its dialog: {}", window.app.ui.status); + window.frame(vec![]); + open(&window) + } + + /// #7906: a dialog that opens without a press closes a tool group's flyout. + #[test] + fn a_dialog_opened_without_a_press_closes_a_flyout() { + assert!(!overlay_open_after_a_dialog_opens("flyout"), "the dialog closes the flyout"); + } + + /// #7906: a dialog that opens without a press closes the All Tools drawer. + #[test] + fn a_dialog_opened_without_a_press_closes_the_tools_drawer() { + assert!(!overlay_open_after_a_dialog_opens("drawer"), "the dialog closes the drawer"); + } + + /// #7906: a dialog that opens without a press closes an open menu. + #[test] + fn a_dialog_opened_without_a_press_closes_a_menu() { + assert!(!overlay_open_after_a_dialog_opens("menu"), "the dialog closes the menu"); + } + + /// The palette opened in the pass after a dialog closes stays open, and the next dialog to open, + /// one pass later, closes it. + #[test] + fn the_palette_opened_as_a_dialog_closes_stays_open_until_the_next_dialog() { + let mut window = Window::new(); + menus::invoke(&mut window.app, "object.move", json!({})); + assert!(window.app.ui.dialog.is_some(), "Move… opens its dialog: {}", window.app.ui.status); + window.frame(vec![]); + window.frame(vec![]); + crate::dialogs::cancel(&mut window.app); + window.app.ui.palette_open = true; + window.frame(vec![]); + assert!(window.app.ui.palette_open, "the palette stays open"); + menus::invoke(&mut window.app, "object.move", json!({})); + assert!(window.app.ui.dialog.is_some(), "Move… opens its dialog again: {}", window.app.ui.status); + window.frame(vec![]); + assert!(!window.app.ui.palette_open, "the next dialog closes the palette"); + } + /// A click on another control outside the popup closes the popup and does not press the /// control. #[test] @@ -2585,7 +3145,7 @@ mod tests { let listed: Vec<_> = matching(&entries, "show panel").into_iter().take(MAX_RESULTS).collect(); let hidden = |e: &&&Entry| e.id.strip_prefix("panel:").is_some_and(|p| !crate::panel_docking::showing(&window.app.ui, p)); let e = listed.iter().find(hidden).expect("a hidden panel's result"); - let label = row_label(e); + let label = row_label(e, &home_text(&window.app, e)); let row = rows(&nodes).into_iter().find(|r| r.0 == label).expect("its row is drawn"); let panel = e.id.strip_prefix("panel:").unwrap_or_default().to_string(); window.click(egui::pos2(window.popup().center().x, ((row.2 + row.3) / 2.0) as f32)); @@ -2673,7 +3233,7 @@ mod tests { assert!(plugin.is_some_and(|p| p < MAX_RESULTS), "the plug-in is shown: {plugin:?}"); assert_eq!(ranked.iter().position(|e| e.id == id), Some(MAX_RESULTS), "the plug-in pushed the highlight past the limit"); assert_eq!((sel, &now), (MAX_RESULTS - 1, &id), "the highlight stays on its result, in the last row"); - let label = row_label(ranked[MAX_RESULTS]); + let label = row_label(ranked[MAX_RESULTS], &home_text(&open.app, ranked[MAX_RESULTS])); assert!(rows(&nodes).iter().any(|r| r.1 && r.0 == label), "its row is drawn and highlighted"); assert_eq!(field_description(&nodes), format!("{} of {}: {label}", MAX_RESULTS + 1, ranked.len())); } diff --git a/crates/ui-egui/src/palette/search.rs b/crates/ui-egui/src/palette/search.rs index a2bc113d4a..d87cf4c182 100644 --- a/crates/ui-egui/src/palette/search.rs +++ b/crates/ui-egui/src/palette/search.rs @@ -10,21 +10,50 @@ use crate::menus; /// and the exact tiers read the whole query. const INDEX_CHARS: usize = 200; -/// The field of a result a word comes from, best first. +/// The field of a result a word comes from, best first, and the fields of the English stem forms +/// ([`stems`]) of the words of the label, the menu path and the description ([`description`]). const LABEL: u8 = 0; const PATH: u8 = 1; const ID: u8 = 2; +const LABEL_STEMMED: u8 = 3; +const PATH_STEMMED: u8 = 4; +const DESCRIPTION: u8 = 5; +const DESCRIPTION_STEMMED: u8 = 6; /// A word's grade in a result, best first: a whole word of the label, a word of the label it -/// starts, a word of the menu path it is or starts, a word of the id it is or starts, or text -/// inside a word of any field ([`super::matching`]'s substring rule). -const LABEL_WORD: u8 = 1; -const LABEL_PREFIX: u8 = 2; -const PATH_WORD: u8 = 3; -const ID_WORD: u8 = 4; -const SUBSTRING: u8 = 5; +/// shares an English stem form with ("outlines" and Outline), a word of the label it starts, a +/// word of the label with the same meaning ([`super::words`]), a word of the menu path it is, +/// shares a stem form with or starts, a word of the menu path with the same meaning, a word of the +/// id it is or starts, text inside a word of any field ([`super::matching`]'s substring rule), a +/// word of the description it is, shares a stem form with, starts or means the same as, a word of +/// the label a typo away from it ([`Index::typos`]), or a word of the menu path a typo away. A word +/// of the description comes after the substring rule, so every result the substring rule finds +/// ranks above a result found only by its description. The grades without a stem or a word with +/// the same meaning are twice the values they had before those were added, so results matched +/// without them keep their order by the sum of the grades. +const LABEL_WORD: u8 = 2; +const LABEL_STEM: u8 = 3; +const LABEL_PREFIX: u8 = 4; +const LABEL_SYNONYM: u8 = 5; +const PATH_WORD: u8 = 6; +const PATH_SYNONYM: u8 = 7; +const ID_WORD: u8 = 8; +const SUBSTRING: u8 = 10; +const DESCRIPTION_WORD: u8 = 11; +const LABEL_TYPO: u8 = 12; +const PATH_TYPO: u8 = 14; const NONE: u8 = u8::MAX; +/// The most characters of a command's description the index reads (VectorCraft's own limit). +const DESCRIPTION_CHARS: usize = 300; + +/// The words of a description the index leaves out, besides words of 2 characters or fewer and +/// words with no letter. +const STOP_WORDS: &[&str] = &["the", "and", "ids", "true", "false", "null"]; + +/// The most words a query word with a typo meets ([`Index::typos`]), nearest first. +const TYPO_TERMS: usize = 32; + /// How a whole query matches a result, best first: it is the result's id, it is a label, a label /// starts with it, or it is the initials of a label. const EXACT_ID: u8 = 0; @@ -34,7 +63,7 @@ const INITIALS: u8 = 3; const NO_PHRASE: u8 = 4; /// One result in the list of a term: the result's place in the catalog and the field the term is -/// a word of. +/// a word or a word's stem form of. #[derive(Clone, Copy)] struct Posting { entry: u16, @@ -55,6 +84,38 @@ pub(crate) struct Index { initials_text: String, /// Each result's offset and length in `initials_text`. initials: Vec<(u32, u16)>, + /// Each word of a group of words with the same meaning ([`super::words::GROUPS`], and the + /// words the UI language's catalog adds), with the group's place in the table. + synonyms: HashMap, u16>, +} + +/// Is `w` one word as the index splits text ([`words`])? +pub(crate) fn is_one_word(w: &str) -> bool { + let mut it = words(w); + it.next() == Some(w) && it.next().is_none() +} + +/// The words of each group of [`super::words::GROUPS`], with the words `search_row` gives for the +/// group's catalog row ([`super::words::row_key`]) in the UI language. A word the catalog gives +/// that is not a single word, or that is already a word of a group, is left out. +fn synonym_groups(search_row: impl Fn(&str) -> Option) -> HashMap, u16> { + let mut out: HashMap, u16> = HashMap::new(); + let groups = super::words::GROUPS.iter().enumerate().filter_map(|(g, words)| u16::try_from(g).ok().map(|g| (g, words))); + for (g, words) in groups.clone() { + for &w in *words { + out.insert(w.into(), g); + } + } + for (g, words) in groups { + let Some(text) = search_row(&super::words::row_key(words)) else { continue }; + for (w, single) in super::words::row_words(&text) { + if single { + out.entry(w.into()).or_insert(g); + } + } + } + out.shrink_to_fit(); + out } /// Splits `text` into lowercase words at whitespace and at `.`, `-`, `/`, `(`, `)`, `…`, `›`, `,` @@ -73,6 +134,144 @@ fn initials_of(label: &str) -> String { .collect() } +/// The English stem forms of the lowercased `word`, at most two, and none for a word that is not +/// plain English letters. `'s` is dropped; `sses` becomes `ss`; `es` after `s`, `x`, `z`, `ch` or +/// `sh` is dropped, and with only its `s` dropped the word is a second form (`boxes`, `box` and +/// `boxe`; `rasterizes`, `rasteriz` and `rasterize`); in a word of more than 5 letters, `ies` +/// becomes `y` or `ie` (`copies`, `copy` and `copie`; `movies`, `movy` and `movie`); `ing` (more +/// than 5 letters) and `ed` (more than 4) are dropped, and when a doubled `b`, `d`, `g`, `m`, `n`, +/// `p`, `r` or `t` is left before them, the rest with that letter made single and the rest as it +/// is are the forms (`cutting`, `cut` and `cutt`), the single one only when it keeps at least 3 +/// letters (`added`, `add` alone); otherwise the rest and the rest followed by `e` are the forms +/// (`scaling`, `scal` and `scale`); a final `s` is dropped from a word of more than 3 letters that +/// does not end in `ss`, `us` or `is`. `series` and `species` have none. +fn stems(word: &str) -> Vec { + let one = |rest: &str| if rest.is_empty() { vec![] } else { vec![rest.to_string()] }; + if !word.bytes().all(|b| b.is_ascii_lowercase() || b == b'\'') || matches!(word, "series" | "species") { + return vec![]; + } + let n = word.len(); + if let Some(rest) = word.strip_suffix("'s") { + return one(rest); + } + if let Some(rest) = word.strip_suffix("sses") { + return vec![format!("{rest}ss")]; + } + if let Some(rest) = word.strip_suffix("es") + && ["s", "x", "z", "ch", "sh"].iter().any(|end| rest.ends_with(end)) + { + return vec![rest.to_string(), format!("{rest}e")]; + } + if n > 5 + && let Some(rest) = word.strip_suffix("ies") + { + return vec![format!("{rest}y"), format!("{rest}ie")]; + } + let verb = if n > 5 { word.strip_suffix("ing") } else { None }.or_else(|| if n > 4 { word.strip_suffix("ed") } else { None }); + if let Some(rest) = verb { + if let [.., a, b] = rest.as_bytes() + && a == b + && b"bdgmnprt".contains(a) + { + let single = rest.get(..rest.len() - 1).unwrap_or_default(); + if single.len() < 3 { + return vec![rest.to_string()]; + } + return vec![single.to_string(), rest.to_string()]; + } + return vec![rest.to_string(), format!("{rest}e")]; + } + if n > 3 && word.ends_with('s') && !["ss", "us", "is"].iter().any(|end| word.ends_with(end)) { + return one(word.get(..n - 1).unwrap_or_default()); + } + vec![] +} + +/// Is `c` a letter of a script written without spaces between words (Han, kana or Hangul)? +fn spaceless(c: char) -> bool { + matches!( + u32::from(c), + 0x1100..=0x11FF + | 0x3040..=0x30FF + | 0x3130..=0x318F + | 0x31F0..=0x31FF + | 0x3400..=0x4DBF + | 0x4E00..=0x9FFF + | 0xA960..=0xA97F + | 0xAC00..=0xD7FF + | 0xF900..=0xFAFF + | 0xFF66..=0xFFDC + | 0x20000..=0x323AF + ) +} + +/// The most edits a query word may be away from a word it meets as a typo: 1 for a word of 4 to 7 +/// characters, 2 for a longer one, and none for a shorter word or one with letters of a script +/// written without spaces ([`spaceless`]). +fn typo_bound(word: &str) -> Option { + if word.chars().any(spaceless) { + return None; + } + match word.chars().count() { + 0..=3 => None, + 4..=7 => Some(1), + _ => Some(2), + } +} + +/// The number of edits between `a` and `b` when it is at most `bound`: a character inserted, +/// removed or changed, or two adjacent characters swapped (`gruop` and `group`), each count as one. +/// The count stops as soon as every way of lining the two up needs more than `bound`. +fn edits_within(a: &[char], b: &[char], bound: usize) -> Option { + if a.len().abs_diff(b.len()) > bound { + return None; + } + let at = |row: &[usize], j: usize| row.get(j).copied().unwrap_or(usize::MAX); + // The edits between the first i characters of `a` and the first j of `b`, for the rows i - 2, + // i - 1 and i. + let mut before: Vec = vec![0; b.len() + 1]; + let mut last: Vec = (0..=b.len()).collect(); + let mut row: Vec = vec![0; b.len() + 1]; + for (i, &ca) in a.iter().enumerate() { + if let Some(first) = row.first_mut() { + *first = i + 1; + } + for (j, &cb) in b.iter().enumerate() { + let changed = at(&last, j).saturating_add(usize::from(ca != cb)); + let removed = at(&last, j + 1).saturating_add(1); + let inserted = at(&row, j).saturating_add(1); + let mut edits = changed.min(removed).min(inserted); + let swapped = i.checked_sub(1).and_then(|k| a.get(k)).zip(j.checked_sub(1).and_then(|k| b.get(k))); + if let Some((&pa, &pb)) = swapped + && pa == cb + && pb == ca + { + edits = edits.min(at(&before, j - 1).saturating_add(1)); + } + if let Some(cell) = row.get_mut(j + 1) { + *cell = edits; + } + } + if row.iter().all(|&e| e > bound) { + return None; + } + std::mem::swap(&mut before, &mut last); + std::mem::swap(&mut last, &mut row); + } + last.last().copied().filter(|&e| e <= bound) +} + +/// Adds each word of `text` to `found` for result `entry` in `field`, and with `stemmed`, each +/// word's English stem forms in that field. +fn add_words(found: &mut Vec<(String, u16, u8)>, text: &str, entry: u16, field: u8, stemmed: Option) { + for w in words(text) { + found.push((w.to_string(), entry, field)); + if let Some(stemmed) = stemmed { + found.extend(stems(w).into_iter().map(|s| (s, entry, stemmed))); + } + } +} + /// A name's last `›`-separated part (the label) and the parts before it (the menu path). fn split_name(name: &str) -> (&str, &str) { match name.rsplit_once(" › ") { @@ -81,6 +280,50 @@ fn split_name(name: &str) -> (&str, &str) { } } +/// A command's description, read from its params text: the text without each `{…}` group that is +/// not inside a `{`, `[` or `(` group (braces inside double quotes are text), without each such +/// `[…]` or `(…)` group just after a `→`, and without the `→` just before a removed group, with +/// each run of whitespace made one space and cut to its first [`DESCRIPTION_CHARS`] characters at +/// the end of a word. A group that is never closed stays in the text, and so does a result written +/// as words after a `→`. Params text that is only a group has an empty description. +pub(crate) fn description(params: &str) -> String { + let mut out = String::new(); + // The end of the text copied to `out`, and whether a removed group is open. + let (mut copied, mut open) = (0, false); + for (i, ch, depth) in crate::shortcut_editor::outside_quotes(params) { + let before = params.get(copied..i).unwrap_or_default(); + match ch { + '{' | '[' | '(' if depth == 0 && (ch == '{' || before.trim_end().ends_with('→')) => { + out.push_str(before); + (copied, open) = (i, true); + } + '}' | ']' | ')' if depth == 1 && open => { + let kept = out.trim_end().strip_suffix('→').unwrap_or(&out).len(); + out.truncate(kept); + out.push(' '); + (copied, open) = (i + ch.len_utf8(), false); + } + _ => {} + } + } + out.push_str(params.get(copied..).unwrap_or_default()); + let text = out.split_whitespace().collect::>().join(" "); + // A cut inside a word drops the rest of that word, so no part of a word is read as a word. + let Some((head, rest)) = text.char_indices().nth(DESCRIPTION_CHARS).and_then(|(end, _)| text.split_at_checked(end)) else { return text }; + let head = if rest.starts_with(' ') { head } else { head.rsplit_once(' ').map_or("", |(kept, _)| kept) }; + head.trim_end().to_string() +} + +/// The lowercase words of the lowercased `description` the index holds: split at every character +/// that is not a letter, a digit or an apostrophe, without apostrophes at either end, and leaving +/// out words of 2 characters or fewer, words with no letter and [`STOP_WORDS`]. +fn description_words(description: &str) -> impl Iterator { + description + .split(|c: char| !(c.is_alphanumeric() || c == '\'')) + .map(|w| w.trim_matches('\'')) + .filter(|w| w.chars().count() > 2 && w.chars().any(char::is_alphabetic) && !STOP_WORDS.contains(w)) +} + /// `name` without the id that follows it when the result shows its id. fn without_id<'a>(name: &'a str, id: &str) -> &'a str { name.strip_suffix(')').and_then(|n| n.strip_suffix(id)).and_then(|n| n.strip_suffix(" (")).unwrap_or(name) @@ -99,10 +342,14 @@ fn ids(e: &Entry) -> impl Iterator { impl Index { /// The index of `entries`, whose menu homes and menu items read `homes` in the UI language. The - /// words of a result's menu home and of its menu item's label count as menu path words. A - /// catalog with more results than a posting can name gets an empty index, and queries match by - /// the substring rule alone. - pub(crate) fn build(entries: &[Entry], homes: &[Option]) -> Index { + /// words of a result's menu home and of its menu item's label count as menu path words. The + /// words of the English names, menu home and menu item label also add their English stem forms + /// ([`stems`]); words in the UI language do not. `params` gives each result's params text, whose + /// [`description`] adds its words ([`description_words`]) and their stem forms; only the words + /// are kept. `search_row` gives the UI language's words for a group of words with the same + /// meaning ([`synonym_groups`]). A catalog with more results than a posting can name gets an + /// empty index, and queries match by the substring rule alone. + pub(crate) fn build(entries: &[Entry], homes: &[Option], params: &[&str], search_row: impl Fn(&str) -> Option) -> Index { if entries.len() > usize::from(u16::MAX) { return Index::default(); } @@ -114,10 +361,13 @@ impl Index { let id = ids(e).next().unwrap_or_default(); let start = initials_text.len(); let mut seen_initials: Vec = vec![]; - for name in names(e) { + // The first two names are English, so their words also give stem forms; the shown name + // may be in another language, and its words are indexed as they are. + for (n, name) in names(e).enumerate() { + let english = n < 2; let (label, path) = split_name(without_id(name, id)); - found.extend(words(label).map(|w| (w.to_string(), entry, LABEL))); - found.extend(words(path).map(|w| (w.to_string(), entry, PATH))); + add_words(&mut found, label, entry, LABEL, english.then_some(LABEL_STEMMED)); + add_words(&mut found, path, entry, PATH, english.then_some(PATH_STEMMED)); let ini = initials_of(label); if ini.chars().count() >= 2 && !seen_initials.contains(&ini) { if !seen_initials.is_empty() { @@ -127,18 +377,27 @@ impl Index { seen_initials.push(ini); } } - for home in [e.home.as_deref(), Some(e.menu_item), homes.get(i).and_then(Option::as_deref)].into_iter().flatten() { - found.extend(words(&home.to_lowercase()).map(|w| (w.to_string(), entry, PATH))); + for home in [e.home.as_deref(), Some(e.menu_item)].into_iter().flatten() { + add_words(&mut found, &home.to_lowercase(), entry, PATH, Some(PATH_STEMMED)); + } + if let Some(home) = homes.get(i).and_then(Option::as_deref) { + add_words(&mut found, &home.to_lowercase(), entry, PATH, None); } for id in ids(e) { found.extend(words(id).map(|w| (w.to_string(), entry, ID))); } + if let Some(text) = params.get(i).filter(|p| !p.is_empty()) { + for w in description_words(&description(text).to_lowercase()) { + found.push((w.to_string(), entry, DESCRIPTION)); + found.extend(stems(w).into_iter().map(|s| (s, entry, DESCRIPTION_STEMMED))); + } + } let len = u16::try_from(initials_text.len() - start).unwrap_or(0); initials.push((u32::try_from(start).unwrap_or(0), len)); } found.sort_unstable(); found.dedup(); - let mut index = Index { initials_text, initials, ..Index::default() }; + let mut index = Index { initials_text, initials, synonyms: synonym_groups(search_row), ..Index::default() }; let mut last: Option<&str> = None; for (word, entry, field) in &found { if last != Some(word.as_str()) { @@ -175,6 +434,8 @@ impl Index { + self.postings.capacity() * std::mem::size_of::() + self.initials_text.capacity() + self.initials.capacity() * std::mem::size_of::<(u32, u16)>() + + self.synonyms.capacity() * (std::mem::size_of::<(Box, u16)>() + 1) + + self.synonyms.keys().map(|w| w.len()).sum::() } /// The text of the word at `(offset, len)` in `term_text`. @@ -183,10 +444,34 @@ impl Index { self.term_text.get(offset..offset + len as usize).unwrap_or_default() } - /// The best grade (1 to 4) `word` gets in each result, [`NONE`] where it is no word and starts - /// no word of the result. The words it starts are found by a binary search of the sorted words. + /// The postings of the word at place `t` in `terms`. + fn postings_of(&self, t: usize) -> &[Posting] { + let Some(&(begin, len)) = self.spans.get(t) else { return &[] }; + let (begin, len) = (begin as usize, len as usize); + self.postings.get(begin..begin + len).unwrap_or_default() + } + + /// The place of the word `text` in `terms`, found by a binary search. + fn find(&self, text: &str) -> Option { + self.terms.binary_search_by(|t| self.text(t).cmp(text)).ok() + } + + /// The best grade ([`LABEL_WORD`] to [`DESCRIPTION_WORD`], without [`SUBSTRING`]) `word` gets in + /// each result, [`NONE`] where it is no word, shares no English stem form with a word of the + /// label, menu path or description, means the same as none of them, and starts no word of the + /// result. The words it starts are found by a binary search of the sorted words; a stem form + /// matches only a word or stem form equal to it. fn grades(&self, word: &str, n: usize) -> Vec { let mut out = vec![NONE; n]; + let mut mark = |postings: &[Posting], grade: &dyn Fn(u8) -> Option| { + for p in postings { + if let Some(grade) = grade(p.field) + && let Some(g) = out.get_mut(usize::from(p.entry)) + { + *g = (*g).min(grade); + } + } + }; let start = self.terms.partition_point(|t| self.text(t) < word); for (t, at) in self.terms.iter().enumerate().skip(start) { let term = self.text(at); @@ -194,21 +479,118 @@ impl Index { break; } let whole = term == word; - let Some(&(begin, len)) = self.spans.get(t) else { continue }; - let (begin, len) = (begin as usize, len as usize); - for p in self.postings.get(begin..begin + len).unwrap_or_default() { + // A stem form is not a word of the result, so a query word that only starts it does + // not match. + mark(self.postings_of(t), &|field| match field { + LABEL if whole => Some(LABEL_WORD), + LABEL => Some(LABEL_PREFIX), + PATH => Some(PATH_WORD), + DESCRIPTION => Some(DESCRIPTION_WORD), + ID => Some(ID_WORD), + _ => None, + }); + } + // The word meets a stem form of a word of the result ("scale" and Scaling) when it is itself + // a word of some result's label, menu path, id or description, so a partly typed word + // ("scal") that only equals a stem form does not lift Scaling above Scale. A description is + // cut at the end of a word ([`description`]), so it holds no partly typed word. + if let Some(t) = self.find(word) + && self.postings_of(t).iter().any(|p| matches!(p.field, LABEL | PATH | ID | DESCRIPTION)) + { + mark(self.postings_of(t), &|field| match field { + LABEL_STEMMED => Some(LABEL_STEM), + PATH_STEMMED => Some(PATH_WORD), + DESCRIPTION_STEMMED => Some(DESCRIPTION_WORD), + _ => None, + }); + } + // A stem form of the word meets a word of the result or a stem form of one ("outlines" + // and Outline, "rotated" and Rotating). Ids are not stemmed. + for form in stems(word) { + let Some(t) = self.find(&form) else { continue }; + mark(self.postings_of(t), &|field| match field { + LABEL | LABEL_STEMMED => Some(LABEL_STEM), + PATH | PATH_STEMMED => Some(PATH_WORD), + DESCRIPTION | DESCRIPTION_STEMMED => Some(DESCRIPTION_WORD), + _ => None, + }); + } + // Each other word of the word's group of words with the same meaning ([`Index::synonyms_of`]) + // meets a word of the label, menu path or description, or a stem form of one, equal to it. + // Ids are not matched this way. + for t in self.synonyms_of(word) { + mark(self.postings_of(t), &|field| match field { + LABEL | LABEL_STEMMED => Some(LABEL_SYNONYM), + PATH | PATH_STEMMED => Some(PATH_SYNONYM), + DESCRIPTION | DESCRIPTION_STEMMED => Some(DESCRIPTION_WORD), + _ => None, + }); + } + out + } + + /// The other words of the group of words with the same meaning that `word`, or a stem form of + /// it, is in ("bg" and background, "flipped" and reflect), as places in `terms`; the words of the + /// group no result holds are left out. + fn synonyms_of(&self, word: &str) -> Vec { + let group = std::iter::once(word.to_string()).chain(stems(word)).find_map(|w| self.synonyms.get(w.as_str()).copied()); + let Some(group) = group else { return vec![] }; + let mut found: Vec = self.synonyms.iter().filter(|&(w, &g)| g == group && &**w != word).filter_map(|(w, _)| self.find(w)).collect(); + // The map's order changes from one build to the next; the words' order in `terms` does not. + found.sort_unstable(); + found + } + + /// The words of labels and menu paths that `word` is a typo of: within [`typo_bound`] edits of + /// it ([`edits_within`]), at most [`TYPO_TERMS`], nearest first, as places in `terms`. Ids and + /// words with letters of a script written without spaces ([`spaceless`]) are not compared. + fn typos(&self, word: &str) -> Vec { + let Some(bound) = typo_bound(word) else { return vec![] }; + let word: Vec = word.chars().collect(); + let mut term: Vec = vec![]; + let mut near: Vec<(usize, usize)> = vec![]; + for (t, at) in self.terms.iter().enumerate() { + let text = self.text(at); + if text.chars().count().abs_diff(word.len()) > bound || text.chars().any(spaceless) { + continue; + } + term.clear(); + term.extend(text.chars()); + if let Some(edits) = edits_within(&word, &term, bound) + && self.postings_of(t).iter().any(|p| matches!(p.field, LABEL | PATH)) + { + near.push((edits, t)); + } + } + near.sort_unstable(); + near.truncate(TYPO_TERMS); + near.into_iter().map(|(_, t)| t).collect() + } + + /// Gives each result a word of `near` ([`Index::typos`]) is a word of its label or menu path + /// [`LABEL_TYPO`] or [`PATH_TYPO`] in `grades`, where its grade is not better. A typo replaces + /// [`DESCRIPTION_WORD`], since a result found only by its description ranks below one found + /// through a typo ([`rank`]). + fn mark_typos(&self, near: &[usize], grades: &mut [u8]) { + for &t in near { + for p in self.postings_of(t) { let grade = match p.field { - LABEL if whole => LABEL_WORD, - LABEL => LABEL_PREFIX, - PATH => PATH_WORD, - _ => ID_WORD, + LABEL => LABEL_TYPO, + PATH => PATH_TYPO, + _ => continue, }; - if let Some(g) = out.get_mut(usize::from(p.entry)) { - *g = (*g).min(grade); + if let Some(g) = grades.get_mut(usize::from(p.entry)) { + *g = if *g == DESCRIPTION_WORD { grade } else { (*g).min(grade) }; } } } - out + } + + /// The text of the first word of `near` that is a word of result `i` in one of `fields` (its + /// label or its menu path, and their stem forms). + fn nearest_of(&self, near: &[usize], i: usize, fields: &[u8]) -> Option<&str> { + let t = near.iter().find(|&&t| self.postings_of(t).iter().any(|p| usize::from(p.entry) == i && fields.contains(&p.field)))?; + self.terms.get(*t).map(|at| self.text(at)) } /// Is `query` (no spaces) the initials of one of result `i`'s labels? @@ -260,17 +642,29 @@ fn phrase(e: &Entry, query: &str, initials: bool) -> u8 { NO_PHRASE } -/// What results are ordered by, compared field by field: how the whole query matches, the worst -/// grade a word gets, the sum of the grades, the kind of result and the label's length. -type RankKey = (u8, u8, u32, u8, usize); +/// What results are ordered by, compared field by field: whether a word matched only through a +/// description, whether a word matched only through a typo, how the whole query matches, the worst +/// grade a word gets, the sum of the grades, how the whole query matches when read with the words +/// of the same meaning it matched through, the kind of result and the label's length. +type RankKey = (bool, bool, u8, u8, u32, u8, u8, usize); /// The results of `entries` that the lowercased `query` matches, best first, as places in /// `entries`. A result matches when every word of the query is text in one of its names or ids /// (the rule the palette always had, so nothing it found is lost), when every word of the query is -/// or starts a word of its label, menu path or id, or when the query is the initials of a label -/// ("ea" for Export As…). Results are ordered by how the whole query matches ([`phrase`]), then by -/// the worst grade a word gets, the sum of the grades, the kind of result ([`kind`]), the label's -/// length and the catalog order. An empty query lists every result in catalog order. +/// or starts a word of its label, menu path, description ([`description`]) or id, shares an English +/// stem form with a word of its label, menu path or description ("rounded corners" for Round +/// Corners…) or means the same as a word of its label, menu path or description ("remove bg" for +/// Remove Background…), or when the query is the initials of a label ("ea" for Export As…). A query +/// word that is no word, stem form or word start of any result's label, menu path or id also +/// matches the words of labels and menu paths it is a typo of ([`Index::typos`]). +/// Results where a word matched only through a description come after every other result. Before +/// them, results where a word matched only through a typo come after every other result, and their +/// whole-query match is read with each such word replaced by the word it is a typo of ("gruop" as +/// "group"). Results are ordered by that, by how the whole query matches ([`phrase`]), then by the +/// worst grade a word gets, the sum of the grades, how the whole query matches when read with each +/// word matched through a word of the same meaning replaced by that word ("colour" as "color"), +/// the kind of result ([`kind`]), the label's length and the catalog order. An empty query lists +/// every result in catalog order. pub(crate) fn rank(entries: &[Entry], index: &Index, query: &str) -> Vec { let query = normalize(query); if query.is_empty() { @@ -279,8 +673,39 @@ pub(crate) fn rank(entries: &[Entry], index: &Index, query: &str) -> Vec { let spaced: Vec<&str> = query.split(' ').collect(); let head: String = query.chars().take(INDEX_CHARS).collect(); let tokens: Vec<&str> = words(&head).collect(); + // Where each word starts in the query (`head` is its start), for reading the query with a typo + // corrected. + let starts: Vec = tokens.iter().map(|t| (t.as_ptr() as usize).saturating_sub(head.as_ptr() as usize)).collect(); let n = entries.len(); - let indexed: Vec> = tokens.iter().map(|t| index.grades(t, n)).collect(); + let mut indexed: Vec> = Vec::with_capacity(tokens.len()); + let mut typos: Vec> = Vec::with_capacity(tokens.len()); + let mut meanings: Vec> = Vec::with_capacity(tokens.len()); + // After a word that is nothing in any result and a typo of nothing, a result is found only by + // the substring rule or its initials, where a typo grade changes nothing, so the later words are + // not compared. + let mut compare = true; + for (k, t) in tokens.iter().enumerate() { + // A repeated word is graded once. + if let Some(j) = tokens.iter().take(k).position(|u| u == t) + && let (Some(grades), Some(near), Some(same)) = (indexed.get(j).cloned(), typos.get(j).cloned(), meanings.get(j).cloned()) + { + indexed.push(grades); + typos.push(near); + meanings.push(same); + continue; + } + meanings.push(index.synonyms_of(t)); + let mut grades = index.grades(t, n); + // A word that matches only words of descriptions is still compared with the words of labels + // and menu paths it may be a typo of. + let near = if compare && grades.iter().all(|&g| g == NONE || g == DESCRIPTION_WORD) { index.typos(t) } else { vec![] }; + if near.is_empty() && grades.iter().all(|&g| g == NONE) { + compare = false; + } + index.mark_typos(&near, &mut grades); + indexed.push(grades); + typos.push(near); + } // The index reads only the start of a longer query, so such a query matches by the substring // rule, which reads all of it. let fits = query.chars().count() <= INDEX_CHARS; @@ -294,24 +719,80 @@ pub(crate) fn rank(entries: &[Entry], index: &Index, query: &str) -> Vec { // Each word's grade, the worst and their sum; with initials, every word counts as a word // the label starts, as the initials stand for every word of the label. let (mut all_indexed, mut worst, mut sum) = (fits && !tokens.is_empty(), 0u8, 0u32); - for (grades, token) in indexed.iter().zip(&tokens) { + // The query as read for the whole-query match, with each word matched only through a typo + // replaced by the word of this result it is a typo of; and as read with each word matched + // through a word with the same meaning replaced by that word too. + let (mut typo, mut corrected, mut copied) = (false, String::new(), 0); + let mut described = false; + let (mut synonym, mut meant, mut meant_copied) = (false, String::new(), 0); + let splice = |out: &mut String, copied: &mut usize, k: usize, token: &str, word: &str| { + if let Some(&start) = starts.get(k) + && let Some(between) = query.get(*copied..start) + { + out.push_str(between); + out.push_str(word); + *copied = start + token.len(); + } + }; + for (k, (grades, token)) in indexed.iter().zip(&tokens).enumerate() { let mut g = grades.get(i).copied().unwrap_or(NONE); if g == NONE { all_indexed = false; - if e.haystack.contains(token) { - g = SUBSTRING; + } + if g > SUBSTRING && e.haystack.contains(token) { + g = SUBSTRING; + } + let g = if initials { + g.min(LABEL_PREFIX) + } else if g == NONE { + SUBSTRING + } else { + g + }; + described |= g == DESCRIPTION_WORD; + let field = match g { + LABEL_TYPO => Some(LABEL), + PATH_TYPO => Some(PATH), + _ => None, + }; + if let Some(field) = field { + typo = true; + if let Some(near) = typos.get(k).and_then(|near| index.nearest_of(near, i, &[field])) { + splice(&mut corrected, &mut copied, k, token, near); + splice(&mut meant, &mut meant_copied, k, token, near); + } + } + let fields: &[u8] = match g { + LABEL_SYNONYM => &[LABEL, LABEL_STEMMED], + PATH_SYNONYM => &[PATH, PATH_STEMMED], + _ => &[], + }; + if !fields.is_empty() { + synonym = true; + if let Some(same) = meanings.get(k).and_then(|same| index.nearest_of(same, i, fields)) { + splice(&mut meant, &mut meant_copied, k, token, same); } } - let g = if initials { g.min(LABEL_PREFIX) } else { g.min(SUBSTRING) }; worst = worst.max(g); sum += u32::from(g); } if !(substring || all_indexed || initials) { continue; } - let tier = phrase(e, &query, initials); + let tier = if typo { + corrected.push_str(query.get(copied..).unwrap_or_default()); + phrase(e, &corrected, false) + } else { + phrase(e, &query, initials) + }; + let meant_tier = if synonym { + meant.push_str(query.get(meant_copied..).unwrap_or_default()); + phrase(e, &meant, false) + } else { + tier + }; let length = split_name(&e.shown).0.chars().count(); - ranked.push(((tier, worst, sum, e.kind, length), place)); + ranked.push(((described, typo, tier, worst, sum, meant_tier, e.kind, length), place)); } ranked.sort_by_key(|&(key, place)| (key, place)); ranked.into_iter().map(|(_, place)| place).collect() @@ -340,6 +821,10 @@ pub(crate) fn menu_homes(native: bool) -> HashMap { out.entry(key(id, p)).or_insert_with(|| (path.join(" › "), *label)); + // Window › Learn runs `window.learn`, which is a result of its own too. + if *id == "window.learn" { + out.entry((*id).to_string()).or_insert_with(|| (path.join(" › "), *label)); + } } menus::Item::Sub(name, children) => { path.push(name); @@ -390,12 +875,19 @@ mod tests { kind: kind(id, home.as_deref()), home, menu_item: "", + label_at: 0, + names_item: false, } } /// `entries` with their index. fn synthetic(entries: Vec) -> Catalog { - let index = Index::build(&entries, &[]); + described(entries, &[]) + } + + /// `entries` with their index, the params text of each in `params`. + fn described(entries: Vec, params: &[&str]) -> Catalog { + let index = Index::build(&entries, &[], params, |_| None); Catalog { list: entries, index, ranked: std::sync::Mutex::new(None) } } @@ -412,8 +904,13 @@ mod tests { for (query, better, worse) in [ // A whole word of the label, then a word of the label it starts. ("cut zz", entry("Zz Cut", "a.one"), entry("Zz Cutter", "b.two")), + // A whole word of the label, then a word of the label it shares a stem form with. + ("scale zz", entry("Zz Scale", "a.one"), entry("Zz Scaling", "b.two")), + // A word of the label it shares a stem form with, then a word of the label it starts. + // The id makes "scale" a word of the catalog. + ("scale zz", entry("Zz Scaling", "a.one"), entry("Zz Scalers", "scale.two")), // A word of the label it starts, then a word of the menu path. - ("fill zz", entry("Zz Filling", "a.one"), entry("Fill › Zz Other", "b.two")), + ("fill zz", entry("Zz Fillet", "a.one"), entry("Fill › Zz Other", "b.two")), // A word of the menu path, then a word of the id. ("zap zz", entry("Zap › Zz One", "a.one"), entry("Zz Two", "zap.two")), // A word of the id, then text inside a word. @@ -426,6 +923,38 @@ mod tests { } } + /// A partly typed word that equals only a stem form ("scal" of Scaling, "spac" of Spacing) is a + /// word the query starts in both results, so the shorter label stays first. + #[test] + fn a_partly_typed_word_does_not_lift_a_verb_form() { + for (query, base, form) in [("scal zz", "Zz Scale", "Zz Scaling"), ("spac zz", "Zz Space", "Zz Spacing"), ("ad zz", "Zz Add", "Zz Added")] { + let c = synthetic(vec![entry(form, "a.one"), entry(base, "b.two")]); + assert_eq!(ranked(&c, query), ["b.two", "a.one"], "{query}"); + } + } + + /// How the whole query matches comes before the word grades, so a stem form ranks above a word + /// the query starts only among results in the same whole-query tier: "scale" lists Scale, then + /// Scalers, which starts with the query, then Scaling, and "scale zz" lists Zz Scaling above Zz + /// Scalers. + #[test] + fn a_whole_query_tier_comes_before_a_stem_form() { + let c = synthetic(vec![entry("Scaling", "c.three"), entry("Scalers", "b.two"), entry("Scale", "a.one")]); + assert_eq!(ranked(&c, "scale"), ["a.one", "b.two", "c.three"]); + let c = synthetic(vec![entry("Zz Scalers", "b.two"), entry("Zz Scaling", "a.one"), entry("Zz Scale", "c.three")]); + assert_eq!(ranked(&c, "scale zz"), ["c.three", "a.one", "b.two"]); + } + + /// Results that no stem form matches keep the order they had before stems were added: two + /// results whose grades summed the same still tie on the sum, and the shorter label comes + /// first. + #[test] + fn results_matched_without_a_stem_keep_their_order() { + // Two label prefixes and a menu path word, against a label word and two menu path words. + let c = synthetic(vec![entry("Bet › Gam › Alp Zzzzzzzzzz", "b.two"), entry("Gam › Alpx Betx", "a.one")]); + assert_eq!(ranked(&c, "alp bet gam"), ["a.one", "b.two"]); + } + /// For each pair of adjacent whole-query tiers, a result in the better tier ranks above one in /// the worse. #[test] @@ -476,6 +1005,370 @@ mod tests { } } + /// Do `a` and `b` share a form, each taken as it is or as one of its stem forms? + fn meet(a: &str, b: &str) -> bool { + let forms = |w: &str| std::iter::once(w.to_string()).chain(stems(w)).collect::>(); + let b = forms(b); + forms(a).iter().any(|f| b.contains(f)) + } + + /// English plurals and verb forms meet their base word, and words that only look alike do not. + #[test] + fn plurals_and_verb_forms_meet_their_base_word() { + for (a, b) in [ + ("outlines", "outline"), + ("rounded", "round"), + ("paths", "path"), + ("cutting", "cut"), + ("scaling", "scale"), + ("rotated", "rotate"), + ("spacing", "space"), + ("tracing", "trace"), + ("curved", "curve"), + ("filled", "fill"), + ("missing", "missing"), + ("boxes", "box"), + ("brushes", "brush"), + ("glasses", "glass"), + ("copies", "copy"), + ("movies", "movie"), + ("artist's", "artist"), + ("rotated", "rotating"), + ("added", "add"), + ("rasterizes", "rasterize"), + ("sizes", "size"), + ] { + assert!(meet(a, b), "{a} meets {b}"); + } + for (a, b) in [("series", "sery"), ("missing", "mis"), ("press", "pres"), ("bus", "bu"), ("axis", "axi"), ("cutting", "cu"), ("added", "ad")] + { + assert!(!meet(a, b), "{a} does not meet {b}"); + } + for w in ["outlines", "scaling", "cutting", "copies", "s", "'s", "ed", "ing", "übers", "群組", "series"] { + assert!(stems(w).len() <= 2, "{w}"); + assert!(stems(w).iter().all(|s| !s.is_empty() && s != w), "{w}: {:?}", stems(w)); + } + assert!(stems("übers").is_empty() && stems("series").is_empty() && stems("species").is_empty()); + } + + /// A query word in a plural or verb form finds a result whose label or menu path holds the base + /// word, below one that holds the word itself, and the words of a name shown in another language + /// are not stemmed. + #[test] + fn a_plural_or_verb_form_finds_the_result() { + let c = synthetic(vec![entry("Zz Rotate", "a.one"), entry("Spacing › Zz Other", "b.two"), entry("Zz Rotated", "c.three")]); + assert_eq!(ranked(&c, "rotating"), ["a.one", "c.three"]); + assert_eq!(ranked(&c, "rotated"), ["c.three", "a.one"]); + assert_eq!(ranked(&c, "spaces other"), ["b.two"], "through the menu path"); + let shown = Entry { shown: "Zz Trees".into(), haystack: "zz one\nzz one\nzz trees\na.one".into(), ..entry("Zz One", "a.one") }; + let c = synthetic(vec![shown, entry("Zz Trees", "b.two")]); + assert_eq!(ranked(&c, "treed zz"), ["b.two"], "only the English name is stemmed"); + let en = catalog(Lang::EN, false); + assert!(place(&en, "outlines", "type.createOutlines").is_some_and(|p| p < 3)); + assert_eq!(ranked(&en, "rounded corners").first().map(String::as_str), Some("effect:stylize.roundCorners")); + for (q, id) in [ + ("scaling", "object.scale"), + ("rotated", "object.rotate"), + ("rasterizes", "object.rasterize"), + ("added anchor points", "object.path.addAnchorPoints"), + ] { + assert!(place(&en, q, id).is_some(), "{q} finds {id}"); + } + } + + /// Edits are counted up to a bound: a changed, inserted or removed character, or two adjacent + /// characters swapped, is one edit, and words further apart than the bound give none. + #[test] + fn edits_are_counted_up_to_a_bound() { + let edits = |a: &str, b: &str, bound: usize| edits_within(&a.chars().collect::>(), &b.chars().collect::>(), bound); + for (a, b, bound, expected) in [ + ("group", "group", 1, Some(0)), + ("gruop", "group", 1, Some(1)), + ("elipse", "ellipse", 1, Some(1)), + ("rectange", "rectangle", 2, Some(1)), + ("eyedroper", "eyedropper", 2, Some(1)), + ("recktanglee", "rectangle", 2, Some(2)), + ("grop", "group", 1, Some(1)), + ("grap", "group", 1, None), + ("ab", "abcd", 1, None), + ("ca", "abc", 2, None), + ("abcd", "wxyz", 2, None), + ("über", "uber", 1, Some(1)), + ("", "ab", 2, Some(2)), + ] { + assert_eq!(edits(a, b, bound), expected, "{a} {b}"); + assert_eq!(edits(b, a, bound), expected, "{b} {a}"); + } + assert_eq!(typo_bound("pen"), None); + assert_eq!(typo_bound("elip"), Some(1)); + assert_eq!(typo_bound("rectang"), Some(1)); + assert_eq!(typo_bound("rectange"), Some(2)); + for w in ["群組群組", "かなかなか", "한국어단어", "zz群組"] { + assert_eq!(typo_bound(w), None, "{w}"); + } + } + + /// A query word with a typo finds a result whose label or menu path holds the word, below every + /// result matched without a typo, and a word that is a word or a word start of some result, a + /// word of fewer than 4 letters, an id and a word of a script written without spaces get no + /// typo matches. + #[test] + fn a_word_with_a_typo_finds_the_result() { + let c = synthetic(vec![entry("Zz Group", "a.one"), entry("Zz Cut", "b.two"), entry("Zz Rectangle", "c.three")]); + assert_eq!(ranked(&c, "gruop"), ["a.one"], "two letters swapped"); + assert_eq!(ranked(&c, "gruop zz"), ["a.one"]); + assert_eq!(ranked(&c, "cutx"), ["b.two"]); + assert!(ranked(&c, "cux").is_empty(), "3 letters"); + assert_eq!(ranked(&c, "recktanglee"), ["c.three"], "two edits in a longer word"); + assert!(ranked(&c, "rectanglexxx").is_empty()); + // Below a result whose name holds the word as text, and below one that holds it whole. + let c = synthetic(vec![entry("Zz Color", "a.one"), entry("Zz Bcolrb", "b.two")]); + assert_eq!(ranked(&c, "colr"), ["b.two", "a.one"]); + let c = synthetic(vec![entry("Color", "a.one"), entry("Zz Bcolrb", "b.two")]); + assert_eq!(ranked(&c, "colr"), ["b.two", "a.one"], "also when the word spelled right is the label"); + let c = synthetic(vec![entry("Zz Color", "a.one"), entry("Zz Colr", "b.two")]); + assert_eq!(ranked(&c, "colr"), ["b.two"], "a word some result holds gets no typo matches"); + // A word of the label before a word of the menu path. + let c = synthetic(vec![entry("Color › Zz Other", "a.one"), entry("Zz Color", "b.two")]); + assert_eq!(ranked(&c, "colr"), ["b.two", "a.one"]); + // Ids and words of scripts written without spaces. + let c = synthetic(vec![entry("Zz One", "group.one"), entry("物件 › 群組群組", "b.two")]); + assert!(ranked(&c, "gruop").is_empty()); + assert!(ranked(&c, "群組群物").is_empty()); + // A word of Latin letters followed by Han letters, one edit from "abcd", is not compared. + let c = synthetic(vec![entry("Zz Abc群", "a.one")]); + assert!(ranked(&c, "abcd").is_empty()); + // The whole query is read with the word it is a typo of: "gruop" names Group as "group" does. + let c = synthetic(vec![entry("Group Selection Tool", "tool:groupSelection"), entry("Object › Group", "object.group")]); + assert_eq!(ranked(&c, "gruop"), ranked(&c, "group")); + assert_eq!(ranked(&c, "gruop").first().map(String::as_str), Some("object.group")); + // The rest of the query is read as typed, `›` included. + let c = synthetic(vec![entry("Object › Group Zz Tool", "tool:zz"), entry("Object › Group", "object.group")]); + assert_eq!(ranked(&c, "object › group"), ["object.group", "tool:zz"]); + assert_eq!(ranked(&c, "object › gruop"), ranked(&c, "object › group")); + // A label typo is read with the word of the label, even when a word of the menu path is + // nearer: "abcdefgh" reads as "abcdefyy" in the first, which is then its label. + let c = synthetic(vec![entry("Abcdefyy Zz", "tool:b"), entry("Abcdefgx › Abcdefyy", "a.one")]); + assert_eq!(ranked(&c, "abcdefgh"), ["a.one", "tool:b"]); + } + + /// A query word with a typo meets at most 32 words, the nearest first, and a long word with no + /// match finds nothing. + #[test] + fn a_typo_meets_at_most_32_words() { + // 35 words one edit from the query and one word two edits from it, which sorts before them. + let near = ('a'..='z').chain('0'..='9').filter(|&ch| ch != 'q'); + let mut entries: Vec = near.enumerate().map(|(i, ch)| entry(&format!("Abcdefg{ch}"), &format!("a.n{i}"))).collect(); + entries.insert(0, entry("Abcdeaxq", "far.one")); + let c = synthetic(entries); + let found = ranked(&c, "abcdefgq"); + assert_eq!(found.len(), 32, "{found:?}"); + assert!(!found.contains(&"far.one".to_string())); + let c = synthetic(vec![entry("Abcdeaxq", "far.one")]); + assert_eq!(ranked(&c, "abcdefgq"), ["far.one"], "two edits in a word of 8 letters"); + assert!(ranked(&c, &"q".repeat(30)).is_empty()); + } + + /// On the English results, misspelled words list first the commands the word spelled right + /// lists first by labels, menu paths and ids (a typo does not match descriptions), the tool among + /// the first four, and a word of 3 letters is not read as a typo. + #[test] + fn misspelled_words_find_the_command() { + let c = catalog(Lang::EN, false); + let first = |q: &str| ranked(&c, q).first().cloned().unwrap_or_default(); + assert_eq!(first("gruop"), "object.group"); + let plain = Index::build(&c.list, &[], &[], |_| None); + let id = |&i: &u32| c.list.get(i as usize).map(|e| e.id.clone()).unwrap_or_default(); + for (typo, word, tool) in [ + ("eyedroper", "eyedropper", "tool:eyedropper"), + ("rectange", "rectangle", "tool:rectangle"), + ("elipse", "ellipse", "tool:ellipse"), + ("gruop", "group", "tool:groupSelection"), + ] { + assert!(substring_rule(&c, typo).is_empty(), "{typo} matched nothing before"); + let top = |q: &str| ranked(&c, q).into_iter().take(4).collect::>(); + let spelled_right: Vec = rank(&c.list, &plain, word).iter().take(4).map(id).collect(); + assert_eq!(top(typo), spelled_right, "{typo}"); + assert!(place(&c, typo, tool).is_some_and(|p| p < 4), "{typo}: {:?}", ranked(&c, typo)); + } + assert_eq!(first("pen"), "tool:pen"); + assert!(place(&c, "pen", "file.open").is_some(), "Open… holds the text"); + } + + /// A query word finds a result whose label or menu path holds another word of its group of words + /// with the same meaning: below a result whose label holds the word itself, above one whose menu + /// path holds the word, and with a menu path word of the group last. A stem form of the query word + /// and of a result's word meet the group too; ids, word starts and words of no group do not. + #[test] + fn a_word_with_the_same_meaning_finds_the_result() { + let c = synthetic(vec![ + entry("Delete › Zz Path", "d.four"), + entry("Remove › Zz Other", "c.three"), + entry("Zz Delete", "a.one"), + entry("Zz Remove", "b.two"), + ]); + assert_eq!(ranked(&c, "remove"), ["b.two", "a.one", "c.three", "d.four"]); + assert!(ranked(&c, "remo zz").iter().all(|id| id != "a.one" && id != "d.four"), "a word start is not looked up"); + let c = synthetic(vec![entry("Zz Reflect…", "a.one"), entry("Zz Reflecting", "b.two"), entry("Zz One", "reflect.one")]); + assert_eq!(ranked(&c, "flipped zz"), ["a.one", "b.two"], "stem forms on both sides, and no id"); + let c = synthetic(vec![entry("Zz Unite", "a.one"), entry("Zz Merge", "b.two")]); + assert_eq!(ranked(&c, "merge"), ["b.two"], "merge is in no group"); + assert_eq!(ranked(&c, "combine"), ["a.one"]); + // Among results that match equally well, the whole query read with the word of the same + // meaning ("colour" as "color") puts the label Color first, but never above a label that + // holds the query word itself. + let c = synthetic(vec![entry("Zz Color", "tool:zz"), entry("Color", "panel:color"), entry("Zz Colour", "c.three")]); + assert_eq!(ranked(&c, "colour"), ["c.three", "panel:color", "tool:zz"]); + } + + /// A catalog row adds words in the UI language to a group, and a word that is not a single word + /// or that is a word of another group is left out. + #[test] + fn a_catalog_row_adds_words_to_a_group() { + let entries = || vec![entry("Zz Delete", "a.one")]; + let row = |key: &str| (key == "remove, delete, erase, clear").then(|| "Entfernen, ganz weg, text".to_string()); + let with = Catalog { list: entries(), index: Index::build(&entries(), &[], &[], row), ranked: std::sync::Mutex::new(None) }; + assert_eq!(ranked(&with, "entfernen"), ["a.one"]); + assert!(ranked(&with, "ganz weg").is_empty(), "two words are left out"); + assert!(ranked(&with, "text").is_empty(), "text stays in its own group"); + let without = synthetic(entries()); + assert!(ranked(&without, "entfernen").is_empty(), "only while the row's language is the UI language"); + } + + /// A description is the params text without the groups of its schema and result: one fixture + /// of each shape the params texts take. + #[test] + fn a_description_leaves_out_the_schema_and_the_result() { + for (params, expected) in [ + // A schema, prose and a result. + ("{a: 1, b?: bool (true)} make it so → {changed, ids}", "make it so"), + // A quoted brace inside a schema. + ("{sep: \"}\" or \"{\" (\"}\")} split the text", "split the text"), + // A schema only. + ("{radius: pt (10)}", ""), + // An empty schema, then prose with no arrow. + ("{} choose the Corner Tool", "choose the Corner Tool"), + // Prose after the result. + ("{from?: index} → {index}: moves the document", ": moves the document"), + // Nested braces and brackets. + ("{a: {b: 1}, c: [x, {y}]} trims the path", "trims the path"), + // Alternative schemas. + ("{id, dx} or {items: [{id}…], dx} move anchors", "or move anchors"), + // A result in brackets or parentheses, and a result written as words. + ("{} → [name…] for the active document", "for the active document"), + ("{id} → ({x, y}) its place", "its place"), + ("{id} → its id.", "→ its id."), + // A group inside parentheses is text, and so is a group that is never closed. + ("fits it (as {x} does) here", "fits it (as {x} does) here"), + ("{a: 1 never closed", "{a: 1 never closed"), + // No group at all. + ("plain words\n here", "plain words here"), + ("", ""), + ] { + assert_eq!(description(params), expected, "{params}"); + } + // A long description ends at the end of a word. + let cut = description(&"word ".repeat(100)); + assert!(cut.chars().count() <= DESCRIPTION_CHARS && cut.ends_with(" word"), "{cut}"); + let cut = description(&format!("{}handles", "abcd ".repeat(59))); + assert!(cut.chars().count() <= DESCRIPTION_CHARS && cut.ends_with(" abcd"), "{cut}"); + let whole = format!("{}handles", "abcd ".repeat(58)); + assert_eq!(description(&whole), whole); + assert!(description_words("the and ids true false null of a 16 10pt x").eq(["10pt"])); + assert!(description_words("image's 'quoted' png").eq(["image's", "quoted", "png"])); + } + + /// A word of a description finds the result as a whole word, a stem form, a word start or a word + /// with the same meaning, below a result that holds the word in its label or menu path or inside + /// a word. A schema's words, words left out of descriptions and typos do not find it. + #[test] + fn a_word_of_the_description_finds_the_result() { + let c = described( + vec![ + entry("Zz Alpha", "a.one"), + entry("Zz Background", "b.two"), + entry("Zz Underbackground", "c.three"), + entry("Background › Zz Delta", "d.four"), + ], + &["{corners?: bool (true)} make the background of the images transparent → {changed}", "", "", ""], + ); + assert_eq!(ranked(&c, "transparent"), ["a.one"]); + assert_eq!(ranked(&c, "making images"), ["a.one"], "stem forms"); + assert_eq!(ranked(&c, "transp"), ["a.one"], "a word start"); + assert_eq!(ranked(&c, "background"), ["b.two", "d.four", "c.three", "a.one"]); + assert_eq!(ranked(&c, "bg"), ["b.two", "d.four", "a.one"], "a word with the same meaning"); + assert_eq!(ranked(&c, "transparent background"), ["a.one"]); + assert!(ranked(&c, "corners").is_empty(), "a word of the schema"); + assert!(ranked(&c, "changed").is_empty(), "a word of the result"); + assert!(ranked(&c, "the").is_empty(), "a word left out"); + assert!(ranked(&c, "trasnparent").is_empty(), "a typo"); + assert!(synthetic(vec![entry("Zz Alpha", "a.one")]).index.find("transparent").is_none()); + } + + /// A result found only by its description ranks below a result found through a typo of a word + /// of its label: "centr" starts "centred" in a description and is a typo of "center". A result + /// matched both ways ranks as matched through the typo. + #[test] + fn a_description_match_ranks_below_a_typo() { + let c = described(vec![entry("Zz Beta", "b.two"), entry("Zz Center", "a.one")], &["{} keeps the art centred on the page", ""]); + assert_eq!(ranked(&c, "centr"), ["a.one", "b.two"]); + assert_eq!(ranked(&c, "zz centr"), ["a.one", "b.two"]); + let both = described(vec![entry("Zz Center", "a.one"), entry("Center", "c.three")], &["", "{} keeps the art centred on the page"]); + assert_eq!(ranked(&both, "centr"), ["c.three", "a.one"]); + } + + /// On the English results, words of what a command does find it: "transparent background" + /// lists Remove Background… near the top, and "png" lists it below every result with png in its + /// name or menu path, while a word of its schema alone ("corners") does not list it. + #[test] + fn words_of_a_description_find_the_command() { + let c = catalog(Lang::EN, false); + let remove = "addon.image.removeBackground"; + let text = super::super::params_texts(&c.list); + let at = c.list.iter().position(|e| e.id == remove).unwrap(); + assert!(description(text[at]).starts_with("make the background of each image transparent"), "{}", description(text[at])); + assert!(substring_rule(&c, "transparent background").len() < ranked(&c, "transparent background").len()); + assert!(place(&c, "transparent background", remove).is_some_and(|p| p < 3), "{:?}", ranked(&c, "transparent background")); + let png = ranked(&c, "png"); + let below = png.iter().position(|id| id == remove).unwrap(); + let named = |e: &Entry| names(e).chain(e.home.as_deref()).any(|n| n.to_lowercase().contains("png")); + let with_png: Vec = c.list.iter().filter(|e| named(e)).filter_map(|e| png.iter().position(|id| *id == e.id)).collect(); + assert!(!with_png.is_empty() && with_png.iter().all(|&p| p < below), "{png:?}"); + assert!(place(&c, "corners", remove).is_none()); + assert!(place(&c, "corners", "effect:stylize.roundCorners").is_some_and(|p| p < 3), "{:?}", ranked(&c, "corners")); + } + + /// On the English results, everyday words find commands whose names use another word, and a + /// result whose label holds a word with the same meaning as the query ranks above one that holds + /// the query only in its menu path. + #[test] + fn words_with_the_same_meaning_find_the_command() { + let c = catalog(Lang::EN, false); + let first = |q: &str| ranked(&c, q).first().cloned().unwrap_or_default(); + let within = |q: &str, id: &str, n: usize| place(&c, q, id).is_some_and(|p| p < n); + for q in ["remove bg", "outline text", "flip", "combine", "vectorize", "colour"] { + assert!(substring_rule(&c, q).len() < ranked(&c, q).len(), "{q} finds more than before"); + } + assert_eq!(first("remove bg"), "addon.image.removeBackground"); + assert_eq!(first("outline text"), "type.createOutlines"); + assert!(within("flip", "object.reflect", 3), "{:?}", ranked(&c, "flip")); + assert!(within("combine", "object.pathfinder.unite", 3), "{:?}", ranked(&c, "combine")); + assert!(ranked(&c, "vectorize").iter().take(3).any(|id| id.starts_with("imageTrace.")), "{:?}", ranked(&c, "vectorize")); + assert_eq!(first("colour"), "panel:color", "{:?}", ranked(&c, "colour")); + // A word that only starts other labels is in a group, and its labels follow the direct match. + assert_eq!(first("unite"), "object.pathfinder.unite"); + assert!(place(&c, "unite", "object.slice.combine").is_some(), "{:?}", ranked(&c, "unite")); + assert!(place(&c, "delete", "view.guides.clear").is_some(), "{:?}", ranked(&c, "delete")); + assert!(place(&c, "settings", "edit.preferences").is_some(), "{:?}", ranked(&c, "settings")); + let merge = ranked(&c, "merge"); + let unite = merge.iter().position(|id| id == "object.pathfinder.unite"); + let named = |id: &String| c.list.iter().any(|e| &e.id == id && split_name(&e.shown).0 == "Merge"); + assert!(merge.first().is_some_and(named), "{merge:?}"); + assert!(unite.is_none() || merge.iter().rposition(named) < unite, "{merge:?}"); + let (scale, vertical) = (place(&c, "type", "type.scaleTextAttributes"), place(&c, "type", "type.orientation.vertical")); + assert!(scale.is_some() && scale < vertical, "{scale:?} {vertical:?}"); + } + /// The application menu of the native Mac menu bar holds the items [`menu_homes`] puts there, /// under the same submenus. #[test] @@ -721,8 +1614,8 @@ mod tests { assert_eq!(of("tool:pen"), None); // The home's words find the result: Preferences… under the native bar's Settings. let native_catalog = catalog(Lang::EN, true); - assert!(place(&native_catalog, "settings pref", "edit.preferences").is_some()); - assert!(place(&c, "settings pref", "edit.preferences").is_none()); + assert!(place(&native_catalog, "vectorcraft settings pref", "edit.preferences").is_some()); + assert!(place(&c, "vectorcraft settings pref", "edit.preferences").is_none()); // The menu item's own label finds the result too: File › Exit runs Quit VectorCraft. assert!(place(&c, "exit", "app.quit").is_some()); } @@ -744,10 +1637,32 @@ mod tests { let c = catalog(Lang::EN, false); let built = started.elapsed(); let started = std::time::Instant::now(); - let index = Index::build(&c.list, &[]); + let params = super::super::params_texts(&c.list); + let index = Index::build(&c.list, &[], ¶ms, |_| None); println!("catalog {built:?}, index alone {:?}, {} results, {} bytes", started.elapsed(), c.list.len(), index.bytes()); + let started = std::time::Instant::now(); + let without = Index::build(&c.list, &[], &[], |_| None); + println!("index without descriptions {:?}, {} bytes", started.elapsed(), without.bytes()); let long = "q".repeat(200); - for q in ["e", "ea", "select", "bring front", "zzzz", long.as_str()] { + let typos = "gruop elipse rectange eyedroper trasnform patern gradeint symbl"; + let repeated = format!("{typos} ").repeat(3); + let queries = [ + "e", + "ea", + "select", + "bring front", + "zzzz", + "eyedroper", + "gruop zz", + "remove bg", + "colour", + "transparent background", + "png", + typos, + repeated.as_str(), + long.as_str(), + ]; + for q in queries { let started = std::time::Instant::now(); let runs = 100; for _ in 0..runs { diff --git a/crates/ui-egui/src/palette/words.rs b/crates/ui-egui/src/palette/words.rs new file mode 100644 index 0000000000..44176dbd24 --- /dev/null +++ b/crates/ui-egui/src/palette/words.rs @@ -0,0 +1,125 @@ +//! Words that mean the same thing when searching the command palette: VectorCraft's own groups, +//! written for this table. A query word in a group also finds results whose label or menu path +//! holds another word of its group ([`super::search`]). +//! +//! A word that is the whole label of a command stays out of a group whose other words name a +//! different command: Merge is the label of Pathfinder and Live Paint commands that are not Unite, +//! and Mirror is the label of a repeat that is not Reflect…, so these are in no group. Insert is left +//! out too, since it starts the labels of type commands that are not Place…. A word that only starts +//! or ends other labels can be in a group, and a search for another word of its group also lists +//! those labels: "unite" lists Combine Slices after Unite, and "delete" lists Clear Guides. Plural and +//! verb forms that the search's English stem forms already join (round and rounded) are not groups. +//! +//! A catalog may add a group's words in its language with a row in the `search` context: the group's +//! English words joined by ", ", then that language's words joined by ", ". The words join the group +//! while that language is the UI language. No catalog has to have these rows. The search splits +//! labels into words only at spaces and punctuation, so in a language written without spaces a row's +//! word finds only a label that is that word alone. + +/// The groups: lowercase single English words, at most `MAX_WORDS` in a group and `MAX_GROUPS` +/// groups, no word longer than [`MAX_CHARS`] characters and no word in two groups. +pub(crate) const GROUPS: &[&[&str]] = &[ + &["remove", "delete", "erase", "clear"], + &["background", "bg"], + &["image", "picture", "photo", "img", "bitmap"], + &["text", "type"], + &["reflect", "flip"], + &["unite", "combine"], + &["trace", "vectorize"], + &["color", "colour"], + &["gray", "grey"], + &["grayscale", "greyscale"], + &["center", "centre"], + &["duplicate", "clone"], + &["zoom", "magnify"], + &["rotate", "turn", "spin"], + &["scale", "resize"], + &["opacity", "transparency"], + &["font", "typeface"], + &["preferences", "settings", "prefs"], + &["artboard", "canvas"], + &["swatch", "palette"], + &["eyedropper", "dropper"], +]; + +/// The most groups [`GROUPS`] may hold. +#[cfg(test)] +const MAX_GROUPS: usize = 60; +/// The most words a group may hold. +#[cfg(test)] +const MAX_WORDS: usize = 6; +/// The most characters a word may have. +pub(crate) const MAX_CHARS: usize = 20; + +/// The context of a catalog row that adds a group's words in its language. +pub(crate) const CONTEXT: &str = "search"; + +/// The source text of group `group`'s row in a catalog: its words joined by ", ". +pub(crate) fn row_key(group: &[&str]) -> String { + group.join(", ") +} + +/// The words of a catalog row's translation `text`, each trimmed and lowercased with its runs of +/// whitespace made one space, and whether each is a single word of at most [`MAX_CHARS`] +/// characters that the search can look up. +pub(crate) fn row_words(text: &str) -> impl Iterator + '_ { + text.split(',').map(|w| { + let w = super::search::normalize(w); + let single = !w.is_empty() && w.chars().count() <= MAX_CHARS && super::search::is_one_word(&w); + (w, single) + }) +} + +/// What is wrong with a catalog's `search` row for `source` translated as `text`: a source that is +/// no group's [`row_key`], an empty word, a word that is not a single word, or a word that is a word +/// of another group. +#[cfg(test)] +pub(crate) fn row_problems(source: &str, text: &str) -> Vec { + let Some(group) = GROUPS.iter().position(|g| row_key(g) == source) else { + return vec![format!("{source:?} is not a group")]; + }; + let mut problems = vec![]; + for (w, single) in row_words(text) { + if w.is_empty() { + problems.push(format!("{source:?}: an empty word")); + } else if !single { + problems.push(format!("{source:?}: {w:?} is not a single word")); + } else if let Some(other) = GROUPS.iter().enumerate().find(|&(i, g)| i != group && g.contains(&w.as_str())) { + problems.push(format!("{source:?}: {w:?} is a word of {:?}", row_key(other.1))); + } + } + problems +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The table keeps to its limits: groups, words per group, characters per word, and each word + /// lowercase, a single word and in one group only. + #[test] + fn the_groups_keep_to_their_limits() { + assert!(GROUPS.len() <= MAX_GROUPS, "{} groups", GROUPS.len()); + let mut seen = std::collections::HashSet::new(); + for group in GROUPS { + assert!((2..=MAX_WORDS).contains(&group.len()), "{group:?}"); + for &w in *group { + assert!(w.chars().count() <= MAX_CHARS, "{w}"); + assert_eq!(super::super::search::normalize(w), w, "{w} is lowercase"); + assert!(super::super::search::is_one_word(w), "{w} is one word"); + assert!(seen.insert(w), "{w} is in two groups"); + } + } + } + + /// A catalog row passes when it names a group and adds single words of no other group, and fails + /// otherwise. + #[test] + fn catalog_rows_are_checked() { + assert!(row_problems("remove, delete, erase, clear", "entfernen, löschen").is_empty()); + assert_eq!(row_problems("remove, delete", "entfernen").len(), 1, "not a group's words"); + assert_eq!(row_problems("remove, delete, erase, clear", "entfernen,, löschen").len(), 1, "an empty word"); + assert_eq!(row_problems("remove, delete, erase, clear", "ganz entfernen").len(), 1, "two words"); + assert_eq!(row_problems("remove, delete, erase, clear", "Text").len(), 1, "a word of another group once lowercased"); + } +} diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rs index 0a4f01879d..02c448755a 100644 --- a/crates/ui-egui/src/panel_docking.rs +++ b/crates/ui-egui/src/panel_docking.rs @@ -1128,6 +1128,7 @@ fn known(action: &Action) -> bool { pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) { let area = area_id(); let ctx = ui.ctx().clone(); + crate::tools_float::set_dock_area_left(&ctx, ui.available_rect_before_wrap().left()); let changed_workspace = ctx.data_mut(|data| { let previous = data.get_temp::(area.with("generation")); data.insert_temp(area.with("generation"), app.ui.docking_generation); @@ -1305,6 +1306,40 @@ pub(crate) fn modal_open(app: &VectorcraftApp, ctx: &egui::Context) -> bool { || ctx.memory(|m| m.areas().is_visible(&crate::dialogs::modal::backdrop())) } +/// Is a modal window open in this pass: a dialog, the About window, a file dialog, the update +/// prompt, or a window such as a progress window drawn over the modal backdrop in this pass? +pub(crate) fn modal_window_up(app: &VectorcraftApp, ctx: &egui::Context) -> bool { + app.ui.dialog.is_some() + || app.ui.about + || app.file_dialog_open() + || crate::updates_ui::blocks_input(app) + || crate::dialogs::modal::drawn_this_pass(ctx) +} + +/// The key of whether a modal window was up in the last pass ([`close_overlays_for_modal`]). +fn modal_window_up_id() -> egui::Id { + egui::Id::unique("modal-window-up") +} + +/// While a modal window is up ([`modal_window_up`]), keeps the command palette closed, so a palette +/// opened over it from the macOS menu bar or by an automation command does not take the keyboard +/// from the window. In the pass the window opens, also closes a tool group's flyout, the All Tools +/// drawer and any open popup, whatever opened the window: a press in the window, a pick in the +/// macOS menu bar, an automation command or a run that ends in a dialog. Popups the window itself +/// opens later stay open. Called after every window of the pass has drawn. +pub(crate) fn close_overlays_for_modal(app: &mut VectorcraftApp, ctx: &egui::Context) { + let up = modal_window_up(app, ctx); + let was = ctx.data_mut(|d| std::mem::replace(d.get_temp_mut_or_default::(modal_window_up_id()), up)); + if up { + app.ui.palette_open = false; + } + if up && !was { + app.ui.flyout = None; + app.ui.tools_drawer = false; + egui::Popup::close_all(ctx); + } +} + /// Keys, text and clipboard events that a floating panel's own OS window left over run the main /// window's shortcuts, tool keys and clipboard on its next frame ([`VectorcraftApp::raw_input_hook`]). /// craft-ui forwards nothing while a field in that window has the keyboard. A field of the main @@ -1377,6 +1412,7 @@ pub(crate) fn floating_size(panel: &str) -> egui::Vec2 { // Tall enough to show its Corners and Shared Edges sections, last in it, which the Corner // Tool's and Shared Edge Merge Tool's menu items open. crate::addons::pathtools::ID => egui::vec2(260.0, 660.0), + crate::addons::packaging::preview::ID => egui::vec2(520.0, 440.0), _ => egui::vec2(260.0, 360.0), } } diff --git a/crates/ui-egui/src/panel_docking/tests.rs b/crates/ui-egui/src/panel_docking/tests.rs index 266f423838..6c861c0db9 100644 --- a/crates/ui-egui/src/panel_docking/tests.rs +++ b/crates/ui-egui/src/panel_docking/tests.rs @@ -408,7 +408,7 @@ fn a_character_field_shortcut_brings_the_floating_character_panel_forward() { h.frame(vec![]); assert!(showing(&h.app.ui, "character")); assert_eq!(h.app.dock_rt.raise, None); - for command in ["type.highlightKerning", "type.highlightTracking", "type.highlightFontName"] { + for command in ["type.highlightKerning", "type.highlightTracking", "type.highlightFontName", "type.highlightFontSize"] { h.app.run(command, json!({})).unwrap(); assert_eq!(h.app.dock_rt.raise.as_deref(), Some("character"), "{command}"); h.frame(vec![]); @@ -833,57 +833,185 @@ fn keep_tools_beside_the_canvas_toggles_and_rejects_a_value_that_is_not_true_or_ assert!(!h.app.ui.tools_beside_canvas, "a bad value changes nothing"); } -/// Off, only the window's edge docks a floating Tools panel; on, the canvas's edge does too, and -/// both dock it beside the canvas. +/// Whichever way the setting is, the canvas's left edge, right of a left-side dock, docks a +/// floating Tools panel beside the canvas and turns the setting on, and the window's left edge +/// docks it outside the dock and turns the setting off; the menu item's check mark follows. #[test] -fn tools_redock_at_the_targets_of_the_chosen_placement() { +fn tools_dropped_on_a_left_edge_dock_there_and_the_setting_follows() { for beside in [false, true] { let mut h = Harness::new(); keep_tools_beside_canvas(&mut h, beside); h.app.run("window.panel.dock", json!({"panel": "layers", "side": "Start"})).unwrap(); - for at_window_edge in [false, true] { + for at_window_edge in [false, true, false] { h.app.run("window.panel.float", json!({"panel": "tools", "x": 600, "y": 300})).unwrap(); settle(&mut h); let canvas = h.app.canvas_rect.unwrap(); let canvas_edge = h.ctx.data(|d| d.get_temp::(crate::tools_float::tools_zone_id())); - assert_eq!(canvas_edge.is_some(), beside, "a canvas-edge target only while kept beside the canvas"); - let canvas_edge = canvas_edge.map_or(pos2(canvas.left() + 12.0, canvas.center().y), |r| r.center()); - let target = if at_window_edge { pos2(12.0, canvas.center().y) } else { canvas_edge }; + let canvas_edge = canvas_edge.expect("the canvas's left edge is a target whichever way the setting is"); + assert!(canvas_edge.left() > 60.0, "right of the left-side dock: {canvas_edge:?}"); + let target = if at_window_edge { pos2(12.0, canvas.center().y) } else { canvas_edge.center() }; h.drag(pos2(620.0, 307.0), target); - if !beside && !at_window_edge { - assert!(h.app.ui.toolbar_pos.is_some(), "the canvas's edge does not dock Tools while the setting is off"); - continue; - } - assert_eq!(h.app.ui.toolbar_pos, None, "beside: {beside}, at the window edge: {at_window_edge}"); + let case = format!("set before: {beside}, at the window edge: {at_window_edge}"); + assert_eq!(h.app.ui.toolbar_pos, None, "{case}"); + assert_eq!(h.app.ui.tools_beside_canvas, !at_window_edge, "{case}"); + assert_eq!(crate::menus::checked(&h.app, "window.toolsBesideCanvas", &json!({})), Some(!at_window_edge), "{case}"); settle(&mut h); - assert_eq!(tools_place(&h), Some(beside), "beside: {beside}, at the window edge: {at_window_edge}"); + assert_eq!(tools_place(&h), Some(!at_window_edge), "{case}"); } } } -/// Turning the setting off while Tools floats forgets the canvas-edge target, and turning it on -/// leaves a floating Tools panel floating. +/// With no panels docked on the left, the canvas's left edge and the window's left edge overlap, +/// and a drop there docks Tools where the setting puts it, leaving the setting as it is. #[test] -fn toggling_while_tools_floats_keeps_it_floating_and_drops_the_canvas_target() { +fn tools_dropped_where_the_left_edges_overlap_keep_the_setting() { + for beside in [false, true] { + let mut h = Harness::new(); + keep_tools_beside_canvas(&mut h, beside); + h.app.run("window.panel.float", json!({"panel": "tools", "x": 600, "y": 300})).unwrap(); + settle(&mut h); + let canvas_edge = h.ctx.data(|d| d.get_temp::(crate::tools_float::tools_zone_id())).expect("the canvas-edge target"); + assert!(canvas_edge.left() < 30.0, "no panels on the left: {canvas_edge:?}"); + h.drag(pos2(620.0, 307.0), pos2(canvas_edge.left() + 4.0, canvas_edge.center().y)); + assert_eq!(h.app.ui.toolbar_pos, None, "set before: {beside}"); + assert_eq!(h.app.ui.tools_beside_canvas, beside, "the setting is unchanged"); + settle(&mut h); + let tools = docked_tools(&h); + assert!(tools.left() < 10.0, "docked at the left edge, set before: {beside}: {tools:?}"); + assert!(tools.right() <= h.app.canvas_rect.unwrap().left() + 1.0, "left of the canvas: {tools:?}"); + } +} + +/// A toolbar made with New Toolbar docked on the left, and no panels there: Tools docks left of the +/// toolbar's lane either way, so a drop on the canvas's edge, right of the lane, keeps the setting. +#[test] +fn tools_dropped_beside_a_left_toolbar_lane_keep_the_setting() { + for beside in [false, true] { + let mut h = Harness::new(); + keep_tools_beside_canvas(&mut h, beside); + h.app.run("window.toolbar.new", json!({"name": "Mine"})).unwrap(); + h.app.run("window.toolbar.dock", json!({"name": "Mine", "side": "left"})).unwrap(); + h.app.run("window.panel.float", json!({"panel": "tools", "x": 600, "y": 300})).unwrap(); + settle(&mut h); + let canvas_edge = h.ctx.data(|d| d.get_temp::(crate::tools_float::tools_zone_id())).expect("the canvas-edge target"); + assert!(canvas_edge.left() > 30.0, "right of the toolbar lane: {canvas_edge:?}"); + let at = pos2(canvas_edge.right() - 4.0, canvas_edge.center().y); + let lit = crate::tools_float::drop_highlight(&h.ctx, at, beside).expect("a strip lights up"); + assert!(lit.left() < 10.0, "the window's edge, where Tools docks, lights up: {lit:?}"); + h.drag(pos2(620.0, 307.0), at); + assert_eq!(h.app.ui.toolbar_pos, None, "set before: {beside}"); + assert_eq!(h.app.ui.tools_beside_canvas, beside, "the setting is unchanged"); + settle(&mut h); + assert!(docked_tools(&h).left() < 10.0, "left of the lane, set before: {beside}"); + } +} + +/// Dragged out of the panel docked at the window's edge and released in the next frame, right of +/// where the panel was, Tools stays floating and the setting stays off. +#[test] +fn tools_released_as_they_float_from_the_window_edge_keep_floating() { + let mut h = Harness::new(); + let docked = docked_tools(&h); + let title = docked.min + vec2(20.0, 12.0); + h.frame(vec![Event::PointerMoved(title), button(title, true)]); + h.frame(vec![Event::PointerMoved(title + vec2(0.0, 10.0))]); + let out = pos2(docked.right().max(crate::toolbar::WIDTH) + 8.0, title.y + 10.0); + h.frame(vec![Event::PointerMoved(out)]); + assert!(h.app.ui.toolbar_pos.is_some(), "dragged out of the docked panel, Tools floats"); + h.frame(vec![button(out, false)]); + settle(&mut h); + assert!(h.app.ui.toolbar_pos.is_some(), "the strip laid out right of the docked panel docks nothing"); + assert!(!h.app.ui.tools_beside_canvas); +} + +/// A drop on the right edge leaves the setting as it is, and so does a move of Tools floating over +/// the canvas's left edge that ends within a few points of where it started. +#[test] +fn tools_docked_on_the_right_or_clicked_leave_the_setting() { + for beside in [false, true] { + let mut h = Harness::new(); + keep_tools_beside_canvas(&mut h, beside); + h.app.run("window.panel.dock", json!({"panel": "layers", "side": "Start"})).unwrap(); + h.app.run("window.panel.float", json!({"panel": "tools", "x": 600, "y": 300})).unwrap(); + settle(&mut h); + h.drag(pos2(620.0, 307.0), pos2(SCREEN.right() - 10.0, 500.0)); + assert_eq!((h.app.ui.toolbar_pos, h.app.ui.toolbar_right), (None, true), "set before: {beside}"); + assert_eq!(h.app.ui.tools_beside_canvas, beside, "docked on the right, the setting is unchanged"); + let canvas_edge = h.ctx.data(|d| d.get_temp::(crate::tools_float::tools_zone_id())).expect("the canvas-edge target"); + h.app.run("window.panel.float", json!({"panel": "tools", "x": canvas_edge.left(), "y": 300})).unwrap(); + settle(&mut h); + let [x, y] = h.app.ui.toolbar_pos.unwrap(); + let title = pos2(x + 12.0, y + 7.0); + assert!(canvas_edge.contains(title), "the title bar is over the canvas's edge: {title:?} {canvas_edge:?}"); + h.press_and_move(title, title + vec2(30.0, 0.0)); + let moved = h.app.ui.toolbar_pos.map(|[px, _]| px - x); + assert!(moved.is_some_and(|dx| dx > 10.0), "the move started, set before: {beside}: {moved:?}"); + let back = title + vec2(2.0, 0.0); + h.frame(vec![Event::PointerMoved(back)]); + h.frame(vec![button(back, false)]); + settle(&mut h); + assert!(h.app.ui.toolbar_pos.is_some(), "released where it started, Tools docks nowhere, set before: {beside}"); + assert_eq!(h.app.ui.tools_beside_canvas, beside, "the setting is unchanged"); + } +} + +/// A left-side dock collapsed to icons is narrower than the window's strip: only the column the +/// two strips share keeps the setting, and each strip's own part docks at its place. +#[test] +fn tools_dropped_beside_a_collapsed_left_dock_follow_the_strip_dropped_on() { + let mut h = Harness::new(); + h.app.run("window.panel.dock", json!({"panel": "layers", "side": "Start"})).unwrap(); + h.app.run("window.collapseDock", json!({"collapsed": true})).unwrap(); + let float = |h: &mut Harness| { + h.app.run("window.panel.float", json!({"panel": "tools", "x": 600, "y": 300})).unwrap(); + settle(h); + h.ctx.data(|d| d.get_temp::(crate::tools_float::tools_zone_id())).expect("the canvas-edge target") + }; + let zone = float(&mut h); + let window_strip = crate::toolbar::WIDTH; + assert!(zone.left() > 10.0 && zone.left() < window_strip - 4.0, "an icon column narrower than the window's strip: {zone:?}"); + let y = zone.center().y; + // Beside the canvas: right of the icon column; at the window's edge: left of it. + let placed_beside = |h: &mut Harness, icons: Rect| { + settle(h); + let tools = docked_tools(h); + if tools.left() >= icons.left() - 1.0 { + Some(true) + } else if tools.left() < 10.0 { + Some(false) + } else { + None + } + }; + // Right of the window's strip: beside the canvas. + h.drag(pos2(620.0, 307.0), pos2(window_strip + 4.0, y)); + assert_eq!((h.app.ui.toolbar_pos, h.app.ui.tools_beside_canvas), (None, true)); + assert_eq!(placed_beside(&mut h, zone), Some(true)); + // In the shared column: where the setting puts it, the setting unchanged. + let zone = float(&mut h); + h.drag(pos2(620.0, 307.0), pos2(zone.left() + 2.0, y)); + assert_eq!((h.app.ui.toolbar_pos, h.app.ui.tools_beside_canvas), (None, true)); + assert_eq!(placed_beside(&mut h, zone), Some(true)); + // Left of the icon column: at the window's edge. + let zone = float(&mut h); + h.drag(pos2(620.0, 307.0), pos2(zone.left() / 2.0, y)); + assert_eq!((h.app.ui.toolbar_pos, h.app.ui.tools_beside_canvas), (None, false)); + assert_eq!(placed_beside(&mut h, zone), Some(false)); +} + +/// Turning the setting on or off while Tools floats leaves it floating. +#[test] +fn toggling_while_tools_floats_keeps_it_floating() { let mut h = Harness::new(); h.app.run("window.panel.dock", json!({"panel": "layers", "side": "Start"})).unwrap(); keep_tools_beside_canvas(&mut h, true); h.app.run("window.panel.float", json!({"panel": "tools", "x": 600, "y": 300})).unwrap(); settle(&mut h); - let zone = h.ctx.data(|d| d.get_temp::(crate::tools_float::tools_zone_id())).expect("the canvas-edge target"); - keep_tools_beside_canvas(&mut h, false); - assert!(h.app.ui.toolbar_pos.is_some(), "turning it off leaves Tools floating"); - assert!(h.ctx.data(|d| d.get_temp::(crate::tools_float::tools_zone_id())).is_none(), "the canvas-edge target is gone"); - h.drag(pos2(620.0, 307.0), zone.center()); - assert!(h.app.ui.toolbar_pos.is_some(), "the old canvas-edge strip docks nothing"); let [x, y] = h.app.ui.toolbar_pos.unwrap(); + keep_tools_beside_canvas(&mut h, false); + assert_eq!(h.app.ui.toolbar_pos, Some([x, y]), "turning it off leaves Tools floating where it was"); keep_tools_beside_canvas(&mut h, true); assert_eq!(h.app.ui.toolbar_pos, Some([x, y]), "turning it on leaves Tools floating where it was"); - keep_tools_beside_canvas(&mut h, false); - h.drag(pos2(x + 20.0, y + 7.0), pos2(12.0, zone.center().y)); - assert_eq!(h.app.ui.toolbar_pos, None); - settle(&mut h); - assert_eq!(tools_place(&h), Some(false)); } /// The setting is kept with a workspace; state and workspaces saved without it keep Tools at the @@ -980,6 +1108,7 @@ fn tools_redock_at_window_edge_above_and_below_canvas() { assert!(panel.center().y < canvas.top() || panel.center().y > canvas.bottom()); h.drag(pos2(620.0, 307.0), pos2(12.0, panel.center().y)); assert_eq!(h.app.ui.toolbar_pos, None, "window-edge drop, beside: {beside}, above the canvas: {above}"); + assert_eq!(h.app.ui.tools_beside_canvas, beside, "no panels on the left: the setting is unchanged"); settle(&mut h); let tools = docked_tools(&h); let panel = h.tab(if above { "layers" } else { "properties" }).unwrap(); @@ -1333,6 +1462,41 @@ fn f7_hides_and_restores_the_whole_expanded_group() { assert!(showing(&h.app.ui, "properties")); } +/// A tool's request for the Transform panel (a double-click on a shape's corner widget) shows and +/// selects it wherever it is: closed, floating, behind another tab, in an icon column or in a dock +/// hidden by Tab. Asking again keeps it on show. +#[test] +fn a_tools_panel_request_shows_the_panel_and_a_second_keeps_it_shown() { + let mut h = Harness::new(); + let ask_twice = |h: &mut Harness, case: &str| { + for n in 1..=2 { + crate::canvas::apply_requests(&mut h.app, Ok(vec![vectorcraft_engine::UiRequest::Panel("transform".into())])); + h.frame(vec![]); + assert!(visible(&h.app.ui, "transform"), "{case}: request {n}"); + } + }; + if h.layout().contains(&"transform".to_string()) { + h.app.run("window.panel.close", json!({"panel": "transform"})).unwrap(); + } + assert!(!visible(&h.app.ui, "transform")); + ask_twice(&mut h, "closed"); + h.app.run("window.panel.float", json!({"panel": "transform"})).unwrap(); + h.frame(vec![]); + ask_twice(&mut h, "floating"); + h.app.run("window.panel.move", json!({"panel": "transform", "anchor": "properties"})).unwrap(); + h.app.run("window.panel.activate", json!({"panel": "properties"})).unwrap(); + h.frame(vec![]); + assert!(!visible(&h.app.ui, "transform")); + ask_twice(&mut h, "behind another tab"); + h.app.run("window.collapseDock", json!({"collapsed": true})).unwrap(); + h.frame(vec![]); + assert!(in_iconic_column(&h.layout(), "transform")); + ask_twice(&mut h, "in an icon column"); + h.app.ui.dock = false; + assert!(!visible(&h.app.ui, "transform")); + ask_twice(&mut h, "in a hidden dock"); +} + #[test] fn f7_restores_only_tabs_hidden_with_the_group() { let mut h = Harness::new(); diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index aa07b13a90..2e1b81e732 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -17,6 +17,7 @@ pub mod color_guide; pub mod color_themes; pub mod color_wheel; pub mod css_properties; +pub mod discover; pub mod doc_info; pub mod flattener_preview; pub mod glyphs; @@ -51,6 +52,8 @@ pub mod transform; pub mod transparency; pub mod variables; +use std::sync::Arc; + use egui::{Rect, Sense, Ui, vec2}; use serde_json::{Value, json}; use vectorcraft_color::{BlendMode, Color, Paint}; @@ -62,9 +65,11 @@ use crate::theme::Tokens; use crate::widgets::{Live, dim_label}; use crate::{VectorcraftApp, icons}; -/// The first selected node (cloned), if any. -pub fn first_selected(app: &VectorcraftApp) -> Option { - first_node(app).cloned() +/// The first selected node, as the `Arc` the document holds, if any. It does not change with later +/// edits: read it again after one. +pub fn first_selected(app: &VectorcraftApp) -> Option> { + let st = app.session.active()?; + st.selection.objects.first().and_then(|id| layers::node_arc(&st.doc, *id)) } /// The radius the Live Corners of path `n` show in the panels: that of the corners the panels set @@ -188,12 +193,15 @@ pub fn show_icon_panel(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) { three_d::ID => three_d::show(app, ui), script_console::ID => script_console::show(app, ui), learn::ID => learn::show(app, ui), + discover::ID => discover::show(app, ui), crate::addons::cleanup::ID => crate::addons::cleanup::show(app, ui), crate::addons::color::ID => crate::addons::color::show(app, ui), crate::addons::packaging::ID => crate::addons::packaging::show(app, ui), + crate::addons::packaging::preview::ID => crate::addons::packaging::preview::show(app, ui), crate::addons::pathtools::ID => crate::addons::pathtools::show(app, ui), crate::addons::pathtools::shape::ID => crate::addons::pathtools::shape::show(app, ui), crate::addons::pen::ID => crate::addons::pen::show(app, ui), + crate::addons::units::ID => crate::addons::units::show(app, ui), id if library_panel::parse(id).is_some() => library_panel::show(app, ui, id), _ => { dim_label(ui, tl!("This panel is on the roadmap (see the parity plan).")); @@ -239,6 +247,7 @@ pub fn panel_menu_items(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) -> bool "attributes" => attributes::menu(app, ui), svg_interactivity::ID => svg_interactivity::menu(app, ui), "colorThemes" => color_themes::menu(app, ui), + color_wheel::ID => color_wheel::menu(app, ui), "layers" => layers::menu(app, ui), links::ID => links::menu(app, ui), asset_export::ID => asset_export::menu(app, ui), @@ -492,12 +501,14 @@ pub(crate) fn live_run(app: &mut VectorcraftApp, label: &str, cmd: &str, params: match phase { Live::Idle => {} Live::Dragging | Live::Released => { - if app.session.begin_interaction(label).is_ok() { + if app.begin_interaction(label).is_ok() { if let Err(e) = app.session.preview(cmd, ¶ms) { app.ui.status = e.to_string(); } - if phase == Live::Released { - app.session.commit_interaction().ok(); + if phase == Live::Released + && let Err(e) = app.session.commit_interaction() + { + app.ui.status = e.to_string(); } app.sync_views(); } else if phase == Live::Released { @@ -795,6 +806,8 @@ mod tests_brush_libraries; #[cfg(test)] mod tests_color_wheel; #[cfg(test)] +mod tests_color_wheel_box; +#[cfg(test)] mod tests_constrain; #[cfg(test)] mod tests_css_properties; diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 8f4e00893f..c979d46fd5 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -13,7 +13,7 @@ use crate::{VectorcraftApp, icons}; mod files; pub(crate) use files::can_load; -pub use files::{ACTIONS_EXT, LOAD_SET, SAVE_SET, load_set, save_set}; +pub use files::{ACTIONS_EXT, LOAD_SET, REPLACE_SET, SAVE_SET, load_set, replace_set, save_set}; #[derive(Clone, Debug, Serialize, Deserialize)] pub struct Action { @@ -75,13 +75,19 @@ impl Action { /// played, or a panel operation that runs as one batch, while recording) gives its own steps, /// since batches do not nest. pub(crate) fn included_commands(&self) -> Vec { + self.playback_steps().into_iter().map(|s| s.command).collect() + } + + /// [`Action::included_commands`], each with the index in [`Action::steps`] of the step it comes + /// from: the steps of a recorded `command.batch` share its index. + fn playback_steps(&self) -> Vec { self.steps .iter() .enumerate() .filter(|(i, _)| !self.excluded_steps.contains(i)) - .flat_map(|(_, (command, params))| match params.get("commands").and_then(Value::as_array) { - Some(steps) if command == "command.batch" => steps.clone(), - _ => vec![json!({"command": command, "params": params})], + .flat_map(|(row, (command, params))| match params.get("commands").and_then(Value::as_array) { + Some(steps) if command == "command.batch" => steps.iter().map(|c| PlayStep { row, command: c.clone() }).collect(), + _ => vec![PlayStep { row, command: json!({"command": command, "params": params}) }], }) .collect() } @@ -151,6 +157,14 @@ pub(crate) fn shown_text(text: &str) -> String { shown } +/// A step that playback runs: a command as `command.batch` takes it, and the index in +/// [`Action::steps`] of the step it comes from, which an error names. +#[derive(Clone, Debug)] +struct PlayStep { + row: usize, + command: Value, +} + /// An action id no other action in this run has. fn next_action_id() -> u64 { static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); @@ -333,9 +347,12 @@ pub fn default_sets() -> Vec { /// A View menu step ([`is_ui_step`]) runs on its own at every speed, in its place among the steps, and /// adds no undo step ([`run_steps`]). At Accelerated the steps before it and the steps after it are /// then one undo step each. +/// +/// At every speed, the error of a step that fails names the step by its place in the action, 1 for +/// the first, counting excluded steps and stops ([`step_error`]). pub fn play(app: &mut VectorcraftApp, set: usize, idx: usize) -> Result { let Some(a) = app.ui.action_sets.get(set).and_then(|s| s.actions.get(idx)).cloned() else { return Err("no such action".into()) }; - let commands = a.included_commands(); + let commands = a.playback_steps(); if commands.is_empty() { return Err("the action has no included steps".into()); } @@ -350,13 +367,13 @@ pub fn play(app: &mut VectorcraftApp, set: usize, idx: usize) -> Result = commands.into(); + let mut steps: std::collections::VecDeque = commands.into(); let Some(first) = steps.pop_front() else { return Err("the action has no included steps".into()) }; let result = play_step(app, &a.name, first)?; let pending = steps.len(); @@ -374,7 +391,7 @@ pub fn play(app: &mut VectorcraftApp, set: usize, idx: usize) -> Result Result { +fn play_step(app: &mut VectorcraftApp, label: &str, step: PlayStep) -> Result { Ok(run_steps(app, label, vec![step])?.into_iter().next().unwrap_or(Value::Null)) } @@ -387,20 +404,33 @@ pub(crate) fn is_ui_step(step: &Value) -> bool { /// Runs `steps` in order, as saved steps ([`VectorcraftApp::replay`]) → their results. The steps /// between two View menu steps ([`is_ui_step`]) run as one `command.batch` named `label`, which is one /// undo step; a View menu step runs on its own ([`play_ui_step`]). A step that fails ends the run with -/// its error: the batch it is in changes nothing, and the steps before that batch stay done. -fn run_steps(app: &mut VectorcraftApp, label: &str, steps: Vec) -> Result, String> { - fn batch(app: &mut VectorcraftApp, label: &str, run: Vec, results: &mut Vec) -> Result<(), String> { +/// its error: the batch it is in changes nothing, and the steps before that batch stay done. The error +/// of a step names the step's place in the action ([`step_error`]). +fn run_steps(app: &mut VectorcraftApp, label: &str, steps: Vec) -> Result, String> { + fn batch(app: &mut VectorcraftApp, label: &str, run: Vec, results: &mut Vec) -> Result<(), String> { if run.is_empty() { return Ok(()); } - let r = app.replay("command.batch", json!({"label": label, "commands": run}))?; + let (rows, run): (Vec, Vec) = run.into_iter().map(|s| (s.row, s.command)).unzip(); + let r = match app.replay("command.batch", json!({"label": label, "commands": run})) { + Ok(r) => r, + Err(e) => { + // The batch numbers its steps from 0 within this run of them, not within the action. + if let Some((n, id, reason)) = batch_step_failure(&e) + && let Some(&row) = rows.get(n) + { + return step_error(row, id, reason); + } + return Err(e); + } + }; results.extend(r.get("results").and_then(Value::as_array).cloned().unwrap_or_default()); Ok(()) } let mut results = Vec::with_capacity(steps.len()); let mut run = vec![]; for step in steps { - if is_ui_step(&step) { + if is_ui_step(&step.command) { batch(app, label, std::mem::take(&mut run), &mut results)?; results.push(play_ui_step(app, &step)?); } else { @@ -411,13 +441,34 @@ fn run_steps(app: &mut VectorcraftApp, label: &str, steps: Vec) -> Result Ok(results) } +/// The step number, command id and reason in the error `command.batch` gives when one of its steps +/// fails (``batch step 2 (`object.move`) failed: …``); none for any other error, such as one about +/// the whole batch. +fn batch_step_failure(e: &str) -> Option<(usize, &str, &str)> { + let rest = e.strip_prefix("batch step ")?; + let digits = rest.find(|c: char| !c.is_ascii_digit())?; + let n = rest[..digits].parse().ok()?; + let (id, reason) = rest[digits..].strip_prefix(" (`")?.split_once("`) failed: ")?; + Some((n, id, reason)) +} + +/// The error of a played step with command `id` that failed with `reason`, naming the step by its +/// place in the action: 1 for the action's first step, counting excluded steps and stops. A step of +/// a recorded `command.batch` is named by the batch's place and its own command. +fn step_error(row: usize, id: &str, reason: &str) -> Result { + Err(format!("action step {} (`{id}`) failed: {reason}", row + 1)) +} + /// Runs a View menu step as its menu item runs it, which adds no undo step → its result. While an /// action records, the step goes into the recording too, as a stop does, unless it does not fit in /// the action ([`recording_room`]): then the status bar shows the reason. -fn play_ui_step(app: &mut VectorcraftApp, step: &Value) -> Result { - let command = step.get("command").and_then(Value::as_str).unwrap_or_default().to_string(); - let params = step.get("params").filter(|p| !p.is_null()).cloned().unwrap_or_else(|| json!({})); - let r = app.replay(&command, params.clone())?; +fn play_ui_step(app: &mut VectorcraftApp, step: &PlayStep) -> Result { + let command = step.command.get("command").and_then(Value::as_str).unwrap_or_default().to_string(); + let params = step.command.get("params").filter(|p| !p.is_null()).cloned().unwrap_or_else(|| json!({})); + let r = match app.replay(&command, params.clone()) { + Ok(r) => r, + Err(e) => return step_error(step.row, &command, &e), + }; if app.ui.recording.is_some() { match recording_room(app, &command, ¶ms) { Ok(()) => app.session.journal.push((command, params)), @@ -429,8 +480,8 @@ fn play_ui_step(app: &mut VectorcraftApp, step: &Value) -> Result /// [`play`] for an action with a stop: runs what comes before the first stop, or at Step by Step and /// Pause For the first step, and leaves the rest to [`tick_playback`] and [`continue_playback`]. -fn play_with_stops(app: &mut VectorcraftApp, label: String, commands: Vec, options: PlaybackOptions) -> Result { - let mut steps: std::collections::VecDeque = commands.into(); +fn play_with_stops(app: &mut VectorcraftApp, label: String, commands: Vec, options: PlaybackOptions) -> Result { + let mut steps: std::collections::VecDeque = commands.into(); let run = next_run(&mut steps, options.speed); let ran = !run.is_empty(); let results = if ran { run_steps(app, &label, run)? } else { vec![] }; @@ -441,9 +492,9 @@ fn play_with_stops(app: &mut VectorcraftApp, label: String, commands: Vec /// Takes the steps that run next as one undo step off the front of `steps`: at Accelerated all of /// them up to the next stop, at the other speeds one. None when a stop comes next. -fn next_run(steps: &mut std::collections::VecDeque, speed: PlaybackSpeed) -> Vec { +fn next_run(steps: &mut std::collections::VecDeque, speed: PlaybackSpeed) -> Vec { let mut run = vec![]; - while steps.front().is_some_and(|s| !is_stop(s)) { + while steps.front().is_some_and(|s| !is_stop(&s.command)) { run.extend(steps.pop_front()); if speed != PlaybackSpeed::Accelerated { break; @@ -462,7 +513,7 @@ fn after_run(app: &mut VectorcraftApp, ran: bool) { playing.played_in = played_in; playing.next_at = None; playing.hold = ran && playing.options.speed == PlaybackSpeed::Step; - if (!ran || playing.options.speed == PlaybackSpeed::Accelerated) && playing.steps.front().is_some_and(is_stop) { + if (!ran || playing.options.speed == PlaybackSpeed::Accelerated) && playing.steps.front().is_some_and(|s| is_stop(&s.command)) { hold_at_stop(app); } if let Some(ctx) = &app.ui_ctx { @@ -527,7 +578,7 @@ struct AtStop { fn hold_at_stop(app: &mut VectorcraftApp) { let Some(playing) = app.ui.action_playing.as_mut() else { return }; let Some(step) = playing.steps.pop_front() else { return }; - let params = step.get("params").cloned().unwrap_or(Value::Null); + let params = step.command.get("params").cloned().unwrap_or(Value::Null); let message = params.get("message").and_then(Value::as_str).unwrap_or_default().to_string(); let allow_continue = params.get("allowContinue").and_then(Value::as_bool).unwrap_or(false); playing.stop = Some(AtStop { message, allow_continue, shown: false }); @@ -632,7 +683,7 @@ pub fn deserialize_playback<'de, D: serde::Deserializer<'de>>(d: D) -> Result, + steps: std::collections::VecDeque, /// The options the action started playing with. options: PlaybackOptions, /// With Pause For, when the next step runs (seconds on the app's clock); none until the frame @@ -690,7 +741,7 @@ pub fn tick_playback(app: &mut VectorcraftApp, now: f64) -> Option { return Some(due - now); } } - if playing.steps.front().is_some_and(is_stop) { + if playing.steps.front().is_some_and(|s| is_stop(&s.command)) { hold_at_stop(app); return None; } @@ -2160,8 +2211,6 @@ pub const RESET: &str = "ui.actionSet.reset"; /// plays (also while it waits at a stop); then nothing changes. No undo step is recorded. /// → {changed, mode, set: the index of the first built-in set} pub fn reset(app: &mut VectorcraftApp, p: &Value) -> Result { - const SELECTED: &str = "actions-selected"; - const EXPANDED: &str = "actions-expanded"; let append = match p { Value::Null => false, Value::Object(m) => { @@ -2192,6 +2241,18 @@ pub fn reset(app: &mut VectorcraftApp, p: &Value) -> Result { } return Ok(json!({ "changed": true, "mode": "append", "set": first })); } + let changed = replace_sets(app, sets); + Ok(json!({ "changed": changed, "mode": "replace", "set": 0 })) +} + +/// Replaces every set in the panel with `sets`, as Reset Actions and Replace Actions… do: the first +/// becomes current and selected, the panel's selected action and step, its expanded actions and a +/// step being dragged are cleared, and an open Set Options, New Action, Batch or step dialog that +/// names a set closes. When the panel already holds sets that save alike, shown that way, nothing +/// changes and the sets keep their ids → whether anything changed. +fn replace_sets(app: &mut VectorcraftApp, sets: Vec) -> bool { + const SELECTED: &str = "actions-selected"; + const EXPANDED: &str = "actions-expanded"; let ctx = app.ui_ctx.clone(); let panel_clear = ctx.as_ref().is_none_or(|ctx| { pstate::>(ctx, SELECTED).is_none() @@ -2200,10 +2261,10 @@ pub fn reset(app: &mut VectorcraftApp, p: &Value) -> Result { && pstate::>(ctx, EXPANDED).is_empty() }); // The ids are not saved, so two lists that save alike hold the same sets. - let built_in = serde_json::to_value(&app.ui.action_sets).is_ok_and(|now| serde_json::to_value(&sets).is_ok_and(|new| new == now)); - let shown_as_reset = app.ui.action_set == Some(0) && app.ui.action_sets_selected == [0] && !app.ui.dialog.as_ref().is_some_and(holds_set); - if built_in && shown_as_reset && panel_clear { - return Ok(json!({ "changed": false, "mode": "replace", "set": 0 })); + let same = serde_json::to_value(&app.ui.action_sets).is_ok_and(|now| serde_json::to_value(&sets).is_ok_and(|new| new == now)); + let shown_as_replaced = app.ui.action_set == Some(0) && app.ui.action_sets_selected == [0] && !app.ui.dialog.as_ref().is_some_and(holds_set); + if same && shown_as_replaced && panel_clear { + return false; } app.ui.action_sets = sets; app.ui.action_set = Some(0); @@ -2217,7 +2278,7 @@ pub fn reset(app: &mut VectorcraftApp, p: &Value) -> Result { set_pstate::>(&ctx, DRAGGED_STEP, None); set_pstate(&ctx, EXPANDED, BTreeSet::::new()); } - Ok(json!({ "changed": true, "mode": "replace", "set": 0 })) + true } /// The panel's (≡) menu. @@ -2301,12 +2362,16 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut egui::Ui) { crate::dialogs::action_playback::open(app); } ui.separator(); - // As commands, so a file dialog shown off the UI thread saves or loads when it answers. + // As commands, so a file dialog shown off the UI thread saves, loads or replaces when it answers. // Save Actions… names the current set by its id, so a file dialog that answers later saves that set. let save = json!({ "id": current.and_then(|s| app.ui.action_sets.get(s)).map(|s| s.id) }); - for (label, id, on, params) in - [(tl!("Save Actions…"), SAVE_SET, current.is_some(), save), (tl!("Load Actions…"), LOAD_SET, can_load(app), json!({}))] - { + // Replace Actions… is off while an action records or plays, as Reset Actions is. + let idle = !recording && app.ui.action_playing.is_none(); + for (label, id, on, params) in [ + (tl!("Save Actions…"), SAVE_SET, current.is_some(), save), + (tl!("Load Actions…"), LOAD_SET, can_load(app), json!({})), + (tl!("Replace Actions…"), REPLACE_SET, can_load(app) && idle, json!({})), + ] { if widgets::menu_item(ui, label, on, false) && let Err(e) = app.run(id, params) && e != "cancelled" @@ -2315,7 +2380,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut egui::Ui) { } } // Asks first: OK replaces the sets with the built-in set, Append adds it after them. - if widgets::menu_item(ui, tl!("Reset Actions"), !recording && app.ui.action_playing.is_none(), false) { + if widgets::menu_item(ui, tl!("Reset Actions"), idle, false) { crate::dialogs::confirm::ask_reset_actions(app); } } @@ -3987,6 +4052,172 @@ mod tests { assert_eq!(saved_sets(&app.ui.action_sets), before, "the playing set stays"); } + /// A click on the panel menu's item `label`; an item that is off takes no click. + fn menu_click(ctx: &egui::Context, app: &mut VectorcraftApp, label: &str) { + use super::super::tests_appearance::{click, frame_events}; + let texts = frame_events(ctx, app, vec![], menu); + let item = texts.iter().find(|(s, _)| s.trim() == label).map(|(_, r)| *r).unwrap_or_else(|| panic!("{label} in the menu")); + click(ctx, app, item.center(), menu); + } + + /// The panel menu's Replace Actions… asks no question, reads the picked file and puts its set, + /// with its name, in place of every set, the built-in set included. A canceled pick changes + /// nothing and says nothing, and the item does nothing where there is no open dialog and while + /// an action records or plays, waiting at a stop included. + #[test] + fn the_panel_menus_replace_actions_puts_the_files_set_in_place_of_every_set() { + let ctx = egui::Context::default(); + let mut app = app_with_sets(); + let before = saved_sets(&app.ui.action_sets); + menu_click(&ctx, &mut app, "Replace Actions…"); + assert_eq!(saved_sets(&app.ui.action_sets), before, "off where there is no open dialog"); + + let files = with_files(&mut app, "/sets/Mine.vcactions"); + let mine = files::write_set(&app.ui.action_sets[1]); + files.borrow_mut().insert("/sets/Mine.vcactions".into(), mine.clone().into_bytes()); + menu_click(&ctx, &mut app, "Replace Actions…"); + assert!(app.ui.dialog.is_none(), "no question first"); + assert_eq!(set_names(&app), ["Mine"], "the built-in set and Other go, and Mine keeps its name"); + assert_eq!(files::write_set(&app.ui.action_sets[0]), mine, "the file's actions and steps"); + assert_eq!((app.ui.action_set, app.ui.action_sets_selected.clone()), (Some(0), vec![0]), "it is current and selected"); + + app.ui.action_sets.push(ActionSet::new("Extra", vec![])); + let before = saved_sets(&app.ui.action_sets); + app.services.pick_open = Some(Box::new(|_: &crate::FilePick| None)); + app.ui.status.clear(); + menu_click(&ctx, &mut app, "Replace Actions…"); + assert_eq!(saved_sets(&app.ui.action_sets), before, "a canceled pick changes nothing"); + assert_eq!(app.ui.status, "", "and says nothing"); + + app.services.pick_open = Some(Box::new(|_: &crate::FilePick| Some("/sets/Mine.vcactions".to_string()))); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run(START_RECORDING, json!({})).unwrap(); + menu_click(&ctx, &mut app, "Replace Actions…"); + assert_eq!(set_names(&app), ["Mine", "Extra"], "off while an action records"); + app.run(STOP_RECORDING, json!({})).unwrap(); + + let (mut app, _) = app_with_a_stop(true); + let files = with_files(&mut app, "/sets/Mine.vcactions"); + files.borrow_mut().insert("/sets/Mine.vcactions".into(), mine.into_bytes()); + let before = saved_sets(&app.ui.action_sets); + play(&mut app, 0, 0).unwrap(); + assert!(waiting_at_stop(&app)); + app.ui.dialog = None; + menu_click(&ctx, &mut app, "Replace Actions…"); + assert_eq!(saved_sets(&app.ui.action_sets), before, "off while playback waits at a stop"); + } + + /// `ui.actionSet.replace` makes the file's set current and selected, clears the panel's selected + /// action and step, expanded actions and a dragged step, closes a dialog that holds a set index + /// and records no undo step. The same file again changes nothing and keeps the ids. A set with + /// no actions replaces the sets too, an `.aia` file reports its left-out steps, and a file with + /// an unknown command reports it, as Load Actions… does; a set with no name takes the file's. + #[test] + fn replace_actions_clears_what_named_the_old_sets_and_reads_aia_files() { + let mut app = app_with_sets(); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + let undo = undo_steps(&app); + app.ui.action_set = Some(2); + app.ui.action_sets_selected = vec![1, 2]; + let ctx = egui::Context::default(); + app.ui_ctx = Some(ctx.clone()); + let nudge = app.ui.action_sets[1].actions[1].id; + set_pstate::>(&ctx, "actions-selected", Some((1, 1))); + set_pstate::>(&ctx, SELECTED_STEP, Some((nudge, 0))); + set_pstate(&ctx, "actions-expanded", BTreeSet::from([nudge])); + let dragged: DraggedStep = (nudge, 0, std::sync::Arc::new((vec![], BTreeSet::new()))); + set_pstate::>(&ctx, DRAGGED_STEP, Some(dragged)); + crate::dialogs::action_batch::open(&mut app, 1, 1).unwrap(); + + let text = files::write_set(&app.ui.action_sets[1]); + let r = app.run(REPLACE_SET, json!({ "data": text })).unwrap(); + assert_eq!(r, json!({"changed": true, "set": 0, "name": "Mine", "actions": 2})); + assert_eq!(set_names(&app), ["Mine"]); + assert_eq!((app.ui.action_set, app.ui.action_sets_selected.clone()), (Some(0), vec![0])); + assert_eq!(pstate::>(&ctx, "actions-selected"), None); + assert_eq!(pstate::>(&ctx, SELECTED_STEP), None); + assert!(pstate::>(&ctx, "actions-expanded").is_empty()); + assert!(pstate::>(&ctx, DRAGGED_STEP).is_none()); + assert!(app.ui.dialog.is_none(), "the Batch dialog of a replaced set closes"); + assert_eq!(undo_steps(&app), undo, "no undo step"); + + let ids = (app.ui.action_sets[0].id, app.ui.action_sets[0].actions.iter().map(|a| a.id).collect::>()); + assert_eq!(app.run(REPLACE_SET, json!({ "data": text })).unwrap()["changed"], false, "the same set, shown that way"); + assert_eq!((app.ui.action_sets[0].id, app.ui.action_sets[0].actions.iter().map(|a| a.id).collect()), ids, "the ids stay"); + + let empty = json!({"format": "vcactions", "version": 1, "name": "Empty", "actions": []}).to_string(); + assert_eq!(app.run(REPLACE_SET, json!({ "data": empty })).unwrap(), json!({"changed": true, "set": 0, "name": "Empty", "actions": 0})); + assert_eq!(set_names(&app), ["Empty"]); + + let aia = aia_text("Tidy Up", &[("Group Them", &[("group", true), ("Move", true)])]); + let r = app.run(REPLACE_SET, json!({ "data": aia })).unwrap(); + let skipped = json!([{"action": "Group Them", "step": "Move"}]); + assert_eq!(r, json!({"changed": true, "set": 0, "name": "Tidy Up", "actions": 1, "skipped": skipped, "leftOut": 1})); + assert_eq!(set_names(&app), ["Tidy Up"]); + assert_eq!(app.ui.action_sets[0].actions[0].steps, [("object.group".to_string(), json!({}))]); + assert_eq!(app.ui.status, "Loaded “Tidy Up”: 1 step was left out"); + + let files = with_files(&mut app, "/sets/unused.vcactions"); + let odd = json!({"format": "vcactions", "version": 1, "name": "", "actions": [{"name": "A", "steps": [{"command": "example.unknown"}]}]}); + files.borrow_mut().insert("/sets/Print Jobs.vcactions".into(), odd.to_string().into_bytes()); + let r = app.run(REPLACE_SET, json!({"path": "/sets/Print Jobs.vcactions"})).unwrap(); + assert_eq!((r["name"].clone(), r["unknownCount"].clone(), r["changed"].clone()), (json!("Print Jobs"), json!(1), json!(true))); + assert_eq!(set_names(&app), ["Print Jobs"]); + } + + /// `ui.actionSet.replace` refuses params that are not an object, another key, a `path` or `data` + /// that is not text, a file that can't be read or that Load Actions… refuses (an empty one too), + /// a canceled pick, and a replace while an action records or plays, waiting at a stop included, + /// and then changes no set and keeps the current set. + #[test] + fn replace_actions_refuses_bad_params_bad_files_and_a_running_action() { + let mut app = app_with_sets(); + let files = with_files(&mut app, "/sets/missing.vcactions"); + files.borrow_mut().insert("/sets/empty.vcactions".into(), vec![]); + app.ui.action_set = Some(1); + let before = saved_sets(&app.ui.action_sets); + let many = json!({"format": "vcactions", "version": 1, "name": "Many", "actions": vec![json!({"name": "A", "steps": []}); 1001]}); + let eof = "not an action set file (EOF while parsing a value at line 1 column 0)"; + for (p, error) in [ + (json!(1), "the params must be an object, not 1"), + (json!([]), "the params must be an object, not []"), + (json!({"set": 0}), "unknown parameter `set`; the command takes: path, data"), + (json!({"path": 5}), "`path` must be a string"), + (json!({"path": null}), "`path` must be a string"), + (json!({"data": 42}), "`data` must be a string"), + (json!({"data": ""}), eof), + (json!({"data": "GIMP Palette"}), "not an action set file (expected value at line 1 column 1)"), + (json!({"data": many.to_string()}), "the action set file holds more than 1,000 actions"), + (json!({"data": " ".repeat(files::MAX_SET_FILE + 1)}), "the action set file is larger than 8 MiB"), + (json!({"data": "/version\n"}), "not an action set file"), + (json!({"path": "/sets/empty.vcactions"}), eof), + (json!({"path": "/sets/nowhere.vcactions"}), "no such file"), + (json!({}), "no such file"), + ] { + assert_eq!(app.run(REPLACE_SET, p.clone()).unwrap_err(), error, "{p}"); + assert_eq!(saved_sets(&app.ui.action_sets), before, "{p} changes nothing"); + assert_eq!(app.ui.action_set, Some(1)); + } + app.services.pick_open = Some(Box::new(|_: &crate::FilePick| None)); + assert_eq!(app.run(REPLACE_SET, Value::Null).unwrap_err(), "cancelled"); + assert_eq!(saved_sets(&app.ui.action_sets), before, "a canceled pick changes nothing"); + + let text = files::write_set(&app.ui.action_sets[1]); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run(START_RECORDING, json!({})).unwrap(); + assert_eq!(app.run(REPLACE_SET, json!({ "data": text })).unwrap_err(), "an action is already recording"); + assert_eq!(saved_sets(&app.ui.action_sets), before, "a recording keeps its set"); + app.run(STOP_RECORDING, json!({})).unwrap(); + + let (mut app, _) = app_with_a_stop(true); + let before = saved_sets(&app.ui.action_sets); + play(&mut app, 0, 0).unwrap(); + assert!(waiting_at_stop(&app)); + assert_eq!(app.run(REPLACE_SET, json!({ "data": text })).unwrap_err(), "an action is already playing"); + assert_eq!(saved_sets(&app.ui.action_sets), before, "the playing set stays"); + } + /// A recording keeps its steps when a canceled undo group drops journal entries made before the /// recording began. #[test] @@ -5813,6 +6044,105 @@ mod tests { assert_eq!(x(&app), 1.0, "the move before Outline stays, and the move of 2 in the failing batch is taken back"); } + /// The error of a played step that fails, with the step's place in the action (1 for the first) + /// and its command id. + fn assert_names_step(e: &str, step: usize, id: &str) { + let prefix = format!("action step {step} (`{id}`) failed: "); + assert!(e.starts_with(&prefix) && e.len() > prefix.len(), "{e}"); + assert!(!e.contains("batch step"), "{e}"); + } + + /// A step that fails after a View menu step at Accelerated is named by its place in the action, + /// not by its place in the batch of the steps after the View step. + #[test] + fn an_error_after_a_view_item_names_the_step_in_the_action() { + let (mut app, _) = app_with_a_view_step(); + app.ui.action_sets[0].actions[0].steps.insert(3, ("object.align".into(), json!({}))); + assert_names_step(&play(&mut app, 0, 0).unwrap_err(), 4, "object.align"); + } + + /// A View menu step that fails is named by its place in the action, excluded steps counted. + #[test] + fn a_failing_view_item_names_the_step_in_the_action() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let steps = vec![("object.move".to_string(), json!({"dx": 1, "dy": 0})), ("view.outline".to_string(), json!({}))]; + let mut action = Action::new("Outline", steps); + action.excluded_steps.insert(0); + app.ui.action_sets = vec![ActionSet::new("Test", vec![action])]; + assert_names_step(&play(&mut app, 0, 0).unwrap_err(), 2, "view.outline"); + } + + /// An excluded step before the failing one counts at Accelerated, as the panel lists it. + #[test] + fn an_error_counts_excluded_steps() { + let (mut app, x) = app_with_three_moves(); + let action = &mut app.ui.action_sets[0].actions[0]; + action.steps.push(("object.align".into(), json!({}))); + action.excluded_steps.insert(0); + assert_names_step(&play(&mut app, 0, 0).unwrap_err(), 4, "object.align"); + assert_eq!(x(&app), 0.0, "the failing batch changes nothing"); + } + + /// A step of a recorded `command.batch` that fails is named by the batch's place in the action + /// and its own command. + #[test] + fn an_error_in_a_recorded_batch_names_the_batch_step() { + let (mut app, _) = app_with_three_moves(); + let batch = json!({"commands": [{"command": "object.move", "params": {"dx": 2, "dy": 0}}, {"command": "object.align", "params": {}}]}); + app.ui.action_sets[0].actions[0].steps.insert(1, ("command.batch".into(), batch)); + assert_names_step(&play(&mut app, 0, 0).unwrap_err(), 2, "object.align"); + } + + /// An error about the whole batch, which names no step, is kept as it is. + #[test] + fn an_error_of_the_whole_batch_names_no_step() { + let (mut app, _) = app_with_three_moves(); + let nested = json!({"commands": [{"command": "command.batch", "params": {"commands": []}}]}); + app.ui.action_sets[0].actions[0].steps.push(("command.batch".into(), nested)); + let e = play(&mut app, 0, 0).unwrap_err(); + assert!(!e.starts_with("action step"), "{e}"); + assert!(e.contains("batches cannot nest"), "{e}"); + } + + /// At Step by Step and Pause For, a later step that fails is named by its place in the action, + /// in the status bar, and the playback ends. + #[test] + fn a_paced_error_names_the_step_in_the_action() { + for speed in ["step", "pause"] { + let (mut app, x) = app_with_three_moves(); + app.ui.action_sets[0].actions[0].steps.insert(2, ("object.align".into(), json!({}))); + app.run(PLAYBACK_OPTIONS, json!({"speed": speed})).unwrap(); + play(&mut app, 0, 0).unwrap(); + let mut now = 0.0; + for _ in 0..40 { + if app.ui.action_playing.is_none() { + break; + } + now += 2.0; + frame(&mut app, now); + } + assert!(app.ui.action_playing.is_none(), "{speed}: the playback ended"); + assert_names_step(&app.ui.status, 3, "object.align"); + assert_eq!(x(&app), 3.0, "{speed}: the moves before the failing step stay, the move after it does not run"); + } + } + + /// A step that fails after Continue at a stop is named by its place in the action, the stops + /// before it counted, the excluded one too. + #[test] + fn an_error_after_a_stop_names_the_step_in_the_action() { + let (mut app, _) = app_with_three_moves(); + let stop = (STOP_STEP.to_string(), json!({"message": "", "allowContinue": true})); + let action = &mut app.ui.action_sets[0].actions[0]; + action.steps.insert(1, stop.clone()); + action.steps.insert(3, stop); + action.steps.push(("object.align".into(), json!({}))); + action.excluded_steps.insert(3); + assert_eq!(play(&mut app, 0, 0).unwrap()["atStop"], json!(true)); + assert_names_step(&app.run(CONTINUE_PLAYBACK, json!({})).unwrap_err(), 6, "object.align"); + assert!(app.ui.action_playing.is_none(), "the playback ended"); + } + /// At Step by Step and Pause For a View menu step is one step of the playback and adds no undo /// step. #[test] diff --git a/crates/ui-egui/src/panels/actions/files.rs b/crates/ui-egui/src/panels/actions/files.rs index d6ca465275..c8f8520ebd 100644 --- a/crates/ui-egui/src/panels/actions/files.rs +++ b/crates/ui-egui/src/panels/actions/files.rs @@ -1,4 +1,4 @@ -//! Action set files: the Actions panel menu's Save Actions… and Load Actions…. +//! Action set files: the Actions panel menu's Save Actions…, Load Actions… and Replace Actions…. //! //! An action set file (`.vcactions`) is JSON: `{"format": "vcactions", "version": 1 to 6, "name", //! "actions": [{"name", "steps": [{"command", "params", "excluded"?}], "key"?, "color"?}]}`. Each step is a @@ -29,6 +29,9 @@ pub const SAVE_SET: &str = "ui.actionSet.save"; /// The command that loads an action set from a file ([`load_set`]). pub const LOAD_SET: &str = "ui.actionSet.load"; +/// The command that replaces every action set with the one from a file ([`replace_set`]). +pub const REPLACE_SET: &str = "ui.actionSet.replace"; + /// The extension of an action set file ([`write_set`]). pub const ACTIONS_EXT: &str = "vcactions"; @@ -496,33 +499,101 @@ fn aia_set(read: &Value, name: &str) -> AiaLoad { AiaLoad { set: ActionSet::new(if set.trim().is_empty() { name.to_string() } else { set }, actions), skipped, left_out } } -/// [`load_set`] of an action set another app saved as text, which `actionSet.read` reads with -/// `params`. -fn load_aia(app: &mut VectorcraftApp, params: Value) -> Result { +/// The steps left out of an action set another app saved as text: the first [`MAX_SKIPPED`] as +/// `[{action, step}]`, and how many there are. None for an action set file. +type LeftOut = Option<(Vec, usize)>; + +/// The set of an action set another app saved as text, which `actionSet.read` reads with `params`, +/// with its left-out steps. +fn read_aia(app: &mut VectorcraftApp, params: Value) -> Result<(ActionSet, LeftOut), String> { // Text that starts `/version` and no number is not an action set either. let read = app.run("actionSet.read", params).map_err(|_| "not an action set file")?; // A set read only in part would play actions that differ from the file's. if read.get("truncated").and_then(Value::as_bool).unwrap_or(false) { return Err("the action set file can't be read in full".into()); } - let AiaLoad { mut set, skipped, left_out } = aia_set(&read, "Actions"); - set.name = free_set_name(&app.ui.action_sets, &set.name); - // The set must save as a file that Load Actions… reads, which can be larger than the file read. - super::edit_keeps_set_loadable(app, None, &set)?; + let AiaLoad { set, skipped, left_out } = aia_set(&read, "Actions"); + Ok((set, Some((skipped, left_out)))) +} + +/// The set of the action set file at `p`'s `path` (else a picked one), or of the file's text +/// `data`, as [`load_set`] reads it. The second value is the left-out steps of an action set +/// another app saved as text (`.aia`), and None for an action set file. Nothing in `app` changes +/// but its status, and an error leaves the sets as they are. +fn read_file(app: &mut VectorcraftApp, p: &Value) -> Result<(ActionSet, LeftOut), String> { + let (text, stem) = match p.get("data") { + Some(Value::String(data)) => { + // Checked before the copy: `read_set` checks it again. + if data.len() > MAX_SET_FILE { + return Err("the action set file is larger than 8 MiB".into()); + } + if is_aia(data.as_bytes()) { + return read_aia(app, json!({ "data": data })); + } + (data.clone(), String::new()) + } + Some(_) => return Err("not an action set file".into()), + None => { + let path = match p.get("path").and_then(Value::as_str) { + Some(path) => path.to_string(), + None => { + let exts = [&[ACTIONS_EXT], vectorcraft_engine::cmd::actionset::EXTS].concat(); + let pick = crate::FilePick { filters: vec![crate::FilePick::filter("Action sets", &exts)], ..Default::default() }; + crate::picks::open(app, &pick).ok_or("cancelled")? + } + }; + // One byte past the limit tells a larger file apart without reading all of it. + let bytes = match (&app.services.read_head, &app.services.read) { + (Some(read_head), _) => read_head(&path, MAX_SET_FILE + 1)?, + (None, Some(read)) => read(&path)?, + (None, None) => return Err("no file reader".into()), + }; + if bytes.len() > MAX_SET_FILE { + return Err("the action set file is larger than 8 MiB".into()); + } + if is_aia(&bytes) { + return read_aia(app, json!({ "name": path, "dataBase64": vectorcraft_format::base64_encode(&bytes) })); + } + let stem = std::path::Path::new(&path).file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default(); + (String::from_utf8(bytes).map_err(|_| "not an action set file")?, stem) + } + }; + Ok((read_set(&text, if stem.is_empty() { "Actions" } else { &stem })?, None)) +} + +/// The answer of [`load_set`] and [`replace_set`] for `set`, which goes at index `at`, with its +/// left-out steps `aia` ([`read_file`]); the status bar names what was left out or kept. +fn loaded(app: &mut VectorcraftApp, set: &ActionSet, at: usize, aia: LeftOut) -> Value { let (name, actions) = (set.name.clone(), set.actions.len()); - app.ui.action_sets.push(set); - if left_out > 0 { - app.status(crate::i18n::msg_n( - left_out as u64, - "Loaded “{name}”: {n} step was left out", - "Loaded “{name}”: {n} steps were left out", - &[("name", &name)], - )); + if let Some((skipped, left_out)) = aia { + if left_out > 0 { + app.status(crate::i18n::msg_n( + left_out as u64, + "Loaded “{name}”: {n} step was left out", + "Loaded “{name}”: {n} steps were left out", + &[("name", &name)], + )); + } + return json!({ "set": at, "name": name, "actions": actions, "skipped": skipped, "leftOut": left_out }); } - Ok(json!({ - "set": app.ui.action_sets.len() - 1, "name": name, "actions": actions, - "skipped": skipped, "leftOut": left_out, - })) + let (unknown, unknown_count, first) = unknown_commands(set); + let mut answer = json!({ "set": at, "name": name, "actions": actions }); + if let Some((action, step, command)) = first { + app.status(crate::i18n::msg_n( + unknown_count as u64, + "Loaded “{name}”: {n} step has an unknown command and was kept: “{action}”, step {step}, `{command}`", + "Loaded “{name}”: {n} steps have unknown commands and were kept; the first: “{action}”, step {step}, `{command}`", + &[ + ("name", &super::shown_text(&name)), + ("action", &super::shown_text(&action)), + ("step", &step), + ("command", &super::shown_text(&command)), + ], + )); + answer["unknownCommands"] = json!(unknown); + answer["unknownCount"] = json!(unknown_count); + } + answer } /// `ui.actionSet.load {path? | data?}`: reads the action set file at `path` (else a picked one), or @@ -548,66 +619,50 @@ fn load_aia(app: &mut VectorcraftApp, params: Value) -> Result { /// Such a file that `actionSet.read` marks `truncated` is refused, and so is one whose set Save /// Actions… would write larger than 8 MiB; then no set is added. pub fn load_set(app: &mut VectorcraftApp, p: &Value) -> Result { - let (text, stem) = match p.get("data") { - Some(Value::String(data)) => { - // Checked before the copy: `read_set` checks it again. - if data.len() > MAX_SET_FILE { - return Err("the action set file is larger than 8 MiB".into()); - } - if is_aia(data.as_bytes()) { - return load_aia(app, json!({ "data": data })); - } - (data.clone(), String::new()) - } - Some(_) => return Err("not an action set file".into()), - None => { - let path = match p.get("path").and_then(Value::as_str) { - Some(path) => path.to_string(), - None => { - let exts = [&[ACTIONS_EXT], vectorcraft_engine::cmd::actionset::EXTS].concat(); - let pick = crate::FilePick { filters: vec![crate::FilePick::filter("Action sets", &exts)], ..Default::default() }; - crate::picks::open(app, &pick).ok_or("cancelled")? - } - }; - // One byte past the limit tells a larger file apart without reading all of it. - let bytes = match (&app.services.read_head, &app.services.read) { - (Some(read_head), _) => read_head(&path, MAX_SET_FILE + 1)?, - (None, Some(read)) => read(&path)?, - (None, None) => return Err("no file reader".into()), - }; - if bytes.len() > MAX_SET_FILE { - return Err("the action set file is larger than 8 MiB".into()); - } - if is_aia(&bytes) { - return load_aia(app, json!({ "name": path, "dataBase64": vectorcraft_format::base64_encode(&bytes) })); - } - let stem = std::path::Path::new(&path).file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default(); - (String::from_utf8(bytes).map_err(|_| "not an action set file")?, stem) - } - }; - let mut set = read_set(&text, if stem.is_empty() { "Actions" } else { &stem })?; + let (mut set, aia) = read_file(app, p)?; set.name = free_set_name(&app.ui.action_sets, &set.name); - // A number added to the name can make a file at the limit larger than it. + // A number added to the name can make a file at the limit larger than it, and the set of an + // `.aia` file can save larger than the file read. super::edit_keeps_set_loadable(app, None, &set)?; - let (unknown, unknown_count, first) = unknown_commands(&set); - let (name, actions) = (set.name.clone(), set.actions.len()); + let answer = loaded(app, &set, app.ui.action_sets.len(), aia); app.ui.action_sets.push(set); - let mut answer = json!({ "set": app.ui.action_sets.len() - 1, "name": name, "actions": actions }); - if let Some((action, step, command)) = first { - app.status(crate::i18n::msg_n( - unknown_count as u64, - "Loaded “{name}”: {n} step has an unknown command and was kept: “{action}”, step {step}, `{command}`", - "Loaded “{name}”: {n} steps have unknown commands and were kept; the first: “{action}”, step {step}, `{command}`", - &[ - ("name", &super::shown_text(&name)), - ("action", &super::shown_text(&action)), - ("step", &step), - ("command", &super::shown_text(&command)), - ], - )); - answer["unknownCommands"] = json!(unknown); - answer["unknownCount"] = json!(unknown_count); + Ok(answer) +} + +/// `ui.actionSet.replace {path? | data?}`: Replace Actions…. Reads an action set file as +/// [`load_set`] does, from `path`, a picked file or the file's text `data`, with the same formats, +/// limits and errors, and replaces every set in the panel with the file's set, which keeps its +/// name. The set becomes current and selected, and the panel clears what named the old sets as +/// [`super::reset`] does. When the panel already holds only a set that saves alike, shown that +/// way, nothing changes and the set keeps its ids. Omitted params (`null`) count as `{}`. Params +/// of another type, another key or a `path` or `data` that is not a string is an error, and so is a replace +/// while an action records or plays (also while it waits at a stop). On any error, a canceled +/// pick included, nothing changes. No undo step is recorded → `{changed, set: 0, name, actions}`, +/// with what [`load_set`] reports of left-out steps and unknown commands. +pub fn replace_set(app: &mut VectorcraftApp, p: &Value) -> Result { + match p { + Value::Null => {} + Value::Object(m) => { + if let Some(key) = m.keys().find(|k| !matches!(k.as_str(), "path" | "data")) { + let keys = "path, data"; + return Err(format!("unknown parameter `{key}`; the command takes: {keys}")); + } + if let Some(key) = ["path", "data"].into_iter().find(|k| m.get(*k).is_some_and(|v| !v.is_string())) { + return Err(format!("`{key}` must be a string")); + } + } + got => return Err(format!("the params must be an object, not {got}")), } + if app.ui.recording.is_some() { + return Err("an action is already recording".into()); + } + if app.ui.action_playing.is_some() { + return Err("an action is already playing".into()); + } + let (set, aia) = read_file(app, p)?; + super::edit_keeps_set_loadable(app, None, &set)?; + let mut answer = loaded(app, &set, 0, aia); + answer["changed"] = json!(super::replace_sets(app, vec![set])); Ok(answer) } diff --git a/crates/ui-egui/src/panels/appearance.rs b/crates/ui-egui/src/panels/appearance.rs index 308b8f3602..db11c16915 100644 --- a/crates/ui-egui/src/panels/appearance.rs +++ b/crates/ui-egui/src/panels/appearance.rs @@ -466,7 +466,7 @@ fn edit_tip(resp: egui::Response, name: &egui::Response) -> egui::Response { pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let t = Tokens::get(ui.ctx()); let node = first_subject(app); - let sel = current_sel(app, ui.ctx(), node.as_ref()); + let sel = current_sel(app, ui.ctx(), node.as_deref()); let hide_thumb: bool = pstate(ui.ctx(), "ap-hide-thumb"); widgets::list_box(ui, |ui| { ui.spacing_mut().item_spacing.y = 0.0; @@ -519,10 +519,10 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { Some(n) => stack(app, ui, n, sel, r, None), None => default_stack(app, ui), } - // Spacer row like Illustrator's empty tail. + // An empty spacer row at the end of the list. ui.allocate_exact_size(vec2(ui.available_width(), 10.0), Sense::hover()); }); - bottom(app, ui, node.as_ref(), sel); + bottom(app, ui, node.as_deref(), sel); delete_key(app, ui); // A row's popup, beside the panel (in the same window when the panel floats). let panel = ui.max_rect(); @@ -543,13 +543,13 @@ fn delete_key(app: &mut VectorcraftApp, ui: &mut Ui) { let keys = super::has_row_keys(&ctx, ROW_KEYS) && !pressed_outside; super::set_row_keys(&ctx, ROW_KEYS, keys); let node = first_subject(app); - let sel = current_sel(app, &ctx, node.as_ref()); + let sel = current_sel(app, &ctx, node.as_deref()); if keys && sel.deletable() && ctx.memory(|m| m.focused().is_none()) && ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Delete) || i.consume_key(egui::Modifiers::NONE, egui::Key::Backspace)) { - delete_selected(app, ui, node.as_ref(), sel); + delete_selected(app, ui, node.as_deref(), sel); } } @@ -564,10 +564,10 @@ fn thumbnail_drag(ui: &mut Ui, th: Rect, id: NodeId) { } /// The object the panel lists: the targeted layer, group or object (`layer.target`), else the -/// first selected one. -fn first_subject(app: &VectorcraftApp) -> Option { +/// first selected one, as the `Arc` the document holds. +fn first_subject(app: &VectorcraftApp) -> Option> { let st = app.session.active()?; - st.selection.subjects().first().and_then(|id| st.doc.node(*id)).cloned() + st.selection.subjects().first().and_then(|id| super::layers::node_arc(&st.doc, *id)) } /// The selection as the Control bar and the object row name it: "No Selection", the kind ("Path", @@ -1680,7 +1680,7 @@ pub(crate) fn fx_menu(app: &mut VectorcraftApp, ui: &mut Ui) { pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { let node = first_subject(app); let has = node.is_some(); - let sel = current_sel(app, ui.ctx(), node.as_ref()); + let sel = current_sel(app, ui.ctx(), node.as_deref()); if menu_item(ui, tl!("Add New Fill"), has, false) { app.run("appearance.addFill", json!({})).ok(); } @@ -1689,10 +1689,10 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { } ui.separator(); if menu_item(ui, tl!("Duplicate Item"), has && sel.editable(), false) { - duplicate_selected(app, ui, node.as_ref(), sel); + duplicate_selected(app, ui, node.as_deref(), sel); } if menu_item(ui, tl!("Remove Item"), has && sel.deletable(), false) { - delete_selected(app, ui, node.as_ref(), sel); + delete_selected(app, ui, node.as_deref(), sel); } if menu_item(ui, tl!("Clear Appearance"), has, false) { app.run("appearance.clear", json!({})).ok(); diff --git a/crates/ui-egui/src/panels/appearance/tests.rs b/crates/ui-egui/src/panels/appearance/tests.rs index 1b26bd3436..2d3350443b 100644 --- a/crates/ui-egui/src/panels/appearance/tests.rs +++ b/crates/ui-egui/src/panels/appearance/tests.rs @@ -87,7 +87,7 @@ fn fx_button(window: &PopupWindow) -> egui::Pos2 { fn draw_bottom_bar(app: &mut VectorcraftApp, ui: &mut Ui) { let node = first_subject(app); - bottom(app, ui, node.as_ref(), Sel::None); + bottom(app, ui, node.as_deref(), Sel::None); } /// The Add New Effect popup has one row per effect group, plug-in groups included. @@ -144,8 +144,8 @@ fn a_duplicate_highlights_the_copies_above_the_originals() { let duplicate = |app: &mut VectorcraftApp| { let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { let node = first_subject(app); - let sel = current_sel(app, ui.ctx(), node.as_ref()); - duplicate_selected(app, ui, node.as_ref(), sel); + let sel = current_sel(app, ui.ctx(), node.as_deref()); + duplicate_selected(app, ui, node.as_deref(), sel); }); out.textures_delta.clear(); }; @@ -173,7 +173,7 @@ fn a_duplicate_highlights_the_copies_above_the_originals() { set_pstate(&ctx, "ap-multi", Highlight { owner, rows: Rows::Effects(None), order: vec![0], anchor: Some(0), active: Some(0) }); let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { let n = first_subject(&app).unwrap(); - let sel = current_sel(&app, ui.ctx(), Some(&n)); + let sel = current_sel(&app, ui.ctx(), Some(&*n)); app.run("effect.duplicate", json!({"item": null, "indices": [4]})).unwrap(); highlight_copies(&mut app, ui.ctx(), &n, sel, Rows::Effects(None), &[4]); }); @@ -197,7 +197,7 @@ fn removing_items_keeps_a_surviving_item_opacity_row_selected() { let remove = |app: &mut VectorcraftApp, k: usize| { let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { let n = first_subject(app).unwrap(); - let sel = current_sel(app, ui.ctx(), Some(&n)); + let sel = current_sel(app, ui.ctx(), Some(&*n)); app.run("appearance.removeItem", json!({ "indices": [k] })).unwrap(); highlight_after_removal(app, ui.ctx(), &n, sel, Rows::Items, &[k]); }); @@ -228,9 +228,9 @@ fn deleting_an_opacity_row_sets_it_back_to_default() { let delete = |app: &mut VectorcraftApp| { let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { let node = first_subject(app); - let sel = current_sel(app, ui.ctx(), node.as_ref()); + let sel = current_sel(app, ui.ctx(), node.as_deref()); assert!(sel.deletable() && !sel.editable(), "{sel:?}"); - delete_selected(app, ui, node.as_ref(), sel); + delete_selected(app, ui, node.as_deref(), sel); }); out.textures_delta.clear(); }; @@ -1016,3 +1016,27 @@ fn a_mixed_selection_lists_what_its_objects_share() { run(&mut app, "select.set", json!({"ids": [ids[0].clone(), t]})); assert_eq!(frame(&mut app).iter().find(|t| *t != "?").map(String::as_str), Some("Mixed Objects")); } + +/// The panel's subject is the `Arc` the document holds for the selected object, a targeted group +/// or a targeted layer, not a copy of it; nothing with nothing selected. +#[test] +fn first_subject_is_the_node_the_document_holds() { + let mut app = app_with_a_selected_rectangle(); + let held = |app: &VectorcraftApp| { + let st = app.session.active().unwrap(); + super::super::layers::node_arc(&st.doc, st.selection.subjects()[0]).unwrap() + }; + assert!(std::sync::Arc::ptr_eq(&first_subject(&app).expect("the rectangle"), &held(&app)), "the selected object"); + let group = app.run("object.group", json!({})).unwrap()["id"].clone(); + app.run("layer.target", json!({ "id": group })).unwrap(); + let n = first_subject(&app).expect("the group"); + assert_eq!(n.id.0, group.as_u64().unwrap()); + assert!(std::sync::Arc::ptr_eq(&n, &held(&app)), "the targeted group"); + let layer = app.session.active().unwrap().doc.layers[0].id; + app.run("layer.target", json!({ "id": layer.0 })).unwrap(); + let n = first_subject(&app).expect("the layer"); + assert_eq!(n.id, layer); + assert!(std::sync::Arc::ptr_eq(&n, &held(&app)), "the targeted layer"); + app.run("select.none", json!({})).unwrap(); + assert!(first_subject(&app).is_none(), "nothing selected"); +} diff --git a/crates/ui-egui/src/panels/artboards.rs b/crates/ui-egui/src/panels/artboards.rs index b7f9e25df5..94560b9f76 100644 --- a/crates/ui-egui/src/panels/artboards.rs +++ b/crates/ui-egui/src/panels/artboards.rs @@ -149,11 +149,14 @@ pub(crate) fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui, options: bool, // The W/H link sits between W and H, but is made after H so Tab goes from W straight to H and // finds the link after it, as in the object Control bar. let mut link_room = None; + let mut labels = Vec::with_capacity(4); for (k, lbl, v) in [("x", "X:", rp.x - origin.x), ("y", "Y:", rp.y - origin.y), ("width", "W:", r.width()), ("height", "H:", r.height())] { if k == "height" { link_room = Some(super::transform::constrain_link_room(ui)); } - widgets::field_label(ui, egui::RichText::new(tl!(lbl)).size(12.0).color(t.text_dim)); + // A click on the label opens the Transform panel, as the Transform link does; a drag scrubs. + let text = egui::RichText::new(tl!(lbl)).size(12.0).color(t.text).underline(); + labels.push(widgets::field_panel_label(ui, text).on_hover_text(tl!("Transform options"))); let set = if matches!(k, "width" | "height") { widgets::size_field(ui, ("cb-ab", k), Some(v), units, 80.0) } else { @@ -173,6 +176,10 @@ pub(crate) fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui, options: bool, let id = ui.scope_id().with("cb-ab-constrain-link"); super::transform::constrain_link_at(app, ui, ui.interact(room, id, egui::Sense::click())); } + // After the fields, which each take the label before them as their own. + for label in &labels { + super::transform::popover(app, label); + } true } diff --git a/crates/ui-egui/src/panels/artboards/tests.rs b/crates/ui-egui/src/panels/artboards/tests.rs index b53faf87c0..b52d1da682 100644 --- a/crates/ui-egui/src/panels/artboards/tests.rs +++ b/crates/ui-egui/src/panels/artboards/tests.rs @@ -957,6 +957,32 @@ fn the_control_bar_resizes_the_active_artboard_about_the_reference_point() { assert_eq!(boards(&app).0, want, "Artboard 2 widens from its left edge"); } +/// With the Artboard tool, a click on the Control bar's X:, Y:, W: or H: label opens the Transform +/// panel's artboard fields in a popover under it, as the Transform link does, and a second click +/// closes it; the artboards stay as they were and no field takes the keyboard. +#[test] +fn the_artboard_control_bars_x_y_w_and_h_labels_open_the_transform_panel() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100, "units": "Points"})).unwrap(); + app.select_tool("artboard"); + let ctx = bar_context(); + let before = boards(&app); + // The bar draws one W:, and the popover's artboard fields another. + let ws = |texts: &[(String, egui::Rect)]| texts.iter().filter(|(t, _)| t == "W:").count(); + for label in ["X:", "Y:", "W:", "H:"] { + let texts = bar_texts(&mut app, &ctx); + assert_eq!(ws(&texts), 1, "{label}: the bar alone: {texts:?}"); + let at = text_rect(&texts, label).center(); + bar_click(&mut app, &ctx, at); + let texts = bar_texts(&mut app, &ctx); + assert_eq!(ws(&texts), 2, "{label}: the Transform panel opens: {texts:?}"); + assert_eq!(ctx.memory(|m| m.focused()), None, "{label}: no field took the keyboard"); + bar_click(&mut app, &ctx, at); + assert_eq!(ws(&bar_texts(&mut app, &ctx)), 1, "{label}: a second click closes it"); + } + assert_eq!(boards(&app), before, "the artboards stay"); +} + /// The Control bar's Portrait and Landscape buttons swap the active artboard's width and height, /// its top-left corner staying put, in one undo step each. #[test] diff --git a/crates/ui-egui/src/panels/blend.rs b/crates/ui-egui/src/panels/blend.rs index ebc182d238..9991e0b37a 100644 --- a/crates/ui-egui/src/panels/blend.rs +++ b/crates/ui-egui/src/panels/blend.rs @@ -55,13 +55,10 @@ fn available(app: &VectorcraftApp, cmd: &str) -> bool { /// Selection counts as its blend. fn selects_blend_without_spine(app: &VectorcraftApp) -> bool { let Some(st) = app.session.active().filter(|st| st.selection.symbol_part.is_none()) else { return false }; + let mut find = st.doc.nearest_finder(); st.selection.objects.iter().any(|id| { - let ancestry = st.doc.ancestry(*id).unwrap_or_default(); - let blend = ancestry.iter().rev().find_map(|a| match st.doc.node(*a).map(|n| &n.kind) { - Some(NodeKind::Blend { spec, .. }) => Some(spec.no_spine), - _ => None, - }); - blend == Some(true) + let blend = find.nearest(*id, |n| matches!(n.kind, NodeKind::Blend { .. })); + matches!(blend.map(|n| &n.kind), Some(NodeKind::Blend { spec, .. }) if spec.no_spine) }) } diff --git a/crates/ui-egui/src/panels/brushes.rs b/crates/ui-egui/src/panels/brushes.rs index 0b540a4ba5..8f98e9291f 100644 --- a/crates/ui-egui/src/panels/brushes.rs +++ b/crates/ui-egui/src/panels/brushes.rs @@ -23,7 +23,7 @@ use vectorcraft_engine::cmd::swatchlib::LibraryInfo; use super::library_panel::{self, LibraryKind, LibraryRef, Row}; use super::memo::Memo; -use super::{first_selected, pstate, set_pstate}; +use super::{first_node, pstate, set_pstate}; use crate::VectorcraftApp; use crate::dialogs::brush_options; use crate::menus::Item; @@ -168,7 +168,7 @@ pub(crate) fn definition_chip(ui: &Ui, r: egui::Rect, st: Option<&DocState>, def } fn selected_brush(app: &VectorcraftApp) -> Option { - first_selected(app).and_then(|n| n.appearance.stroke().and_then(|s| s.brush.clone())) + first_node(app).and_then(|n| n.appearance.stroke().and_then(|s| s.brush.clone())) } /// What the panel's last click was made with: the document, its selected objects and the current @@ -523,6 +523,12 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { { app.status(e); } + // The selected brushed paths' own settings: the brush stays as it is. + if menu_item(ui, tl!("Options of Selected Object…"), brush_options::object_available(app), false) + && let Err(e) = app.run("ui.brushObjectOptions", json!({})) + { + app.status(e); + } ui.separator(); // Selects the brushes no stroke paints with, for Delete Brush and Duplicate Brush. if menu_item(ui, tl!("Select All Unused"), app.session.active().is_some(), false) diff --git a/crates/ui-egui/src/panels/character.rs b/crates/ui-egui/src/panels/character.rs index e9c497a4ad..aae2e21e28 100644 --- a/crates/ui-egui/src/panels/character.rs +++ b/crates/ui-egui/src/panels/character.rs @@ -282,14 +282,13 @@ pub(crate) fn format(app: &mut VectorcraftApp, p: Value) { /// has selected (the whole text when nothing is selected) while it edits text, else /// `text.setFormat` on the selected stories ([`selected_stories`]). pub(crate) fn run_format(app: &mut VectorcraftApp, mut p: Value) -> Result { - let Some((id, a, b)) = text_editing(app) else { + let Some((id, a, b)) = text_editing_kept(app)? else { target_selected_stories(app, &mut p); return app.run("text.setFormat", p); }; if let Some(first) = text_story(app).and_then(|story| story.first().copied()) { return story_style(app, first, p); } - end_typing(app); p["id"] = json!(id.0); if b > a { p["start"] = json!(a); @@ -340,7 +339,8 @@ fn char_cmd(app: &mut VectorcraftApp, cmd: &str, mut p: Value) { /// and Optical set no space (#5111); nowhere to set at an empty line's start. Else it is a /// character attribute like the others: the selected range, or all the text. fn set_kerning(app: &mut VectorcraftApp, value: Value) { - let Some((id, a, b)) = text_editing(app) else { + let Ok(editing) = text_editing_kept(app) else { return }; + let Some((id, a, b)) = editing else { format(app, json!({"kerning": value})); return; }; @@ -350,7 +350,6 @@ fn set_kerning(app: &mut VectorcraftApp, value: Value) { } let Some(NodeKind::Text(t)) = app.session.active().and_then(|st| st.doc.node(id)).map(|n| &n.kind) else { return }; let Some((target, before)) = vectorcraft_text::edit::caret_kerning_target(&t.plain_text(), a) else { return }; - end_typing(app); let params = if before { json!({"id": id.0, "start": target.start, "end": target.end, "kerningBefore": value.as_f64().unwrap_or(0.0)}) } else { @@ -484,12 +483,14 @@ pub(crate) fn toggle_face(app: &mut VectorcraftApp, face: Face) -> Result &'static str { match self { Field::FontName => "ch-font", + Field::FontSize => "ch-size", Field::Kerning => "ch-kern", Field::Tracking => "ch-track", } @@ -507,17 +509,19 @@ impl Field { fn name(self) -> &'static str { match self { Field::FontName => "fontName", + Field::FontSize => "fontSize", Field::Kerning => "kerning", Field::Tracking => "tracking", } } } -/// `type.highlightFontName`, `type.highlightKerning` and `type.highlightTracking`: show the -/// Character panel if it is hidden (a shown one is activated, so its floating window comes -/// forward), and give `field` the keyboard focus when the panel next draws it, a number field with -/// its value selected (typing replaces it, Enter applies it). Without selected type or text the -/// Type tool edits, the panel shows, nothing takes the focus and the command fails. → `{field}`. +/// `type.highlightFontName`, `type.highlightFontSize`, `type.highlightKerning` and +/// `type.highlightTracking`: show the Character panel if it is hidden (a shown one is activated, +/// so its floating window comes forward), and give `field` the keyboard focus when the panel next +/// draws it, a number field with its value selected (typing replaces it, Enter applies it). +/// Without selected type or text the Type tool edits, the panel shows, nothing takes the focus and +/// the command fails. → `{field}`. pub(crate) fn highlight(app: &mut VectorcraftApp, field: Field) -> Result { // `window.panel` would hide a floating panel in front of its window, or an open flyout. if crate::panel_docking::visible(&app.ui, "character") { @@ -538,19 +542,18 @@ pub(crate) fn highlight(app: &mut VectorcraftApp, field: Field) -> Result Result { text_style(app).ok_or("select some type first")?; let on = shared(app, |s| s.underline) != Some(true); - format(app, json!({"underline": on})); + run_format(app, json!({"underline": on}))?; Ok(json!(on)) } /// `text.setRangeStyle` with `p` on the range the Type tool has selected (the whole text when /// nothing is selected). Does nothing unless the Type tool edits text. pub(crate) fn range_style(app: &mut VectorcraftApp, p: Value) { - let Some((id, a, b)) = text_editing(app) else { return }; + let Ok(Some((id, a, b))) = text_editing_kept(app) else { return }; if let Some(first) = text_story(app).and_then(|story| story.first().copied()) { story_style(app, first, p).ok(); return; } - end_typing(app); let mut q = p; q["id"] = json!(id.0); if b > a { @@ -574,6 +577,15 @@ pub(crate) fn text_editing(app: &VectorcraftApp) -> Option<(NodeId, usize, usize Some((id, g("start"), g("end"))) } +/// [`text_editing`] after [`end_typing`], for an edit of the text: the selection is read in the +/// text with the typing applied, which Real-time Drawing off leaves unapplied until then. When the +/// typing can't be kept, the error (also shown in the status bar), so the edit stops instead of +/// acting on a selection in the text without the typing. +pub(crate) fn text_editing_kept(app: &mut VectorcraftApp) -> Result, String> { + try_end_typing(app)?; + Ok(text_editing(app)) +} + /// The frames of the threaded story whose whole text the Type tool has selected after Select All, /// in the order of the edited frame's thread as the document holds it now; `None` when its /// selection is in one type object. @@ -701,13 +713,25 @@ fn story_style(app: &mut VectorcraftApp, first: NodeId, mut p: Value) -> Result< app.run("text.setRangeStyle", p) } -/// Close the Type tool's typing session (one undo step) before another command edits the text. +/// Close the Type tool's typing session (one undo step) before another command edits the text. The +/// typing Real-time Drawing off left unapplied is applied first; when it can't be kept, the error +/// shows and the session goes on. pub(crate) fn end_typing(app: &mut VectorcraftApp) { + try_end_typing(app).ok(); +} + +/// [`end_typing`] that also returns the error when the typing can't be kept. +fn try_end_typing(app: &mut VectorcraftApp) -> Result<(), String> { if app.session.tool_options().get("typing").and_then(Value::as_bool) == Some(true) { + if let Err(e) = app.keep_typing() { + app.status(e.clone()); + return Err(e); + } app.session.set_tool_option("commitTyping", &json!(true)); app.session.commit_interaction().ok(); app.sync_views(); } + Ok(()) } static CTX: OnceLock = OnceLock::new(); @@ -716,7 +740,8 @@ static CTX: OnceLock = OnceLock::new(); static CLIP: Mutex = Mutex::new(String::new()); static CLIP_RUNS: Mutex> = Mutex::new(None); -fn text_copy(app: &mut VectorcraftApp) -> bool { +/// Copy the Type tool's selected text (with `cut`, for a Cut, whose caller then deletes it). +fn text_copy(app: &mut VectorcraftApp, cut: bool) -> bool { let Some((id, a, b)) = text_editing(app) else { return false }; let story = text_story(app); // An empty selection has nothing to copy, unless the story's text is in the other frames. @@ -744,7 +769,7 @@ fn text_copy(app: &mut VectorcraftApp) -> bool { // plain-text copy would replace its formats, so let the publisher provide both text and // rich art. Paste on the canvas can then keep the runs after Type editing ends. if app.services.system_clipboard.is_some() { - app.publish_clipboard(); + app.publish_clipboard(cut); return true; } } @@ -815,10 +840,10 @@ pub(crate) fn intercept_text_command(app: &mut VectorcraftApp, id: &str) -> Opti } match id { "edit.copy" => { - text_copy(app); + text_copy(app, false); } "edit.cut" => { - if text_copy(app) { + if text_copy(app, true) { text_key(app, ToolKey::Delete, Mods::default()); } } @@ -909,10 +934,10 @@ pub(crate) fn apply_type_input(app: &mut VectorcraftApp, t: TextInput) { match t { TextInput::Key(k, m) => text_key(app, k, m), TextInput::Copy => { - text_copy(app); + text_copy(app, false); } TextInput::Cut => { - if text_copy(app) { + if text_copy(app, true) { text_key(app, ToolKey::Delete, Mods::default()); } } @@ -1318,9 +1343,10 @@ pub(crate) fn axis_sliders(app: &mut VectorcraftApp, ui: &mut Ui, face: &vectorc /// Set Variable Font settings `axes` on the text the panel acts on, live while a slider drags. fn axes_cmd(app: &mut VectorcraftApp, axes: Value, phase: widgets::Live) { - match text_editing(app) { - Some((id, a, b)) => { - end_typing(app); + match text_editing_kept(app) { + // The typing can't be kept (the error shows): nothing is set. + Err(_) => {} + Ok(Some((id, a, b))) => { let mut q = json!({"id": id.0, "fontAxes": axes}); // After Select All in threaded text: every frame of the story. if let Some(first) = text_story(app).and_then(|story| story.first().copied()) { @@ -1332,7 +1358,7 @@ fn axes_cmd(app: &mut VectorcraftApp, axes: Value, phase: widgets::Live) { } super::live_run(app, "Character", "text.setRangeStyle", q, phase); } - None => { + Ok(None) => { let mut p = json!({ "fontAxes": axes }); target_selected_stories(app, &mut p); super::live_run(app, "Character", "text.setFormat", p, phase); diff --git a/crates/ui-egui/src/panels/character/tests.rs b/crates/ui-egui/src/panels/character/tests.rs index 4b0e96679f..9863091461 100644 --- a/crates/ui-egui/src/panels/character/tests.rs +++ b/crates/ui-egui/src/panels/character/tests.rs @@ -343,6 +343,57 @@ fn highlight_commands_focus_the_font_kerning_and_tracking_fields() { assert_eq!(app.character_focus, None); } +/// Type › Size › Other… (Highlight Font Size) shows the Character panel and gives its Font Size +/// field the keyboard focus with the value selected: what is typed replaces it, Enter applies it +/// as one undo step, and a selection of different sizes takes the one size typed into the blank +/// field. Without selected type the panel shows, the command fails and nothing takes the focus. +#[test] +fn highlight_font_size_focuses_the_font_size_field() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let a = app.run("text.create", json!({"x": 20, "y": 50, "text": "AVAX", "size": 12})).unwrap()["id"].clone(); + let b = app.run("text.create", json!({"x": 20, "y": 120, "text": "Wave", "size": 20})).unwrap()["id"].clone(); + let ctx = egui::Context::default(); + let frame = |app: &mut VectorcraftApp, events: Vec| { + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + }; + let typed = |text: &str| { + let enter = egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + vec![egui::Event::Text(text.into()), enter] + }; + let size = |app: &VectorcraftApp| shared(app, |s| s.size); + app.run("select.set", json!({"ids": [a.clone()]})).unwrap(); + assert_eq!(app.run("type.highlightFontSize", json!({})).unwrap(), json!({"field": "fontSize"})); + assert!(crate::panel_docking::showing(&app.ui, "character"), "the panel shows"); + frame(&mut app, vec![]); + assert_eq!(app.character_focus, None, "the Font Size field took the focus"); + frame(&mut app, typed("33")); + assert_eq!(size(&app), Some(33.0), "typing replaced the size"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(size(&app), Some(12.0), "one undo step restores the size"); + // Choosing Other again while the field holds typed text that is not applied selects all of it. + app.run("type.highlightFontSize", json!({})).unwrap(); + frame(&mut app, vec![]); + frame(&mut app, vec![egui::Event::Text("999".into())]); + app.run("type.highlightFontSize", json!({})).unwrap(); + frame(&mut app, vec![]); + frame(&mut app, typed("18")); + assert_eq!(size(&app), Some(18.0), "typing replaced the text typed before"); + ctx.memory_mut(|m| m.stop_text_input()); + // Different sizes: the field is blank, and the size typed applies to every selected object. + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + assert_eq!(size(&app), None); + app.run("type.highlightFontSize", json!({})).unwrap(); + frame(&mut app, vec![]); + frame(&mut app, typed("16")); + assert_eq!(size(&app), Some(16.0), "both objects take the size typed"); + // No type selected: the panel shows, the command fails and nothing is armed. + app.run("select.none", json!({})).unwrap(); + assert!(app.run("type.highlightFontSize", json!({})).is_err()); + assert_eq!(app.character_focus, None); +} + /// A variable font gets the Variable Font button, which opens one slider per axis named as the /// font names it; a drag along one sets that axis of the selected type in one undo step. #[test] @@ -1685,7 +1736,7 @@ fn copy_and_cut_take_a_story_that_left_the_edited_frame() { // A story that holds no text has nothing to copy, so Cut does not run its delete. app.run("select.all", json!({})).unwrap(); assert_eq!(text_story(&app).map(|frames| frames.len()), Some(3)); - assert!(!text_copy(&mut app)); + assert!(!text_copy(&mut app, false)); } } } diff --git a/crates/ui-egui/src/panels/color.rs b/crates/ui-egui/src/panels/color.rs index 28fb618dc9..c6a96b62d1 100644 --- a/crates/ui-egui/src/panels/color.rs +++ b/crates/ui-egui/src/panels/color.rs @@ -231,19 +231,23 @@ pub(crate) const WEB_WARNING: (&str, &str) = ("dc-cube", "Out of Web Color Warni /// The out-of-gamut warning: its icon and tooltip. pub(crate) const GAMUT_WARNING: (&str, &str) = ("dc-gamut", "Out of Gamut Warning"); -/// A warning icon with the corrected colour beside it. Returns true when the colour is clicked. +/// A warning icon with the corrected colour beside it. Returns true when the icon or the colour is +/// clicked. pub(crate) fn warning_chip(ui: &mut Ui, (icon, warning): (&str, &str), fix: &Color) -> bool { let t = Tokens::get(ui.ctx()); + let tip = crate::i18n::fmt( + tl!("{warning}: click to correct to the closest color ({hex})"), + &[("warning", tl!(warning)), ("hex", &format!("#{}", hex_digits(fix).to_ascii_lowercase()))], + ); ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = 3.0; - icons::icon(ui, icon, 16.0, t.icon).on_hover_text(tl!(warning)); + let icon = icons::icon(ui, icon, 16.0, t.icon).interact(Sense::click()); + icon.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!(warning))); let (r, resp) = ui.allocate_exact_size(vec2(16.0, 16.0), Sense::click()); - widgets::swatch_tile(ui, r, &Paint::solid(*fix), false, resp.hovered()); - resp.on_hover_text(crate::i18n::fmt( - tl!("{warning}: click to correct to the closest color ({hex})"), - &[("warning", tl!(warning)), ("hex", &format!("#{}", hex_digits(fix).to_ascii_lowercase()))], - )) - .clicked() + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &tip)); + widgets::swatch_tile(ui, r, &Paint::solid(*fix), false, resp.hovered() || icon.hovered()); + let icon = icon.on_hover_text(&tip).clicked(); + resp.on_hover_text(&tip).clicked() || icon }) .inner } diff --git a/crates/ui-egui/src/panels/color_themes.rs b/crates/ui-egui/src/panels/color_themes.rs index d736fa415b..3590d70812 100644 --- a/crates/ui-egui/src/panels/color_themes.rs +++ b/crates/ui-egui/src/panels/color_themes.rs @@ -1,6 +1,8 @@ //! Color Themes panel (local only): the Create tab makes a five-colour theme on a harmony wheel (a //! harmony rule from the selected colour, or Custom: each colour moves on its own; with a rule the -//! colours move together), the My Themes tab lists the themes saved in the preferences. Themes are +//! colours move together; the selected color is also edited in its hex field or with CMYK, RGB, Lab +//! or HSB sliders), the My Themes tab lists the themes saved in the preferences (the panel +//! menu's Show Find Field adds a field that lists only the themes whose names hold its text). Themes are //! saved, edited, deleted and added to Swatches as colour groups through `colorTheme.*`; the theme //! being made is panel state. @@ -10,8 +12,10 @@ use vectorcraft_color::Color; use vectorcraft_color::harmony::{Harmony, THEME_SIZE, move_on_wheel}; use vectorcraft_engine::cmd::colortheme::ColorTheme; -use super::{active_paint, c32, color_json, empty_state, pstate, set_pstate}; +use super::color::{Mode, components, from_components, track_color}; +use super::{active_paint, c32, color_json, empty_state, proxy_cmd, pstate, set_pstate}; use crate::VectorcraftApp; +use crate::dialogs::recolor::slider_cell; use crate::theme::{self, Tokens}; use crate::widgets::{self, menu_item}; @@ -21,6 +25,11 @@ const DEFAULT_RULE: Harmony = Harmony::Analogous2; const DEFAULT_BASE: Color = Color::Rgb { r: 0.1, g: 0.55, b: 0.6 }; /// Diameter of the harmony wheel. const WHEEL: f32 = 150.0; +/// The color modes of the selected color's sliders, in the order the Color Mode menu lists them. +const SLIDER_MODES: [Mode; 4] = [Mode::Cmyk, Mode::Rgb, Mode::Lab, Mode::Hsb]; +/// Widths of a slider's label and of its number field (the field's width is the Recolor dialog's). +const SLIDER_LABEL_W: f32 = 12.0; +const SLIDER_FIELD_W: f32 = 48.0; /// The theme being made on the Create tab. #[derive(Clone, Debug, Default, PartialEq)] @@ -90,9 +99,35 @@ fn set_draft(ctx: &egui::Context, d: Draft) { set_pstate(ctx, "ct-draft", Some(d)); } -/// The saved theme picked on the My Themes tab. +/// The saved theme picked on the My Themes tab, while the list shows it: a theme that the find +/// field hides stays picked, but nothing acts on it until the list shows it again. fn picked(app: &VectorcraftApp, ctx: &egui::Context) -> Option { - pstate::>(ctx, "ct-picked").filter(|n| app.session.prefs.color_themes.iter().any(|t| t.name == *n)) + let q = query(ctx); + pstate::>(ctx, "ct-picked").filter(|n| app.session.prefs.color_themes.iter().any(|t| t.name == *n && matches(&t.name, &q))) +} + +/// The My Themes find field's text, kept while the panel menu hides the field. +fn find_id() -> egui::Id { + egui::Id::unique("ct-find") +} + +/// Whether the panel menu's Show Find Field shows the find field (off in a new session). +fn show_find(ctx: &egui::Context) -> bool { + pstate(ctx, "ct-show-find") +} + +/// The find field's text, trimmed and lowercased; empty while the field is hidden. +fn query(ctx: &egui::Context) -> String { + if !show_find(ctx) { + return String::new(); + } + ctx.data(|d| d.get_temp::(find_id())).unwrap_or_default().trim().to_lowercase() +} + +/// Whether the find field lists theme `name` for `query` (trimmed and lowercased): its name holds +/// the text anywhere, in any letter case. An empty query lists every theme. +fn matches(name: &str, query: &str) -> bool { + query.is_empty() || name.to_lowercase().contains(query) } /// The tab shown: 0 Create, 1 My Themes. @@ -100,6 +135,78 @@ fn tab(ctx: &egui::Context) -> usize { pstate(ctx, "ct-tab") } +/// The color mode of the sliders: the one last picked from their Color Mode menu while the app +/// runs, or else the selected color's own model (HSB for a gray). Picking a mode changes no color. +fn slider_mode(ctx: &egui::Context, c: Option<&Color>) -> Mode { + pstate::>(ctx, "ct-mode").unwrap_or_else(|| match c.map(Mode::of) { + Some(m @ (Mode::Cmyk | Mode::Rgb | Mode::Lab)) => m, + _ => Mode::Hsb, + }) +} + +/// The slider values a slider edit last set: the selected place and the color they made in +/// `mode`. While those still hold, the sliders show `v` as it was set, so an edit of one slider +/// leaves the others' numbers as they were instead of converting them back from the color. +#[derive(Clone, Debug, PartialEq)] +struct Held { + sel: usize, + color: Color, + mode: Mode, + v: Vec, +} + +/// The numbers the sliders show for the selected color of `d` in `mode`. +fn slider_values(ctx: &egui::Context, d: &Draft, mode: Mode) -> Option> { + let c = d.colors.get(d.sel)?; + let held = + pstate::>(ctx, "ct-held").filter(|h| h.sel == d.sel && h.color == *c && h.mode == mode && h.v.len() == mode.labels().len()); + Some(held.map_or_else(|| components(mode, c), |h| h.v)) +} + +/// The Color Mode menu (CMYK, RGB, Lab and HSB) and its sliders, each a rail and a number field, for +/// the selected color of `d`. An edit sets the selected color in the menu's mode (an RGB or HSB +/// edit makes it RGB, a CMYK edit CMYK and a Lab edit Lab) as the hex field does: with a rule the +/// theme follows from it as the new base. +fn sliders(ui: &mut Ui, d: &mut Draft) { + let t = Tokens::get(ui.ctx()); + let ctx = ui.ctx().clone(); + let current = slider_mode(&ctx, d.colors.get(d.sel)); + ui.horizontal(|ui| { + ui.label(egui::RichText::new(tl!("Color Mode:")).color(t.text_dim)); + let labels: Vec<&str> = SLIDER_MODES.iter().map(|m| m.label()).collect(); + if let Some(&m) = + widgets::dropdown_named(ui, "ct-mode", Some(tl!("Color Mode:")), current.label(), &labels, 90.0).and_then(|i| SLIDER_MODES.get(i)) + { + set_pstate(&ctx, "ct-mode", Some(m)); + } + }); + ui.add_space(2.0); + let mode = slider_mode(&ctx, d.colors.get(d.sel)); + let Some(comps) = slider_values(&ctx, d, mode) else { return }; + let spacing = 6.0; + let rail = (ui.available_width() - SLIDER_LABEL_W - SLIDER_FIELD_W - 2.0 * spacing - 4.0).max(40.0); + let mut set: Option> = None; + egui::Grid::new("ct-sliders").num_columns(3).spacing([spacing, 4.0]).show(ui, |ui| { + for (n, lbl) in mode.labels().iter().enumerate() { + let v = comps.get(n).copied().unwrap_or(0.0); + let shown = widgets::SliderValue::field(f64::from(v), f64::from(mode.min(n))..=f64::from(mode.max(n)), mode.suffix(n), 0); + let track = |x: f32| c32(&track_color(mode, &comps, n, x)); + if let Some(nv) = slider_cell(ui, ("ct", mode.label(), n), lbl, shown, mode.suffix(n), &track, SLIDER_LABEL_W, rail) { + let mut c2 = comps.clone(); + c2[n] = nv as f32; + set = Some(c2); + } + ui.end_row(); + } + }); + if let Some(v) = set { + d.set_selected(from_components(mode, &v)); + if let Some(&color) = d.colors.get(d.sel) { + set_pstate(&ctx, "ct-held", Some(Held { sel: d.sel, color, mode, v })); + } + } +} + /// Save the theme being made (overwriting the theme it edits); it then edits the saved theme. fn save(app: &mut VectorcraftApp, ctx: &egui::Context) { let mut d = draft(app, ctx); @@ -126,6 +233,17 @@ fn add_draft_to_swatches(app: &mut VectorcraftApp, ctx: &egui::Context) { app.run("swatch.newGroup", json!({ "name": name, "colors": colors_json(&d.colors), "keepModel": true })).ok(); } +/// Paint the active proxy (Fill or Stroke) with the selected colour of the theme being made, in its +/// own model: the selection and the new-art default take it in one paint command, so one undo +/// step, and no step when the art already has it. With characters selected with the Type tool, +/// only those characters take it and the new-art default stays as it was, as with a swatch click. +/// The theme stays as it is. +fn set_active_color(app: &mut VectorcraftApp, d: &Draft) { + if let Some(c) = d.colors.get(d.sel) { + app.run(proxy_cmd(app, false), json!({ "color": color_json(c), "keepModel": true })).ok(); + } +} + pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let ctx = ui.ctx().clone(); ui.horizontal(|ui| { @@ -187,11 +305,18 @@ fn create(app: &mut VectorcraftApp, ui: &mut Ui) { } } ui.add_space(6.0); + sliders(ui, &mut d); + ui.add_space(4.0); ui.horizontal(|ui| { let hex = d.colors.get(d.sel).map(|c| c.to_hex().trim_start_matches('#').to_string()).unwrap_or_default(); if let Some(c) = widgets::hex_field_named(ui, "ct-hex", Some(tl!("Color")), &hex).and_then(|h| Color::from_hex(&h)) { d.set_selected(c); } + let can_set = app.session.active().is_some() && d.colors.get(d.sel).is_some(); + let tip = tl!("Set the current fill or stroke to the selected color"); + if widgets::icon_button_enabled(ui, "paint-bucket", tip, false, can_set, 24.0).clicked() { + set_active_color(app, &d); + } let current = active_paint(app).color(); if widgets::icon_button_enabled(ui, "pipette", tl!("Set the selected color to the current color"), false, current.is_some(), 24.0).clicked() && let Some(c) = current @@ -241,6 +366,12 @@ enum Action { fn my_themes(app: &mut VectorcraftApp, ui: &mut Ui) { let t = Tokens::get(ui.ctx()); let ctx = ui.ctx().clone(); + // The find field lists the saved themes whose names hold its text, in their saved order. + if show_find(&ctx) { + widgets::search_field(ui, find_id(), tl!("Find")); + ui.add_space(4.0); + } + let q = query(&ctx); let pick = picked(app, &ctx); let mut action = None; if app.session.prefs.color_themes.is_empty() { @@ -248,7 +379,11 @@ fn my_themes(app: &mut VectorcraftApp, ui: &mut Ui) { } else { widgets::list_box(ui, |ui| { egui::ScrollArea::vertical().id_salt("ct-list").max_height(300.0).auto_shrink([false, true]).show(ui, |ui| { - for th in &app.session.prefs.color_themes { + let mut shown = app.session.prefs.color_themes.iter().filter(|th| matches(&th.name, &q)).peekable(); + if shown.peek().is_none() { + widgets::dim_label(ui, tl!("No matches.")); + } + for th in shown { let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), 44.0), Sense::hover()); let resp = ui.interact(r, ui.scope_id().with(("ct-theme", &th.name)), Sense::click()); let selected = pick.as_deref() == Some(th.name.as_str()); @@ -340,6 +475,11 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { { delete(app, &ctx, n); } + ui.separator(); + let find = show_find(&ctx); + if menu_item(ui, tl!("Show Find Field"), true, find) { + set_pstate(&ctx, "ct-show-find", !find); + } } else { if menu_item(ui, tl!("Save Theme"), true, false) { save(app, &ctx); @@ -454,6 +594,341 @@ mod tests { frame(&mut app, &ctx); } + /// The texts one frame draws: the panel, or with `menu_only` its panel menu, with `events`. + fn drawn(app: &mut VectorcraftApp, ctx: &egui::Context, menu_only: bool, events: Vec) -> Vec<(String, Rect)> { + crate::i18n::set_current(crate::i18n::Lang::EN); + let screen = Rect::from_min_size(egui::Pos2::ZERO, vec2(320.0, 700.0)); + let input = egui::RawInput { events, screen_rect: Some(screen), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| if menu_only { menu(app, ui) } else { show(app, ui) }); + out.textures_delta.clear(); + fn texts(s: &egui::Shape, out: &mut Vec<(String, Rect)>) { + match s { + egui::Shape::Text(t) => out.push((t.galley.text().to_string(), t.visual_bounding_rect())), + egui::Shape::Vec(v) => v.iter().for_each(|s| texts(s, out)), + _ => {} + } + } + let mut found = vec![]; + out.shapes.iter().for_each(|s| texts(&s.shape, &mut found)); + found + } + + /// The saved themes the My Themes list draws, in order. + fn listed(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec { + drawn(app, ctx, false, vec![]); + let names: Vec = themes(app).iter().map(|t| t.name.clone()).collect(); + drawn(app, ctx, false, vec![]).into_iter().map(|(t, _)| t).filter(|t| names.contains(t)).collect() + } + + /// Click panel menu item `label` (with its check mark, or three spaces when unchecked). + fn click_menu(app: &mut VectorcraftApp, ctx: &egui::Context, label: &str) { + let texts = drawn(app, ctx, true, vec![]); + let at = texts.iter().find(|(t, _)| t == label).unwrap_or_else(|| panic!("no {label:?} in {texts:?}")).1.center(); + let button = + |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + drawn(app, ctx, true, vec![egui::Event::PointerMoved(at), button(true), button(false)]); + } + + /// My Themes with three saved themes and the find field holding `text`. + fn three_themes(text: &str) -> (VectorcraftApp, egui::Context) { + let mut app = app(); + for (name, color) in [("Harbor", "#2266aa"), ("Harvest", "#cc8822"), ("Forest", "#227744")] { + app.run("colorTheme.save", json!({"color": color, "rule": "complementary", "name": name})).unwrap(); + } + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + set_pstate(&ctx, "ct-tab", 1usize); + set_pstate(&ctx, "ct-show-find", true); + ctx.data_mut(|d| d.insert_temp(find_id(), text.to_string())); + (app, ctx) + } + + /// Show Find Field is a checked item of the My Themes menu only, off in a new session; each + /// choice turns the field on or off. + #[test] + fn show_find_field_toggles_the_find_field_on_my_themes() { + let mut app = app(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let has = |texts: &[(String, Rect)], label: &str| texts.iter().any(|(t, _)| t == label); + let texts = drawn(&mut app, &ctx, true, vec![]); + assert!(!has(&texts, " Show Find Field") && !has(&texts, "✓ Show Find Field"), "the Create tab has no find field"); + set_pstate(&ctx, "ct-tab", 1usize); + assert!(has(&drawn(&mut app, &ctx, true, vec![]), " Show Find Field"), "off in a new session"); + assert!(!has(&drawn(&mut app, &ctx, false, vec![]), "Find"), "no field while it is off"); + click_menu(&mut app, &ctx, " Show Find Field"); + assert!(show_find(&ctx)); + assert!(has(&drawn(&mut app, &ctx, true, vec![]), "✓ Show Find Field")); + assert!(has(&drawn(&mut app, &ctx, false, vec![]), "Find"), "the field shows its hint"); + click_menu(&mut app, &ctx, "✓ Show Find Field"); + assert!(!show_find(&ctx)); + } + + /// The find field lists the themes whose names hold its text, in any letter case, anywhere in + /// the name, in their saved order; it reads names only, and its text is plain text. + #[test] + fn the_find_field_lists_themes_whose_names_hold_its_text() { + let (mut app, ctx) = three_themes(" HAR "); + assert_eq!(listed(&mut app, &ctx), ["Harbor", "Harvest"]); + ctx.data_mut(|d| d.insert_temp(find_id(), "vest".to_string())); + assert_eq!(listed(&mut app, &ctx), ["Harvest"], "a match in the middle of a name"); + // Colours are not searched: no name holds "2266aa". + ctx.data_mut(|d| d.insert_temp(find_id(), "2266aa".to_string())); + assert!(listed(&mut app, &ctx).is_empty()); + assert!(drawn(&mut app, &ctx, false, vec![]).iter().any(|(t, _)| t == "No matches.")); + assert_eq!(themes(&app).len(), 3, "the saved themes stay"); + // Pattern characters are plain text, and letters outside ASCII match in either case. + app.run("colorTheme.save", json!({"color": "#aa2266", "rule": "complementary", "name": "Été a.b*"})).unwrap(); + ctx.data_mut(|d| d.insert_temp(find_id(), "ÉTÉ A.B*".to_string())); + assert_eq!(listed(&mut app, &ctx), ["Été a.b*"]); + ctx.data_mut(|d| d.insert_temp(find_id(), ".*".to_string())); + assert!(listed(&mut app, &ctx).is_empty()); + // Blank text, or the field turned off, lists every theme; turned on again the text applies. + ctx.data_mut(|d| d.insert_temp(find_id(), " ".to_string())); + assert_eq!(listed(&mut app, &ctx).len(), 4); + ctx.data_mut(|d| d.insert_temp(find_id(), "har".to_string())); + set_pstate(&ctx, "ct-show-find", false); + assert_eq!(listed(&mut app, &ctx).len(), 4); + set_pstate(&ctx, "ct-show-find", true); + assert_eq!(listed(&mut app, &ctx), ["Harbor", "Harvest"]); + } + + /// With no saved themes the panel says so, whatever the find field holds. + #[test] + fn no_saved_themes_is_not_no_matches() { + let mut app = app(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + set_pstate(&ctx, "ct-tab", 1usize); + set_pstate(&ctx, "ct-show-find", true); + ctx.data_mut(|d| d.insert_temp(find_id(), "har".to_string())); + drawn(&mut app, &ctx, false, vec![]); + let texts: Vec = drawn(&mut app, &ctx, false, vec![]).into_iter().map(|(t, _)| t).collect(); + assert!(texts.iter().any(|t| t == "No saved themes"), "{texts:?}"); + assert!(!texts.iter().any(|t| t == "No matches.")); + } + + /// A picked theme that the find field hides stays picked, but neither the menu nor the footer + /// acts on it until the list shows it again. + #[test] + fn a_theme_the_find_field_hides_is_not_acted_on() { + let (mut app, ctx) = three_themes("har"); + set_pstate(&ctx, "ct-picked", Some("Forest".to_string())); + assert_eq!(picked(&app, &ctx), None); + drawn(&mut app, &ctx, true, vec![]); + click_menu(&mut app, &ctx, " Delete Theme"); + assert_eq!(themes(&app).len(), 3, "Delete Theme is off"); + click_menu(&mut app, &ctx, " Edit Theme"); + assert_eq!(tab(&ctx), 1, "Edit Theme is off"); + let undo = undo_len(&app); + click_menu(&mut app, &ctx, " Add to Swatches"); + assert_eq!(undo_len(&app), undo, "Add to Swatches is off"); + // Cleared, the field lists Forest again and it is picked as before. + ctx.data_mut(|d| d.insert_temp(find_id(), String::new())); + assert_eq!(picked(&app, &ctx).as_deref(), Some("Forest")); + ctx.data_mut(|d| d.insert_temp(find_id(), "har".to_string())); + set_pstate(&ctx, "ct-show-find", false); + assert_eq!(picked(&app, &ctx).as_deref(), Some("Forest"), "the field turned off lists it too"); + set_pstate(&ctx, "ct-show-find", true); + // A theme the field shows is acted on. + set_pstate(&ctx, "ct-picked", Some("Harvest".to_string())); + click_menu(&mut app, &ctx, " Delete Theme"); + assert_eq!(themes(&app).iter().map(|t| t.name.as_str()).collect::>(), ["Harbor", "Forest"]); + } + + /// The footer buttons are off for a picked theme that the find field hides. + #[test] + fn footer_buttons_are_off_for_a_hidden_pick() { + use crate::widgets::accessibility_tests::{named, tree}; + let mut app = app(); + app.run("colorTheme.save", json!({"color": "#227744", "rule": "complementary", "name": "Forest"})).unwrap(); + for (text, off) in [("har", true), ("for", false)] { + let shown = tree(|ui| { + let ctx = ui.ctx().clone(); + set_pstate(&ctx, "ct-tab", 1usize); + set_pstate(&ctx, "ct-show-find", true); + set_pstate(&ctx, "ct-picked", Some("Forest".to_string())); + ctx.data_mut(|d| d.insert_temp(find_id(), text.to_string())); + show(&mut app, ui); + }); + for label in ["Edit theme", "Add to Swatches", "Delete theme"] { + assert_eq!(named(&shown, label).is_disabled(), off, "{label} with {text:?}"); + } + } + } + + const SET_ACTIVE: &str = "Set the current fill or stroke to the selected color"; + + /// A click on the panel button that screen readers name `label`. egui finds what the pointer is + /// over from the frame before, so the move gets a frame of its own. + fn click(app: &mut VectorcraftApp, ctx: &egui::Context, label: &str) { + crate::i18n::set_current(crate::i18n::Lang::EN); + ctx.enable_accesskit(); + let mut time = ctx.input(|i| i.time); + let mut run = |app: &mut VectorcraftApp, events: Vec| { + time += 0.1; + let screen = Rect::from_min_size(egui::Pos2::ZERO, vec2(320.0, 520.0)); + let input = egui::RawInput { events, time: Some(time), screen_rect: Some(screen), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| show(app, ui)); + out.textures_delta.clear(); + out + }; + run(app, vec![]); + let out = run(app, vec![]); + let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; + let node = nodes.iter().find(|(_, n)| n.label() == Some(label)); + let b = node.unwrap_or_else(|| panic!("nothing named {label:?}")).1.bounds().expect("bounds"); + let at = egui::pos2((b.x0 + b.x1) as f32 * 0.5, (b.y0 + b.y1) as f32 * 0.5); + let button = + |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + run(app, vec![egui::Event::PointerMoved(at)]); + run(app, vec![button(true)]); + run(app, vec![button(false)]); + } + + /// A Custom theme of five different colours with the third selected. + fn five_colors(ctx: &egui::Context) -> Draft { + let colors = ["#cc2200", "#22aa44", "#3355dd", "#ddbb11", "#884499"].map(|h| Color::from_hex(h).unwrap()).to_vec(); + let d = Draft { colors, rule: None, sel: 2, name: "Mine".into(), editing: None }; + set_draft(ctx, d.clone()); + d + } + + /// The fill and stroke paints of object `id`. + fn paints(app: &VectorcraftApp, id: vectorcraft_doc::NodeId) -> (vectorcraft_color::Paint, vectorcraft_color::Paint) { + let n = app.session.doc().unwrap().doc.node(id).unwrap(); + (n.appearance.fill().unwrap().paint.clone(), n.appearance.stroke().unwrap().paint.clone()) + } + + fn undo_len(app: &VectorcraftApp) -> usize { + app.session.doc().unwrap().history.undo.len() + } + + /// Screen readers name the Set Active Color button by its tool tip; it is off without a document. + #[test] + fn set_active_color_is_named_and_needs_a_document() { + use crate::widgets::accessibility_tests::{named, tree}; + let mut app = app(); + let shown = tree(|ui| show(&mut app, ui)); + assert_eq!(named(&shown, SET_ACTIVE).role(), egui::accesskit::Role::Button); + assert!(!named(&shown, SET_ACTIVE).is_disabled()); + let mut none = VectorcraftApp::new(Session::new(), Default::default()); + let shown = tree(|ui| show(&mut none, ui)); + assert!(named(&shown, SET_ACTIVE).is_disabled(), "no document: nothing to paint"); + } + + /// Set Active Color paints the active proxy of the selection with the selected theme colour, + /// one undo step a click, none when the art already has it, and leaves the theme as it is. + #[test] + fn set_active_color_paints_the_active_proxy_with_the_selected_color() { + let mut app = app(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap(); + let id = app.session.doc().unwrap().selection.objects[0]; + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let d = five_colors(&ctx); + let (_, stroke) = paints(&app, id); + let undo = undo_len(&app); + click(&mut app, &ctx, SET_ACTIVE); + assert_eq!(paints(&app, id), (vectorcraft_color::Paint::solid(d.colors[2]), stroke.clone()), "the selected colour, not the first"); + assert_eq!(undo_len(&app), undo + 1, "one undo step"); + click(&mut app, &ctx, SET_ACTIVE); + assert_eq!(undo_len(&app), undo + 1, "no step when the fill already has the colour"); + // With the Stroke proxy in front, the stroke takes the colour and the fill stays. + app.run("paint.toggleActive", json!({"fill": false})).unwrap(); + set_draft(&ctx, Draft { sel: 3, ..d.clone() }); + click(&mut app, &ctx, SET_ACTIVE); + let solid = |i: usize| vectorcraft_color::Paint::solid(d.colors[i]); + assert_eq!(paints(&app, id), (solid(2), solid(3))); + assert_eq!(undo_len(&app), undo + 2); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(paints(&app, id), (solid(2), stroke.clone()), "one undo takes the stroke back"); + app.run("edit.redo", json!({})).unwrap(); + assert_eq!(paints(&app, id), (solid(2), solid(3))); + // The theme being made and the saved themes stay as they were. + assert_eq!(draft(&app, &ctx), Draft { sel: 3, ..d.clone() }); + assert!(themes(&app).is_empty()); + // The reverse pipette paints nothing. + let undo = undo_len(&app); + click(&mut app, &ctx, "Set the selected color to the current color"); + assert_eq!((paints(&app, id), undo_len(&app)), ((solid(2), solid(3)), undo)); + } + + /// With nothing selected, Set Active Color sets the new-art default alone, without an undo step, + /// and new art takes it. + #[test] + fn set_active_color_with_nothing_selected_sets_the_default_for_new_art() { + let mut app = app(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let d = five_colors(&ctx); + let undo = undo_len(&app); + click(&mut app, &ctx, SET_ACTIVE); + assert_eq!(app.session.paint.fill, vectorcraft_color::Paint::solid(d.colors[2])); + assert_eq!(undo_len(&app), undo, "no art changed"); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap(); + let id = app.session.doc().unwrap().selection.objects[0]; + assert_eq!(paints(&app, id).0, vectorcraft_color::Paint::solid(d.colors[2])); + } + + /// In a CMYK document Set Active Color keeps an RGB theme colour in RGB. + #[test] + fn set_active_color_keeps_the_model_in_a_cmyk_document() { + let mut app = app(); + app.run("file.documentColorMode", json!({"mode": "cmyk"})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap(); + let id = app.session.doc().unwrap().selection.objects[0]; + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let d = five_colors(&ctx); + click(&mut app, &ctx, SET_ACTIVE); + assert_eq!(paints(&app, id).0.color(), Some(d.colors[2])); + assert!(matches!(d.colors[2], Color::Rgb { .. })); + } + + /// With characters selected with the Type tool, Set Active Color paints those characters as a + /// swatch click does: the type and the undo history come out as they do from `paint.setFill` with + /// the same color, and the new-art default stays as it was. + #[test] + fn set_active_color_paints_selected_characters_as_a_swatch_click_does() { + use vectorcraft_doc::{NodeId, NodeKind}; + // The editing handshake of text_styles::tests::select_type_range. + let typed = || { + let mut app = app(); + let id = NodeId(app.run("text.create", json!({"x": 10, "y": 50, "text": "ABcdef", "size": 18})).unwrap()["id"].as_u64().unwrap()); + app.session.select_tool("type", Default::default()).unwrap(); + app.session.apply_actions(vec![vectorcraft_tools::Action::Notify("text.editNew".into())]).unwrap(); + app.session.set_tool_option("select", &json!({"start": 2, "end": 4})); + super::super::character::end_typing(&mut app); + assert_eq!(super::super::character::text_editing(&app), Some((id, 2, 4))); + (app, id) + }; + let runs = |app: &VectorcraftApp, id: NodeId| match &app.session.doc().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => t.runs.clone(), + _ => panic!("not type"), + }; + let (mut by_button, id) = typed(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let d = five_colors(&ctx); + let undo = undo_len(&by_button); + let default = (by_button.session.paint.fill.clone(), by_button.session.paint.stroke.clone()); + assert_ne!(default.0, vectorcraft_color::Paint::solid(d.colors[2])); + click(&mut by_button, &ctx, SET_ACTIVE); + let (mut by_command, _) = typed(); + by_command.run("paint.setFill", json!({"color": color_json(&d.colors[2]), "keepModel": true})).unwrap(); + let painted = runs(&by_button, id); + assert!(painted.iter().any(|r| r.style.fill == vectorcraft_color::Paint::solid(d.colors[2])), "the characters take the color"); + assert!(painted.iter().any(|r| r.style.fill != vectorcraft_color::Paint::solid(d.colors[2])), "the other characters keep theirs"); + assert_eq!(painted, runs(&by_command, id)); + assert_eq!((&by_button.session.paint.fill, &by_button.session.paint.stroke), (&default.0, &default.1), "the default stays"); + assert_eq!( + (&by_button.session.paint.fill, &by_button.session.paint.stroke), + (&by_command.session.paint.fill, &by_command.session.paint.stroke) + ); + assert_eq!((undo_len(&by_button), undo_len(&by_command)), (undo + 1, undo + 1)); + } + /// In a CMYK document the theme being made goes to Swatches with its colors in their own model. #[test] fn the_theme_being_made_keeps_its_model_in_a_cmyk_document() { @@ -471,4 +946,234 @@ mod tests { let g = app.session.doc().unwrap().doc.swatch_groups.last().expect("the group"); assert_eq!(g.swatches.iter().filter_map(|w| w.paint.color()).collect::>(), colors); } + + /// One frame of the panel in a 260 × 700 window with `events`, in English, with screen readers on. + fn step(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> egui::FullOutput { + crate::i18n::set_current(crate::i18n::Lang::EN); + ctx.enable_accesskit(); + let time = ctx.input(|i| i.time) + 0.1; + let screen = Rect::from_min_size(egui::Pos2::ZERO, vec2(260.0, 700.0)); + let input = egui::RawInput { events, time: Some(time), screen_rect: Some(screen), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| show(app, ui)); + out.textures_delta.clear(); + out + } + + /// The screen-reader nodes of the frame after a settling one. + fn nodes(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec<(egui::accesskit::NodeId, egui::accesskit::Node)> { + step(app, ctx, vec![]); + step(app, ctx, vec![]).platform_output.accesskit_update.expect("an accessibility tree").nodes + } + + /// The labels of the color sliders the Create tab shows (named by one letter, unlike the wheel's + /// Brightness slider), with each one's range, in order. + fn slider_ranges(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec<(String, f64, f64)> { + let mut found: Vec<(f64, String, f64, f64)> = nodes(app, ctx) + .into_iter() + .filter(|(_, n)| n.role() == egui::accesskit::Role::Slider && n.label().is_some_and(|l| l.chars().count() == 1)) + .filter_map(|(_, n)| { + let top = n.bounds()?.y0; + Some((top, n.label()?.to_string(), n.min_numeric_value()?, n.max_numeric_value()?)) + }) + .collect(); + found.sort_by(|a, b| a.0.total_cmp(&b.0)); + found.into_iter().map(|(_, l, lo, hi)| (l, lo, hi)).collect() + } + + /// The node id and bounds of the screen-reader node named `label` whose role is (with `rail`) or + /// is not a slider. + fn node(app: &mut VectorcraftApp, ctx: &egui::Context, label: &str, rail: bool) -> (egui::accesskit::NodeId, egui::Pos2) { + let all = nodes(app, ctx); + let (id, n) = all + .iter() + .find(|(_, n)| n.label() == Some(label) && (n.role() == egui::accesskit::Role::Slider) == rail) + .unwrap_or_else(|| panic!("nothing named {label:?}")); + let b = n.bounds().expect("bounds"); + (*id, egui::pos2((b.x0 + b.x1) as f32 * 0.5, (b.y0 + b.y1) as f32 * 0.5)) + } + + /// A screen reader's set-value action on the slider named `label`. + fn set_slider(app: &mut VectorcraftApp, ctx: &egui::Context, label: &str, value: f64) { + use egui::accesskit::{Action, ActionData, ActionRequest, TreeId}; + let (target_node, _) = node(app, ctx, label, true); + let data = Some(ActionData::NumericValue(value)); + step( + app, + ctx, + vec![egui::Event::AccessKitActionRequest(ActionRequest { action: Action::SetValue, target_node, target_tree: TreeId::ROOT, data })], + ); + step(app, ctx, vec![]); + } + + /// A click at `at`, each event in a frame of its own. + fn press_at(app: &mut VectorcraftApp, ctx: &egui::Context, at: egui::Pos2) { + let button = + |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + step(app, ctx, vec![egui::Event::PointerMoved(at)]); + step(app, ctx, vec![button(true)]); + step(app, ctx, vec![button(false)]); + } + + fn key(app: &mut VectorcraftApp, ctx: &egui::Context, key: egui::Key, modifiers: egui::Modifiers) { + step(app, ctx, vec![egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }]); + step(app, ctx, vec![egui::Event::Key { key, physical_key: None, pressed: false, repeat: false, modifiers }]); + } + + /// Type `text` into the number field named `label` in place of its number, and press Enter. + fn type_into(app: &mut VectorcraftApp, ctx: &egui::Context, label: &str, text: &str) { + let (_, at) = node(app, ctx, label, false); + press_at(app, ctx, at); + key(app, ctx, egui::Key::A, egui::Modifiers::COMMAND); + step(app, ctx, vec![egui::Event::Text(text.into())]); + key(app, ctx, egui::Key::Enter, egui::Modifiers::NONE); + step(app, ctx, vec![]); + } + + /// The Create tab offers a Color Mode menu of CMYK, RGB, Lab and HSB with a rail and a number + /// field for each component over its range, beside the hex field. It starts in the selected + /// color's own model (HSB for a gray), keeps the mode picked while the app runs, and picking a + /// mode changes no color. + #[test] + fn the_create_tab_offers_cmyk_rgb_lab_and_hsb_sliders() { + let mut app = app(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut d = five_colors(&ctx); + let named = |app: &mut VectorcraftApp, ctx: &egui::Context, label: &str| nodes(app, ctx).iter().any(|(_, n)| n.label() == Some(label)); + assert!(named(&mut app, &ctx, "Color Mode:"), "the menu is named"); + assert!(named(&mut app, &ctx, "Color"), "the hex field stays"); + let rgb = vec![("R".to_string(), 0.0, 255.0), ("G".into(), 0.0, 255.0), ("B".into(), 0.0, 255.0)]; + assert_eq!(slider_ranges(&mut app, &ctx), rgb, "an RGB color starts in RGB"); + for (c, first) in [(Color::cmyk(0.1, 0.2, 0.3, 0.4), "C"), (Color::lab(50.0, -20.0, 30.0), "L"), (Color::gray(0.5), "H")] { + d.colors[2] = c; + set_draft(&ctx, d.clone()); + assert_eq!(slider_ranges(&mut app, &ctx)[0].0, first, "{c:?}"); + } + let expect = [ + vec![("C", 0.0, 100.0), ("M", 0.0, 100.0), ("Y", 0.0, 100.0), ("K", 0.0, 100.0)], + vec![("R", 0.0, 255.0), ("G", 0.0, 255.0), ("B", 0.0, 255.0)], + vec![("L", 0.0, 100.0), ("a", -128.0, 127.0), ("b", -128.0, 127.0)], + vec![("H", 0.0, 360.0), ("S", 0.0, 100.0), ("B", 0.0, 100.0)], + ]; + for (m, rows) in SLIDER_MODES.into_iter().zip(expect) { + set_pstate(&ctx, "ct-mode", Some(m)); + let rows: Vec<(String, f64, f64)> = rows.into_iter().map(|(l, lo, hi)| (l.to_string(), lo, hi)).collect(); + assert_eq!(slider_ranges(&mut app, &ctx), rows, "{m:?}"); + assert_eq!(draft(&app, &ctx), d, "picking a mode changes no color"); + } + // The picked mode stays when another color is selected. + set_draft(&ctx, Draft { sel: 0, ..d.clone() }); + assert_eq!(slider_ranges(&mut app, &ctx)[0].0, "H"); + } + + /// In Custom, a rail, the arrow keys and the number field change the selected color alone, in + /// the menu's mode, and the selection stays; the other numbers stay as they were set. + #[test] + fn a_slider_edit_changes_only_the_selected_custom_color() { + let mut app = app(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let d = five_colors(&ctx); + let start = components(Mode::Rgb, &d.colors[2]); + set_slider(&mut app, &ctx, "R", 10.0); + let now = draft(&app, &ctx); + assert_eq!(now.colors[2], from_components(Mode::Rgb, &[10.0, start[1], start[2]])); + assert_eq!(now.sel, 2); + for i in [0, 1, 3, 4] { + assert_eq!(now.colors[i], d.colors[i], "color {i} stays"); + } + // The arrow keys step the focused rail by one. + let (_, at) = node(&mut app, &ctx, "G", true); + press_at(&mut app, &ctx, at); + let held = pstate::>(&ctx, "ct-held").expect("held").v; + key(&mut app, &ctx, egui::Key::ArrowRight, egui::Modifiers::NONE); + let after = pstate::>(&ctx, "ct-held").expect("held").v; + assert_eq!(after, vec![10.0, held[1] + 1.0, start[2]]); + // The number field. + type_into(&mut app, &ctx, "B", "40"); + let now = draft(&app, &ctx); + assert_eq!(now.colors[2], from_components(Mode::Rgb, &[10.0, held[1] + 1.0, 40.0])); + assert_eq!((now.sel, now.rule), (2, None)); + assert_eq!(now.colors[0], d.colors[0]); + } + + /// The sliders keep the numbers they set: an HSB color taken to no saturation keeps its hue on + /// the H slider, and S back up brings that hue back. Another color shows its own numbers. + #[test] + fn the_sliders_keep_the_numbers_they_set() { + let mut app = app(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + five_colors(&ctx); + set_pstate(&ctx, "ct-mode", Some(Mode::Hsb)); + let hue = |app: &mut VectorcraftApp, ctx: &egui::Context| { + let (id, _) = node(app, ctx, "H", true); + nodes(app, ctx).into_iter().find(|(n, _)| *n == id).and_then(|(_, n)| n.numeric_value()) + }; + set_slider(&mut app, &ctx, "H", 200.0); + set_slider(&mut app, &ctx, "S", 0.0); + assert_eq!(hue(&mut app, &ctx), Some(200.0), "a gray keeps the hue it was set to"); + set_slider(&mut app, &ctx, "S", 80.0); + let [h, s, _] = draft(&app, &ctx).colors[2].to_hsb(); + assert!((h - 200.0).abs() < 0.5 && (s - 0.8).abs() < 1e-3, "{h} {s}"); + set_draft(&ctx, Draft { sel: 0, ..draft(&app, &ctx) }); + let own = components(Mode::Hsb, &draft(&app, &ctx).colors[0])[0].round(); + assert_eq!(hue(&mut app, &ctx), Some(f64::from(own)), "another color shows its own numbers"); + } + + /// With a rule, a slider edit makes the edited color the theme's new base, as a hex edit does, + /// and selects it. + #[test] + fn with_a_rule_a_slider_edit_rebuilds_the_theme_from_the_edited_color() { + let mut app = app(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let d = Draft { rule: Some(Harmony::Triad), ..five_colors(&ctx) }; + set_draft(&ctx, d.clone()); + set_pstate(&ctx, "ct-mode", Some(Mode::Hsb)); + let start = components(Mode::Hsb, &d.colors[2]); + set_slider(&mut app, &ctx, "H", 200.0); + let base = from_components(Mode::Hsb, &[200.0, start[1], start[2]]); + let now = draft(&app, &ctx); + assert_eq!((now.colors, now.sel), (Harmony::Triad.theme(base), 0)); + } + + /// A CMYK edit keeps the color CMYK and a Lab edit keeps it Lab, with the numbers set, through + /// Save and Add to Swatches in a CMYK document; a number that is not one, or not finite, changes + /// nothing, and one past the range sets its end. + #[test] + fn cmyk_and_lab_slider_edits_keep_their_models() { + let mut app = app(); + app.run("file.documentColorMode", json!({"mode": "cmyk"})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let d = five_colors(&ctx); + set_pstate(&ctx, "ct-mode", Some(Mode::Cmyk)); + let start = components(Mode::Cmyk, &d.colors[2]); + set_slider(&mut app, &ctx, "C", 20.0); + set_slider(&mut app, &ctx, "K", 40.0); + let cmyk = from_components(Mode::Cmyk, &[20.0, start[1], start[2], 40.0]); + assert_eq!(draft(&app, &ctx).colors[2], cmyk); + assert!(matches!(cmyk, Color::Cmyk { k, .. } if (k - 0.4).abs() < 1e-6)); + // Lab on another color. + set_draft(&ctx, Draft { sel: 3, ..draft(&app, &ctx) }); + set_pstate(&ctx, "ct-mode", Some(Mode::Lab)); + let start = components(Mode::Lab, &d.colors[3]); + set_slider(&mut app, &ctx, "b", -60.0); + let lab = Color::lab(start[0], start[1], -60.0); + assert_eq!(draft(&app, &ctx).colors[3], lab); + // Not numbers, not finite, past the range. + let before = draft(&app, &ctx); + type_into(&mut app, &ctx, "L", "abc"); + set_slider(&mut app, &ctx, "a", f64::NAN); + assert_eq!(draft(&app, &ctx), before); + set_slider(&mut app, &ctx, "a", 500.0); + assert_eq!(draft(&app, &ctx).colors[3], Color::lab(start[0], 127.0, -60.0)); + let colors = draft(&app, &ctx).colors; + save(&mut app, &ctx); + assert_eq!(themes(&app)[0].colors, colors, "saved in their models"); + add_draft_to_swatches(&mut app, &ctx); + let g = app.session.doc().unwrap().doc.swatch_groups.last().expect("the group"); + assert_eq!(g.swatches.iter().filter_map(|w| w.paint.color()).collect::>(), colors); + } } diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index a2108d8cf8..31522578e5 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -6,8 +6,15 @@ //! space: an RGB, CMYK or Lab color keeps its model, and a Gray color or a tint of a global swatch //! becomes a process color in the document's color mode. The HSB picked last stays while the //! objects, the proxy, the color and the color settings are unchanged, so a gray keeps its hue. +//! +//! The panel menu's Box View puts a box in the wheel's place: a color field with a vertical +//! channel strip at its right, for the channel picked under Box Channel (Hue, Saturation, +//! Brightness, Red, Green or Blue). The field shows the other two components on the Color +//! Picker's axes. The view and the channel are kept with the preferences (`ui.colorWheel`). -use egui::{Ui, UiBuilder}; +use egui::{Ui, UiBuilder, vec2}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; use vectorcraft_color::cms::{self, Cms}; use vectorcraft_color::{Color, Paint, hsb_to_rgb, rgb_to_hsb}; use vectorcraft_doc::{ColorMode, NodeId}; @@ -15,11 +22,189 @@ use vectorcraft_doc::{ColorMode, NodeId}; use super::color::{Target, apply, wheel_target}; use super::{pstate, set_pstate}; use crate::VectorcraftApp; -use crate::widgets::{self, FieldAxis, Live}; +use crate::dialogs::color_picker::Channel; +use crate::widgets::{self, FieldAxis, Live, SliderValue, menu_item}; pub const ID: &str = "colorWheel"; /// The widest the wheel is drawn. const MAX_WHEEL: f32 = 200.0; +/// The width of the box's channel strip, its arrows included. +const STRIP: f32 = 22.0; +/// The space between the box's field and its channel strip. +const STRIP_GAP: f32 = 6.0; + +/// What the panel shows right of the proxy: the wheel, or the box (a color field and a channel +/// strip). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub enum View { + #[default] + Wheel, + Box, +} + +impl View { + pub const ALL: [View; 2] = [View::Wheel, View::Box]; + + pub fn id(self) -> &'static str { + match self { + View::Wheel => "wheel", + View::Box => "box", + } + } + + pub fn parse(s: &str) -> Option { + Self::ALL.into_iter().find(|v| v.id() == s) + } +} + +/// The panel's settings, kept with the preferences (`UiState::color_wheel`, `ui.colorWheel`). +/// Each key reads on its own, and a value this build does not know reads as the key's default. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct Settings { + #[serde(deserialize_with = "deserialize_view")] + pub view: View, + #[serde(serialize_with = "serialize_channel", deserialize_with = "deserialize_channel")] + pub channel: Channel, +} + +fn deserialize_view<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + let v = ::deserialize(d)?; + Ok(v.as_str().and_then(View::parse).unwrap_or_default()) +} + +fn serialize_channel(c: &Channel, s: S) -> Result { + s.serialize_str(c.id()) +} + +fn deserialize_channel<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + let v = ::deserialize(d)?; + Ok(v.as_str().and_then(Channel::parse).unwrap_or_default()) +} + +/// Serde reader for the saved settings ([`crate::UiState::color_wheel`]): a value that is not an +/// object reads as the defaults, so it doesn't lose the rest of the preferences. +pub fn deserialize_settings<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + let v = ::deserialize(d)?; + Ok(serde_json::from_value(v).unwrap_or_default()) +} + +/// `ui.colorWheel {view?, channel?}`: show the wheel or the box, and pick the box's channel. Keys +/// left out keep their values; params that are not an object, another key or a value off the list +/// are an error and change nothing. → the settings. +pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result { + const KEYS: [&str; 2] = ["view", "channel"]; + match p { + Value::Null => {} + Value::Object(o) => { + if let Some(key) = o.keys().find(|k| !KEYS.contains(&k.as_str())) { + return Err(format!("unknown parameter `{key}`; the command takes: {}", KEYS.join(", "))); + } + } + got => return Err(format!("the params must be an object, not {got}")), + } + let mut set = app.ui.color_wheel.clone(); + match p.get("view") { + None | Some(Value::Null) => {} + Some(v) => set.view = v.as_str().and_then(View::parse).ok_or("`view` must be wheel or box")?, + } + match p.get("channel") { + None | Some(Value::Null) => {} + Some(v) => set.channel = v.as_str().and_then(Channel::parse).ok_or("`channel` must be hue, saturation, brightness, red, green or blue")?, + } + app.ui.color_wheel = set; + Ok(json!(app.ui.color_wheel)) +} + +/// The panel menu: Wheel View and Box View, and Box Channel while the box shows. +pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { + let set = app.ui.color_wheel.clone(); + for (label, view) in [(tl!("Wheel View"), View::Wheel), (tl!("Box View"), View::Box)] { + if menu_item(ui, label, true, set.view == view) { + command(app, &json!({ "view": view.id() })).ok(); + } + } + ui.add_enabled_ui(set.view == View::Box, |ui| { + ui.menu_button(format!(" {}", tl!("Box Channel")), |ui| { + for ch in Channel::ALL { + if menu_item(ui, ch.name(), true, ch == set.channel) { + command(app, &json!({ "channel": ch.id() })).ok(); + } + } + }); + }); +} + +/// The display values of HSB `hsb` in `ch`'s space, from 0 to 1: hue, saturation and brightness, +/// or red, green and blue. +fn box_values(ch: Channel, hsb: [f32; 3]) -> [f32; 3] { + if ch.is_hsb() { [hsb[0] / 360.0, hsb[1], hsb[2]] } else { hsb_to_rgb(hsb) } +} + +/// The strip's value and the field's point (x across, y down; 0 to 1 each) of HSB `hsb` in the box +/// of channel `ch`. +pub(crate) fn box_pos(ch: Channel, hsb: [f32; 3]) -> (f32, f32, f32) { + let v = box_values(ch, hsb); + let (z, x, y) = ch.axes(); + (v[z], v[x], 1.0 - v[y]) +} + +/// The HSB at strip value `z` and field point (x, y) in the box of channel `ch`: the inverse of +/// [`box_pos`]. A pick in an RGB channel that has no hue (a gray) keeps the hue of `was`. +pub(crate) fn box_pick(ch: Channel, z: f32, x: f32, y: f32, was: [f32; 3]) -> [f32; 3] { + let (zi, xi, yi) = ch.axes(); + let mut v = [0.0; 3]; + v[zi] = z; + v[xi] = x; + v[yi] = 1.0 - y; + let v = v.map(|c| c.clamp(0.0, 1.0)); + if ch.is_hsb() { + return [v[0] * 360.0, v[1], v[2]]; + } + let hsb = rgb_to_hsb(v); + if hsb[1] <= 0.0 || hsb[2] <= 0.0 { [was[0], hsb[1], hsb[2]] } else { hsb } +} + +/// The number the strip of channel `ch` reads to screen readers for HSB `hsb`, its suffix and its +/// largest value: hue in degrees, saturation and brightness in percent, red, green and blue from 0 +/// to 255. +fn strip_number(ch: Channel, hsb: [f32; 3]) -> (f64, &'static str, f64) { + let (units, suffix) = match ch { + Channel::Hue => (360.0, "°"), + Channel::Saturation | Channel::Brightness => (100.0, "%"), + Channel::Red | Channel::Green | Channel::Blue => (255.0, ""), + }; + let (z, _, _) = box_pos(ch, hsb); + (f64::from(z) * units, suffix, units) +} + +/// The box in a `size` × `size` area: the field of channel `ch` and its strip, on HSB `hsb`, with +/// markers when `marked`. Returns the HSB a click, a drag, a key or a screen reader's action picks, +/// and its phase. +fn show_box(ui: &mut Ui, ch: Channel, hsb: [f32; 3], marked: bool, size: f32) -> Option<([f32; 3], Live)> { + let (z, x, y) = box_pos(ch, hsb); + let mut pick = None; + ui.horizontal_top(|ui| { + ui.spacing_mut().item_spacing.x = STRIP_GAP; + let field = vec2((size - STRIP_GAP - STRIP).max(1.0), size); + let at = |x: f32, y: f32| widgets::hsb32(box_pick(ch, z, x, y, hsb)); + if let (Some((x, y)), phase) = widgets::color_field(ui, "color-wheel-box", (tl!("Color box"), ch.field_axes()), field, (x, y), marked, &at) { + pick = Some((box_pick(ch, z, x, y, hsb), phase)); + } + // The hue strip shows the whole spectrum; the others change only their own component. + let track = |z: f32| widgets::hsb32(if ch == Channel::Hue { [z * 360.0, 1.0, 1.0] } else { box_pick(ch, z, x, y, hsb) }); + let (v, suffix, max) = strip_number(ch, hsb); + let shown = SliderValue::field(v, 0.0..=max, suffix, 0); + match widgets::channel_slider_stepped(ui, "color-wheel-strip", ch.name(), Some(shown), z, marked, vec2(STRIP, size), &track) { + (Some(z), phase, _) => pick = Some((box_pick(ch, z, x, y, hsb), phase)), + (None, _, Some(v)) => pick = Some((box_pick(ch, (v / max) as f32, x, y, hsb), Live::Released)), + _ => {} + } + }); + pick +} + /// Panel state: the HSB picked last, its [`Owner`] and the display sRGB of the color it stored. const MEMORY: &str = "color-wheel-hsb"; @@ -132,6 +317,10 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { super::proxy(app, ui, 40.0); }); let size = ui.available_width().min(MAX_WHEEL); + if app.ui.color_wheel.view == View::Box { + pick = show_box(ui, app.ui.color_wheel.channel, hsb, marked, size); + return; + } let ring = widgets::hue_ring(ui, "color-wheel-ring", tl!("Hue ring"), size, hsb[0], marked); let square = widgets::ring_square(ring.rect); let mut field_ui = ui.new_child(UiBuilder::new().id_salt("color-wheel-square").max_rect(square)); diff --git a/crates/ui-egui/src/panels/discover.rs b/crates/ui-egui/src/panels/discover.rs new file mode 100644 index 0000000000..1c3fd12262 --- /dev/null +++ b/crates/ui-egui/src/panels/discover.rs @@ -0,0 +1,336 @@ +//! Help searches the tools, menu commands, and built-in tutorials. + +use egui::Ui; +use serde::Serialize; +use serde_json::{Value, json}; + +use crate::{VectorcraftApp, menus}; + +pub const ID: &str = "discover"; +const MAX_QUERY: usize = 1024; + +#[derive(Clone, Debug, Serialize)] +pub struct Hit { + pub kind: &'static str, + pub id: String, + pub label: String, + pub path: Vec, + pub shortcut: String, + /// The English label and menu path that `label` and `path` translate, and a command's menu + /// params, kept to bring a retained result up to date ([`refresh`]). + #[serde(skip)] + english_label: String, + #[serde(skip)] + english_path: Vec, + #[serde(skip)] + params: Value, +} + +#[derive(Clone, Debug, Default)] +pub struct View { + pub query: String, + pub results: Vec, + pub selected: Option, + pub focus: bool, + /// The menu state ([`crate::native_menu::state_hash`]: commands run, shortcuts, the language, + /// recent files and more) the results were last brought up to date for. + current_for: Option, +} + +fn matches(query: &str, text: &str) -> bool { + let text = text.to_lowercase(); + query.split_whitespace().all(|word| text.contains(word)) +} + +fn now(app: &VectorcraftApp) -> u64 { + crate::native_menu::state_hash(app, None) +} + +/// Updates the retained results' labels, menu paths and shortcuts after the menu state changes (a +/// command, a shortcut or the UI language), keeping the query, the results' order and the selected +/// result. A command result takes its menu item's current label and place (Show Grid becomes Hide +/// Grid), and leaves the results when no menu lists it any more, such as a recent file that was +/// removed. +fn refresh(app: &mut VectorcraftApp) { + let stamp = now(app); + if app.ui.discover.current_for == Some(stamp) { + return; + } + let lang = crate::i18n::current(); + let entries = if app.ui.discover.results.iter().any(|hit| hit.kind == "command") { menus::menu_entries(app) } else { Vec::new() }; + let mut by_command: std::collections::HashMap<(&str, String), Vec<&menus::MenuEntry>> = std::collections::HashMap::new(); + for entry in &entries { + if let Some(id) = entry.command.as_deref() { + by_command.entry((id, entry.params.to_string())).or_default().push(entry); + } + } + let selected = app.ui.discover.selected.take(); + let mut kept = Vec::with_capacity(app.ui.discover.results.len()); + for (index, mut hit) in std::mem::take(&mut app.ui.discover.results).into_iter().enumerate() { + match hit.kind { + "tool" => { + hit.label = crate::i18n::tr(lang, &hit.english_label).into(); + hit.shortcut = crate::shortcut_editor::tool_shortcut(&hit.id).unwrap_or_default().into(); + } + "command" => { + let same = by_command.get(&(hit.id.as_str(), hit.params.to_string())).map_or(&[][..], Vec::as_slice); + let Some(entry) = same.iter().find(|e| e.path == hit.english_path).or_else(|| same.first()) else { + continue; + }; + hit.english_label = entry.label.clone(); + hit.english_path = entry.path.clone(); + hit.label = menus::shown_label(app, &hit.id, &hit.params, &hit.english_label); + hit.path = entry.shown_path.clone(); + hit.shortcut = menus::item_shortcut(&hit.id, &hit.params).or_else(|| menus::shortcut_of(&hit.id)).unwrap_or_default().into(); + } + _ => {} + } + if selected == Some(index) { + app.ui.discover.selected = Some(kept.len()); + } + kept.push(hit); + } + app.ui.discover.results = kept; + app.ui.discover.current_for = Some(stamp); +} + +fn search(app: &VectorcraftApp, query: &str) -> Vec { + let query = query.trim().to_lowercase(); + if query.is_empty() { + return Vec::new(); + } + let mut hits = Vec::new(); + let lang = crate::i18n::current(); + for tool in vectorcraft_tools::catalog::all_tools() { + let label = crate::i18n::tr(lang, tool.label); + if matches(&query, &format!("{} {label} {}", tool.label, tool.id)) { + hits.push(Hit { + kind: "tool", + id: tool.id.into(), + label: label.into(), + path: vec![], + shortcut: crate::shortcut_editor::tool_shortcut(tool.id).unwrap_or_default().into(), + english_label: tool.label.into(), + english_path: vec![], + params: Value::Null, + }); + } + } + for entry in menus::menu_entries(app) { + let Some(id) = entry.command else { continue }; + // The menu bar in the window has no VectorCraft menu; only the native macOS bar shows it. + if !cfg!(target_os = "macos") && entry.path.first().is_some_and(|title| title == "VectorCraft") { + continue; + } + let label = menus::shown_label(app, &id, &entry.params, &entry.label); + let path = entry.shown_path; + if matches(&query, &format!("{} {label} {} {} {id}", entry.label, entry.path.join(" "), path.join(" "))) { + hits.push(Hit { + kind: "command", + id, + label, + path, + shortcut: entry.shortcut, + english_label: entry.label, + english_path: entry.path, + params: entry.params, + }); + } + } + for skill in super::learn::catalog::SKILLS { + for tutorial in skill.tutorials { + if matches(&query, &format!("{} {} {}", skill.title, tutorial.title, tutorial.id)) { + hits.push(Hit { + kind: "tutorial", + id: tutorial.id.into(), + label: tutorial.title.into(), + path: vec![skill.title.into()], + shortcut: String::new(), + english_label: tutorial.title.into(), + english_path: vec![skill.title.into()], + params: Value::Null, + }); + } + } + } + hits +} + +fn results(app: &VectorcraftApp) -> Value { + json!({"query": app.ui.discover.query, "results": app.ui.discover.results, "selected": app.ui.discover.selected}) +} + +fn set_query(app: &mut VectorcraftApp, query: &str) { + app.ui.discover.current_for = Some(now(app)); + app.ui.discover.results = search(app, query); + app.ui.discover.query = query.into(); + app.ui.discover.selected = None; +} + +pub(crate) fn command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option> { + let spec = menus::UI_COMMANDS.iter().find(|spec| spec.0 == id && id.starts_with("help.discover"))?; + if !(p.is_object() || p.is_null()) { + return Some(Err("`params` must be an object".into())); + } + if let Err(e) = vectorcraft_engine::cmd::params::check_keys(id, spec.3, p) { + return Some(Err(e.to_string())); + } + refresh(app); + Some(match id { + "help.discover" | "help.discover.search" => { + let query = match p.get("query") { + Some(Value::String(query)) => Some(query.as_str()), + None if id == "help.discover" => None, + _ => { + let key = "query"; + return Some(Err(format!("`{key}` must be a string"))); + } + }; + if let Some(query) = query { + if query.chars().take(MAX_QUERY + 1).count() > MAX_QUERY { + let label = "query"; + let max = MAX_QUERY; + return Some(Err(format!("{label} must be at most {max} characters"))); + } + set_query(app, query); + } + app.ui.discover.focus = true; + crate::panel_docking::reveal_panel(app, ID).map(|_| results(app)) + } + "help.discover.choose" => { + let hit = p + .get("index") + .and_then(Value::as_u64) + .and_then(|i| usize::try_from(i).ok()) + .and_then(|i| app.ui.discover.results.get(i).cloned().map(|hit| (i, hit))); + let Some((index, hit)) = hit else { + return Some(Err("index out of range".into())); + }; + let outcome = match hit.kind { + "tool" => app.run("learn.locateTool", json!({"tool": hit.id})), + "tutorial" => Ok(json!({"tutorial": hit.id})), + _ => Ok(json!({"command": hit.id, "path": hit.path, "shortcut": hit.shortcut})), + }; + outcome.and_then(|outcome| { + crate::panel_docking::reveal_panel(app, ID)?; + app.ui.discover.selected = Some(index); + app.ui.discover.focus = true; + Ok(json!({"result": hit, "location": outcome})) + }) + } + "help.discover.back" => { + app.ui.discover.selected = None; + app.ui.discover.focus = true; + Ok(results(app)) + } + _ => return None, + }) +} + +pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { + refresh(app); + let mut query = app.ui.discover.query.clone(); + let field = ui.add(egui::TextEdit::singleline(&mut query).char_limit(MAX_QUERY).hint_text(tl!("Search")).desired_width(f32::INFINITY)); + if std::mem::take(&mut app.ui.discover.focus) { + field.request_focus(); + } + if field.changed() + && let Err(e) = app.run("help.discover.search", json!({"query": query})) + { + app.status(e); + } + if (field.has_focus() || field.lost_focus()) + && !app.session.tool_busy() + && !app.session.tool_composing() + && ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) + { + if let Err(e) = app.run("window.panel.close", json!({"panel": ID})) { + app.status(e); + } + return; + } + let mut chosen = None; + let mut home = false; + let mut back = false; + let mut locate = None; + ui.horizontal(|ui| { + home = ui.button(tl!("Home")).clicked(); + if app.ui.discover.selected.is_some() { + back = ui.button(tl!("Back")).clicked(); + } + }); + crate::widgets::divider(ui); + if let Some(hit) = app.ui.discover.selected.and_then(|i| app.ui.discover.results.get(i)) { + ui.heading(&hit.label); + if !hit.path.is_empty() { + ui.label(hit.path.join(" › ")); + } + if !hit.shortcut.is_empty() { + ui.label(menus::pretty_shortcut(&hit.shortcut)); + } + if hit.kind == "tutorial" + && let Some((_, tutorial)) = super::learn::catalog::tutorial(&hit.id) + { + for (index, step) in tutorial.steps.iter().enumerate() { + ui.label(format!("{}. {}", index + 1, step.plain())); + if let Some(tool) = step.tool + && let Some(info) = vectorcraft_tools::tool_info(tool) + && ui.link(crate::i18n::tr(crate::i18n::current(), info.label)).clicked() + { + locate = Some(tool); + } + } + } + } else { + egui::ScrollArea::vertical().id_salt("discover-results").show(ui, |ui| { + if app.ui.discover.results.is_empty() && !query.trim().is_empty() { + ui.label(tl!("No results")); + } + for kind in ["tool", "command", "tutorial"] { + let label = match kind { + "tool" => tl!("Tools"), + "command" => tl!("Search Commands…"), + _ => tl!("Learn"), + }; + let mut heading = false; + for (index, hit) in app.ui.discover.results.iter().enumerate().filter(|(_, h)| h.kind == kind) { + if !heading { + crate::widgets::subheader(ui, label); + heading = true; + } + if ui.selectable_label(false, &hit.label).on_hover_text(hit.path.join(" › ")).clicked() { + chosen = Some(index); + } + } + } + }); + } + if home { + if let Err(e) = app.run("help.discover.search", json!({"query": ""})) { + app.status(e); + } + } else if back { + if let Err(e) = app.run("help.discover.back", json!({})) { + app.status(e); + } + } else if let Some(index) = chosen { + match app.run("help.discover.choose", json!({"index": index})) { + Ok(picked) => status_reason(app, &picked["location"]), + Err(e) => app.status(e), + } + } + if let Some(tool) = locate { + match app.run("learn.locateTool", json!({"tool": tool})) { + Ok(located) => status_reason(app, &located), + Err(e) => app.status(e), + } + } +} + +/// A `learn.locateTool` reply that could not mark its tool (`location: "unavailable"`) shows its +/// `reason` in the status bar. +fn status_reason(app: &mut VectorcraftApp, located: &Value) { + if let Some(reason) = located.get("reason").and_then(Value::as_str) { + app.status(reason); + } +} diff --git a/crates/ui-egui/src/panels/doc_info.rs b/crates/ui-egui/src/panels/doc_info.rs index 64144a2150..ff978ebb4f 100644 --- a/crates/ui-egui/src/panels/doc_info.rs +++ b/crates/ui-egui/src/panels/doc_info.rs @@ -11,10 +11,11 @@ use crate::VectorcraftApp; use crate::theme::Tokens; use crate::widgets::{self, menu_item}; -/// `document.info` and what it was fetched for: (document uid, revision, selection only). +/// `document.info` and what it was fetched for: (document uid, revision, selection only, the +/// Artboard tool's options while it is the current tool, else null). #[derive(Clone, Default)] struct Cache { - key: Option<(u64, u64, bool)>, + key: Option<(u64, u64, bool, Value)>, info: Value, } @@ -31,10 +32,12 @@ pub(crate) fn row(ui: &mut Ui, label: &str, value: String) { }); } -/// `document.info` with its categories, fetched again only when the document or the scope changes. +/// `document.info` with its categories, fetched again only when the document, the scope or the +/// artboards the Artboard tool has selected change. fn info(app: &mut VectorcraftApp, ctx: &egui::Context, sel_only: bool) -> Option { + let artboard_tool = if app.session.tool_id() == "artboard" { app.session.tool_options_of("artboard") } else { Value::Null }; let st = app.session.active()?; - let key = Some((st.uid, st.revision, sel_only)); + let key = Some((st.uid, st.revision, sel_only, artboard_tool)); let mut c: Cache = pstate(ctx, "docinfo-cache"); if c.key != key { c.info = app.session.execute("document.info", &json!({ "selectionOnly": sel_only })).ok()?; @@ -121,6 +124,9 @@ fn shown_value(info: &Value, id: &str, k: usize, (label, value): (&str, &str), n let ppi = info["document"]["rasterEffectsPpi"].as_f64()?; Some(fill(tl!("{n} ppi"), &[("n", &ppi.to_string())])) } + "Grid Size" | "Grid Colors" | "Simulate Colored Paper" | "Flattener Preset" => { + transparency_value(&info["document"]["transparency"], label) + } _ => None, }, "brushes" => Some(brush_value(value).to_string()), @@ -136,6 +142,40 @@ fn shown_value(info: &Value, id: &str, k: usize, (label, value): (&str, &str), n } } +/// A transparency row of Document (`label`) in the interface language, from `document.info`'s +/// `document.transparency` (`t`): the grid's size, its colors' preset name (two custom colors stay +/// as `document.info` gives them), Simulate Colored Paper on or off, and a built-in flattener +/// preset's name (a saved preset's name stays as it is). +fn transparency_value(t: &Value, label: &str) -> Option { + let shown = match label { + "Grid Size" => match t["gridSize"].as_str()? { + "small" => tl!("Small"), + "medium" => tl!("Medium"), + "large" => tl!("Large"), + _ => return None, + }, + "Grid Colors" => match t["gridColorsName"].as_str()? { + "Custom" => return None, + name if vectorcraft_doc::setup::GRID_COLOR_PRESETS.iter().any(|(n, _)| *n == name) => tl!(name), + _ => return None, + }, + "Simulate Colored Paper" => { + if t["simulatePaper"].as_bool()? { + tl!("On") + } else { + tl!("Off") + } + } + _ => match t["flattenerPreset"].as_str()? { + "High Resolution" => tl!("High Resolution"), + "Medium Resolution" => tl!("Medium Resolution"), + "Low Resolution" => tl!("Low Resolution"), + _ => return None, + }, + }; + Some(shown.to_string()) +} + /// [`crate::i18n::fill_once`]: a name that holds `{…}` text stays as it is. fn fill(template: &str, args: &[(&str, &str)]) -> String { crate::i18n::fill_once(template, args) @@ -553,6 +593,58 @@ mod tests { assert!(report.contains("Units: Millimeters\n") && report.contains("Radial Repeat, 6 instances"), "{report}"); } + /// Document shows the transparency settings with their values in the interface language (two + /// custom grid colors as they are), and while the Artboard tool is the current tool the + /// artboards it has selected, following its selection without an edit to the document. + #[test] + fn document_shows_transparency_and_the_artboard_tools_selection() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + app.session.execute("artboard.new", &json!({"x": 150, "y": 40, "width": 60, "height": 80})).unwrap(); + app.session.execute("artboard.setProps", &json!({"index": 1, "name": "Back"})).unwrap(); + let ctx = egui::Context::default(); + let document = |app: &mut VectorcraftApp| { + let info = info(app, &ctx, false).unwrap(); + shown_rows(&info, "document") + }; + let value = |rows: &[(String, String)], label: &str| rows.iter().find(|(l, _)| l == label).map(|(_, v)| v.clone()); + let english = document(&mut app); + assert_eq!(value(&english, "Grid Colors").as_deref(), Some("Light")); + assert_eq!(value(&english, "X"), None, "no artboard rows with another tool: {english:?}"); + app.select_tool("artboard"); + app.session.set_tool_option("selected", &json!([1])); + let rows = document(&mut app); + let at = rows.iter().position(|(l, v)| l == "Artboard" && v == "Back").unwrap_or_else(|| panic!("{rows:?}")); + assert_eq!(rows[at + 1..at + 5].iter().map(|(_, v)| v.as_str()).collect::>(), ["60 pt", "80 pt", "0 pt", "0 pt"]); + // Selecting another artboard changes the rows, though the document did not change. + app.session.set_tool_option("selected", &json!([0, 1])); + let rows = document(&mut app); + assert_eq!(rows.iter().filter(|(l, _)| l == "Artboard").count(), 2, "{rows:?}"); + assert!(rows.contains(&("X".into(), "150 pt".into())) && rows.contains(&("Y".into(), "40 pt".into())), "from artboard 1's corner: {rows:?}"); + app.session + .execute( + "document.setup", + &json!({"gridSize": "large", "simulatePaper": true, "flattenerPreset": "Low Resolution", "gridColors": "Purple"}), + ) + .unwrap(); + let Some(de) = crate::i18n::Lang::from_code("de") else { panic!("no German catalog") }; + crate::i18n::set_current(de); + let german = document(&mut app); + let painted = crate::tests_labels::painted_text(&mut app, show); + crate::i18n::set_current(crate::i18n::Lang::EN); + let shown = |label: &str| value(&german, label).unwrap_or_else(|| panic!("no {label} in {german:?}")); + assert_eq!( + [shown("Grid Size"), shown("Grid Colors"), shown("Simulate Colored Paper"), shown("Flattener Preset")], + ["Groß", "Lila", "Ein", "Niedrige Auflösung"] + ); + assert!(painted.contains("Rastergröße") && painted.contains("Groß") && painted.contains("Back"), "{painted}"); + app.session.execute("document.setup", &json!({"gridColors": ["#ff0000", "#00ff00"]})).unwrap(); + crate::i18n::set_current(de); + let custom = value(&document(&mut app), "Grid Colors"); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert_eq!(custom.as_deref(), Some("#ff0000, #00ff00")); + } + /// A Repeat object's counts take each language's plural forms, and a grid that draws fewer /// instances than its rows and columns give is followed by the number it draws. #[test] diff --git a/crates/ui-egui/src/panels/graphic_styles.rs b/crates/ui-egui/src/panels/graphic_styles.rs index 59d518cb1b..2696c78c08 100644 --- a/crates/ui-egui/src/panels/graphic_styles.rs +++ b/crates/ui-egui/src/panels/graphic_styles.rs @@ -3,10 +3,13 @@ //! shows the shape outlined in black and filled with white, under a red slash. Clicking a style applies it to the //! selection (Alt-click adds it on top); Shift-click adds to the panel's selection every style from //! the last one clicked without Shift through this one; Cmd/Ctrl-click adds or removes one; -//! double-click opens Graphic Style Options. Dragging a style moves it in the list, applies it +//! double-click opens Graphic Style Options. Dragging a style moves it in the list (dropped on +//! another style with Alt held, replaces that style with its look), applies it //! to the art it is dropped on (`canvas::panel_drop`), or, dropped on New Graphic Style, adds a //! copy of it and of the styles highlighted with it at the end of the list; art dragged off the -//! canvas or the Appearance panel's thumbnail dropped on the panel becomes a new style. Holding the right button on a style +//! canvas or the Appearance panel's thumbnail dropped on the panel becomes a new style, and +//! dropped on a style with Alt held replaces that style with its look (`graphicStyle.redefine`). +//! Holding the right button on a style //! shows it large, on the selected object when there is one. The Control bar's Style picker lists //! the same tiles ([`picker`]). Graphic style libraries open in library panels //! ([`GraphicStyleLibraries`]). @@ -364,6 +367,10 @@ struct Events { moved: Option<(String, usize)>, /// Art or an appearance dropped on the panel: a new style from this object. new_from: Option, + /// Art or an appearance dropped on a style with Alt held: the style takes this object's look. + replaced: Option<(String, NodeId)>, + /// A style dropped on another with Alt held: the second (`.0`) takes the first's (`.1`) look. + restyled: Option<(String, String)>, /// The style the right button is held on. large: Option, /// A style is dragged over a tile or row. @@ -383,10 +390,27 @@ fn clicked(ui: &Ui, resp: &Response, name: &str) -> Option { /// Clicks, drags and the right button on the tile or row `resp` of style `i` of `d` (`list`: rows /// stack downwards). A drag from it carries the style ([`PanelDrag::GraphicStyle`]); a style -/// dragged over it lands before or after it by the pointer's half. +/// dragged over it lands before or after it by the pointer's half, or with Alt held outlines it +/// and, released there, replaces it with the dragged style's look. Art (its first object) or the +/// Appearance panel's thumbnail held over it with Alt outlines it, and released there replaces the +/// style with that object's look; without Alt it is left to the list ([`zone_input`]). fn cell_input(ui: &Ui, resp: &Response, d: &Document, i: usize, list: bool, ev: &mut Events) { let name = &d.graphic_styles[i].name; widgets::drag_source(ui, resp, || PanelDrag::GraphicStyle(name.clone())); + let source = resp.dnd_hover_payload::().and_then(|drag| match &*drag { + PanelDrag::Art(ids) => ids.first().copied(), + PanelDrag::Appearance(id) => Some(*id), + _ => None, + }); + if let Some(id) = source + && alt_held(ui) + { + ev.over = true; + widgets::drop_target_outline(ui, resp.rect); + if resp.dnd_release_payload::().is_some() { + ev.replaced = Some((name.clone(), id)); + } + } if let Some(drag) = resp.dnd_hover_payload::() && let PanelDrag::GraphicStyle(moving) = &*drag { @@ -394,6 +418,11 @@ fn cell_input(ui: &Ui, resp: &Response, d: &Document, i: usize, list: bool, ev: if moving == name { // Dropped on itself: it stays where it is. resp.dnd_release_payload::(); + } else if alt_held(ui) { + widgets::drop_target_outline(ui, resp.rect); + if resp.dnd_release_payload::().is_some() { + ev.restyled = Some((name.clone(), moving.clone())); + } } else { let r = resp.rect; let at = ui.input(|i| i.pointer.interact_pos()).unwrap_or(r.center()); @@ -432,7 +461,7 @@ fn zone_input(ui: &Ui, zone: &Response, d: &Document, ev: &mut Events) { PanelDrag::Art(ids) => (None, ids.first().copied()), PanelDrag::Appearance(id) => (None, Some(*id)), PanelDrag::Paint { .. } - | PanelDrag::Symbol(_) + | PanelDrag::Symbol { .. } | PanelDrag::LibrarySymbol { .. } | PanelDrag::Brush { .. } | PanelDrag::LibraryBrush { .. } @@ -505,6 +534,15 @@ fn act(app: &mut VectorcraftApp, ui: &Ui, s: &Shown, ev: Events, picker: bool) { if let Some(id) = ev.new_from { run(app, "graphicStyle.new", json!({ "id": id.0 })); } + // An object that is linked to the style and still has its look leaves the style as it is. + if let Some((name, id)) = ev.replaced + && !app.session.graphic_style_of(id).is_some_and(|(g, linked)| linked && g.name == name) + { + run(app, "graphicStyle.redefine", json!({ "name": name, "id": id.0 })); + } + if let Some((name, from)) = ev.restyled { + run(app, "graphicStyle.redefine", json!({ "name": name, "from": from })); + } match ev.click { Some(Click::Pick(name, _)) if picker => { app.run("graphicStyle.apply", json!({"name": name, "add": alt_held(ui)})).ok(); @@ -1432,6 +1470,190 @@ mod tests { } } + /// Art or the Appearance panel's thumbnail dropped on a style with Alt held replaces that style + /// with the object's look, in one undo step: the style keeps its name, its place and its id, the + /// objects still linked to it take the new look, and the object becomes linked. The style is + /// outlined while one is held over it with Alt. Without Alt the drop makes a new style; a style + /// dragged with Alt still only moves; an object linked to the style with its look, an empty art + /// drag and an object that is gone change nothing and record no undo step. + #[test] + fn art_or_an_appearance_dropped_on_a_style_with_alt_replaces_that_style() { + let mut app = app(); + let rect = app.session.active().unwrap().doc.layers[0].children().unwrap()[0].id; + app.run("paint.setFill", json!({"color": "#ff0000", "ids": [rect.0]})).unwrap(); + app.run("graphicStyle.new", json!({"name": "Red", "id": rect.0})).unwrap(); + app.run("graphicStyle.move", json!({"name": "Red", "to": 0})).unwrap(); + app.run("shape.ellipse", json!({"x": 60, "y": 60, "width": 20, "height": 20})).unwrap(); + let oval = app.session.active().unwrap().selection.objects[0]; + app.run("paint.setFill", json!({"color": "#00ff00", "ids": [oval.0]})).unwrap(); + let ctx = egui::Context::default(); + let screen = Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(260.0, 600.0))); + // One frame of the panel with `events` and `modifiers` held: whether a drop-target outline + // the size of one style's tile or row is drawn around `at`. + let frame_at = |app: &mut VectorcraftApp, at: egui::Pos2, events: Vec, modifiers: egui::Modifiers| { + let events = std::iter::once(egui::Event::ModifiersChanged(modifiers)).chain(events).collect(); + let mut out = ctx.run_ui(egui::RawInput { screen_rect: screen, events, ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + let accent = Tokens::get(&ctx).accent; + out.shapes.iter().any(|c| match &c.shape { + egui::Shape::Rect(r) => r.stroke.width == 1.5 && r.stroke.color == accent && r.rect.contains(at) && r.rect.height() < 45.0, + _ => false, + }) + }; + let release = |at: egui::Pos2, modifiers: egui::Modifiers| { + let up = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers }; + vec![egui::Event::PointerMoved(at), up] + }; + let (none, alt) = (egui::Modifiers::default(), egui::Modifiers::ALT); + let doc = |app: &VectorcraftApp| app.session.active().unwrap().doc.clone(); + let steps = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len(); + let red = doc(&app).graphic_style("Red").unwrap().clone(); + let green = doc(&app).node(oval).unwrap().appearance.fill_paint(); + assert_ne!(red.appearance.fill_paint(), green); + // The first style: the top of the list's first row, or its first tile. + for (view, at) in [(View::SmallList, pos2(60.0, 9.0)), (View::Thumbnail, pos2(20.0, 20.0))] { + app.ui.graphic_styles_view = view; + frame_at(&mut app, at, vec![], none); + for payload in [PanelDrag::Art(vec![oval]), PanelDrag::Appearance(oval)] { + let n = names(&app); + let before = steps(&app); + // Held over the style with Alt it is outlined; without Alt it is not. + egui::DragAndDrop::set_payload(&ctx, payload.clone()); + assert!(!frame_at(&mut app, at, vec![egui::Event::PointerMoved(at)], none), "{view:?} {payload:?}: no outline without Alt"); + assert!(frame_at(&mut app, at, vec![egui::Event::PointerMoved(at)], alt), "{view:?} {payload:?}: outlined with Alt"); + assert_eq!(names(&app), n, "{view:?} {payload:?}: holding it there changes nothing"); + // Released there with Alt: Red takes the oval's look and keeps its name, place and id. + frame_at(&mut app, at, release(at, alt), alt); + let d = doc(&app); + assert_eq!(names(&app), n, "{view:?} {payload:?}"); + let g = d.graphic_style("Red").unwrap(); + assert_eq!((g.id, g.appearance.fill_paint()), (red.id, green.clone()), "{view:?} {payload:?}"); + assert_eq!(d.node(rect).unwrap().appearance.fill_paint(), green, "{view:?} {payload:?}: the linked rectangle follows"); + assert_eq!(d.node(rect).unwrap().extras().graphic_style, Some(red.id)); + assert_eq!(d.node(oval).unwrap().extras().graphic_style, Some(red.id), "{view:?} {payload:?}: the oval is linked"); + assert_eq!(steps(&app), before + 1, "{view:?} {payload:?}: one undo step"); + app.run("edit.undo", json!({})).unwrap(); + let d = doc(&app); + assert_eq!(d.graphic_style("Red").unwrap().appearance, red.appearance, "{view:?} {payload:?}: undo restores the style"); + assert_eq!(d.node(oval).unwrap().extras().graphic_style, None); + assert_eq!(d.node(rect).unwrap().appearance.fill_paint(), red.appearance.fill_paint()); + } + + // Without Alt the oval becomes a new style at the end, and Red stays as it was. + let n = names(&app); + egui::DragAndDrop::set_payload(&ctx, PanelDrag::Art(vec![oval])); + frame_at(&mut app, at, release(at, none), none); + assert_eq!(names(&app).len(), n.len() + 1, "{view:?}"); + assert_eq!(doc(&app).graphic_style("Red").unwrap().appearance, red.appearance, "{view:?}"); + app.run("edit.undo", json!({})).unwrap(); + + // A style dragged onto Red without Alt moves and replaces nothing. + let last = n.last().unwrap().clone(); + egui::DragAndDrop::set_payload(&ctx, PanelDrag::GraphicStyle(last.clone())); + frame_at(&mut app, at, release(at, none), none); + assert_eq!(names(&app)[0], last, "{view:?}"); + assert_eq!(doc(&app).graphic_style("Red").unwrap().appearance, red.appearance, "{view:?}"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(names(&app), n, "{view:?}"); + + // The rectangle that is linked to Red with its look, an empty drag of art and an object + // that is gone change nothing and record nothing. + let before = steps(&app); + for payload in [PanelDrag::Art(vec![rect]), PanelDrag::Appearance(rect), PanelDrag::Art(vec![]), PanelDrag::Art(vec![NodeId(9999)])] { + egui::DragAndDrop::set_payload(&ctx, payload.clone()); + frame_at(&mut app, at, release(at, alt), alt); + assert_eq!(names(&app), n, "{view:?} {payload:?}"); + assert_eq!(doc(&app).graphic_style("Red").unwrap().appearance, red.appearance, "{view:?} {payload:?}"); + assert_eq!(steps(&app), before, "{view:?} {payload:?}"); + } + } + } + + /// A style dropped on another with Alt held replaces that style's look with its own: the + /// replaced style keeps its name, place and id, and its art follows, in one undo step; the + /// dragged style and its art stay as they are. Without Alt the style moves; dropped on itself + /// it does nothing. + #[test] + fn a_style_dropped_on_another_with_alt_replaces_that_style() { + let mut app = app(); + let rect = app.session.active().unwrap().doc.layers[0].children().unwrap()[0].id; + app.run("paint.setFill", json!({"color": "#ff0000", "ids": [rect.0]})).unwrap(); + app.run("graphicStyle.new", json!({"name": "Red", "id": rect.0})).unwrap(); + app.run("graphicStyle.move", json!({"name": "Red", "to": 0})).unwrap(); + app.run("shape.ellipse", json!({"x": 60, "y": 60, "width": 20, "height": 20})).unwrap(); + let oval = app.session.active().unwrap().selection.objects[0]; + app.run("paint.setFill", json!({"color": "#00ff00", "ids": [oval.0]})).unwrap(); + app.run("graphicStyle.new", json!({"name": "Green", "id": oval.0})).unwrap(); + let ctx = egui::Context::default(); + let screen = Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(260.0, 600.0))); + // One frame of the panel with `events` and `modifiers` held: whether a drop-target outline + // the size of one style's tile or row is drawn around `at`. + let frame_at = |app: &mut VectorcraftApp, at: egui::Pos2, events: Vec, modifiers: egui::Modifiers| { + let events = std::iter::once(egui::Event::ModifiersChanged(modifiers)).chain(events).collect(); + let mut out = ctx.run_ui(egui::RawInput { screen_rect: screen, events, ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + let accent = Tokens::get(&ctx).accent; + out.shapes.iter().any(|c| match &c.shape { + egui::Shape::Rect(r) => r.stroke.width == 1.5 && r.stroke.color == accent && r.rect.contains(at) && r.rect.height() < 45.0, + _ => false, + }) + }; + let release = |at: egui::Pos2, modifiers: egui::Modifiers| { + let up = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers }; + vec![egui::Event::PointerMoved(at), up] + }; + let (none, alt) = (egui::Modifiers::default(), egui::Modifiers::ALT); + let doc = |app: &VectorcraftApp| app.session.active().unwrap().doc.clone(); + let steps = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len(); + let (red, green) = (doc(&app).graphic_style("Red").unwrap().clone(), doc(&app).graphic_style("Green").unwrap().clone()); + let (red_fill, green_fill) = (red.appearance.fill_paint(), green.appearance.fill_paint()); + assert_ne!(red_fill, green_fill); + // The first style: the top of the list's first row, or its first tile. + for (view, at) in [(View::SmallList, pos2(60.0, 9.0)), (View::Thumbnail, pos2(20.0, 20.0))] { + app.ui.graphic_styles_view = view; + frame_at(&mut app, at, vec![], none); + let n = names(&app); + assert_eq!(n[0], "Red", "{view:?}"); + let before = steps(&app); + // Held over Red with Alt it is outlined; without Alt it is not (the insertion marker shows instead). + egui::DragAndDrop::set_payload(&ctx, PanelDrag::GraphicStyle("Green".into())); + assert!(!frame_at(&mut app, at, vec![egui::Event::PointerMoved(at)], none), "{view:?}: no outline without Alt"); + assert!(frame_at(&mut app, at, vec![egui::Event::PointerMoved(at)], alt), "{view:?}: outlined with Alt"); + assert_eq!((names(&app), steps(&app)), (n.clone(), before), "{view:?}: holding it there changes nothing"); + + // Released there with Alt: Red takes Green's look and keeps its name, place and id. + frame_at(&mut app, at, release(at, alt), alt); + let d = doc(&app); + assert_eq!(names(&app), n, "{view:?}: no style moves"); + let g = d.graphic_style("Red").unwrap(); + assert_eq!((g.id, &g.appearance), (red.id, &green.appearance), "{view:?}"); + assert_eq!(d.node(rect).unwrap().appearance.fill_paint(), green_fill, "{view:?}: the linked rectangle follows"); + assert_eq!(d.node(rect).unwrap().extras().graphic_style, Some(red.id), "{view:?}"); + assert_eq!(d.graphic_style("Green").unwrap(), &green, "{view:?}: Green stays as it was"); + assert_eq!(d.node(oval).unwrap().extras().graphic_style, Some(green.id), "{view:?}: the oval stays linked to Green"); + assert_eq!(steps(&app), before + 1, "{view:?}: one undo step"); + app.run("edit.undo", json!({})).unwrap(); + let d = doc(&app); + assert_eq!(d.graphic_style("Red").unwrap(), &red, "{view:?}: undo restores the style"); + assert_eq!(d.node(rect).unwrap().appearance.fill_paint(), red_fill, "{view:?}"); + assert_eq!(d.node(rect).unwrap().extras().graphic_style, Some(red.id), "{view:?}"); + + // Red dropped on itself with Alt changes nothing and records nothing. + egui::DragAndDrop::set_payload(&ctx, PanelDrag::GraphicStyle("Red".into())); + frame_at(&mut app, at, release(at, alt), alt); + assert_eq!((names(&app), steps(&app)), (n.clone(), before), "{view:?}"); + assert_eq!(doc(&app).graphic_style("Red").unwrap(), &red, "{view:?}"); + + // Without Alt, Green moves before Red and Red keeps its look. + egui::DragAndDrop::set_payload(&ctx, PanelDrag::GraphicStyle("Green".into())); + frame_at(&mut app, at, release(at, none), none); + assert_eq!(names(&app)[0], "Green", "{view:?}"); + assert_eq!(doc(&app).graphic_style("Red").unwrap(), &red, "{view:?}"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(names(&app), n, "{view:?}"); + } + } + #[test] fn shift_click_selects_a_range_and_cmd_click_adds_or_removes_one_style() { let mut app = app(); diff --git a/crates/ui-egui/src/panels/image_trace.rs b/crates/ui-egui/src/panels/image_trace.rs index bca4192b61..bae86b0c83 100644 --- a/crates/ui-egui/src/panels/image_trace.rs +++ b/crates/ui-egui/src/panels/image_trace.rs @@ -17,7 +17,7 @@ use vectorcraft_doc::{Node, NodeId, NodeKind, TraceView}; use vectorcraft_engine::cmd::TracePresetChange; use vectorcraft_engine::cmd::swatchlib::DOCUMENT_SWATCHES; -use super::{first_selected, pstate, set_pstate, swatches}; +use super::{first_node, pstate, set_pstate, swatches}; use crate::VectorcraftApp; use crate::widgets::{self, menu_item}; @@ -152,10 +152,10 @@ pub(crate) fn is_trace(n: &Node) -> bool { /// The object Trace acts on: the first selected image or Image Trace object in paint order, as /// `imageTrace.make` takes it, else the first selected object. -fn target_node(app: &VectorcraftApp) -> Option { +fn target_node(app: &VectorcraftApp) -> Option<&Node> { let st = app.session.active()?; let traceable = |n: &&Node| is_trace(n) || matches!(n.kind, NodeKind::Image(_)); - st.selection.in_paint_order(&st.doc).into_iter().find_map(|id| st.doc.node(id).filter(traceable).cloned()).or_else(|| first_selected(app)) + st.selection.in_paint_order(&st.doc).into_iter().find_map(|id| st.doc.node(id).filter(traceable)).or_else(|| first_node(app)) } /// The active document and the object Trace acts on. @@ -166,7 +166,7 @@ fn target_key(app: &VectorcraftApp) -> Option<(u64, NodeId)> { /// What Trace acts on: an Image Trace object (with its stored settings), a plain image, or neither. fn target(app: &VectorcraftApp) -> (bool, bool, Option) { let Some(n) = target_node(app) else { return (false, false, None) }; - (is_trace(&n), matches!(n.kind, NodeKind::Image(_)), n.extras().trace.as_deref().cloned()) + (is_trace(n), matches!(n.kind, NodeKind::Image(_)), n.extras().trace.as_deref().cloned()) } /// Whether any selected object is an Image Trace object, wherever it is in the selection. diff --git a/crates/ui-egui/src/panels/image_trace/tests.rs b/crates/ui-egui/src/panels/image_trace/tests.rs index 7f686db45a..333f6bb59b 100644 --- a/crates/ui-egui/src/panels/image_trace/tests.rs +++ b/crates/ui-egui/src/panels/image_trace/tests.rs @@ -2,7 +2,7 @@ use super::super::tests_long_popups::{ PopupWindow, assert_last_row_scrolls_into_view, assert_rows_stay_on_one_line, assert_short_list_does_not_scroll, }; use super::*; -use crate::panels::library_panel; +use crate::panels::{first_selected, library_panel}; use egui::{Event, PointerButton, Pos2, Rect, vec2}; /// One headless frame of the panel (and its menu) with `events`: the texts drawn, with where. @@ -209,7 +209,10 @@ fn a_large_image_traced_as_a_flat_logo_shows_the_size_it_was_traced_at() { app.run("file.place", json!({"name": "logo.png", "dataBase64": data, "link": false})).unwrap(); trace_with(&mut app, "Flat Logo"); assert!(target(&app).2.is_some(), "the image is traced: {}", app.ui.status); - assert_eq!(app.ui.status, "Flat Logo traced the image at 801 × 801 pixels, averaged down from 1602 × 1602."); + let note = "Flat Logo traced the image at 801 × 801 pixels, averaged down from 1602 × 1602."; + let status = format!("Traced with 1 note: {note}"); + assert_eq!(app.ui.status, status); + assert_eq!(app.ui.status_notes, Some((status, vec![note.to_string()]))); } #[test] diff --git a/crates/ui-egui/src/panels/info.rs b/crates/ui-egui/src/panels/info.rs index 2e81441654..19fe505c0c 100644 --- a/crates/ui-egui/src/panels/info.rs +++ b/crates/ui-egui/src/panels/info.rs @@ -14,7 +14,7 @@ use crate::VectorcraftApp; use crate::theme::Tokens; use crate::widgets::{self, menu_item}; -/// Colour values in the colour's own model, like Illustrator's Info panel. +/// Color values in the color's own model, for the Info panel. pub fn color_values(c: &Color) -> Vec<(&'static str, String)> { match *c { Color::Rgb { r, g, b } => vec![("R", format!("{:.0}", r * 255.0)), ("G", format!("{:.0}", g * 255.0)), ("B", format!("{:.0}", b * 255.0))], diff --git a/crates/ui-egui/src/panels/layers.rs b/crates/ui-egui/src/panels/layers.rs index 6e8c2648fa..5871db03b3 100644 --- a/crates/ui-egui/src/panels/layers.rs +++ b/crates/ui-egui/src/panels/layers.rs @@ -221,6 +221,14 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { reveal = rows.first().copied(); ui.data_mut(|d| d.insert_temp(key("seen"), rows.clone())); } + // Locate Object or Locate Layer (`layer.locate`): the located row is revealed each time, also + // when it was already highlighted and a layer around it was closed since or the list scrolled + // away. A request for a row no longer highlighted is dropped. + let locate = app.session.active_mut().and_then(|st| st.locate_reveal.take()).filter(|id| rows.contains(id)); + if let Some(id) = locate { + open_around(app, &doc, &[id]); + reveal = Some(id); + } let highlighted = reveal.is_some(); // A new active layer (a canvas selection highlights no row): reveal it too, unless a row // highlighted in the panel holds the view. @@ -330,15 +338,17 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // The column drag: live while it lasts, one undo step when the button is released. let released = ui.input(|i| i.pointer.any_released()); // Layers dragged into the empty space under the last row go below the bottom layer (there is - // no row there to take the drop). + // no row there to take the drop). The bottom layer itself goes there only as an Alt copy, + // which lands below it; moved, it would stay where it is (#8237). let below = list_rect.top() - scrolled.inner.state.clamped_offset().y + list.len() as f32 * view.h; + let alt = ui.input(|i| i.modifiers.alt); if query.is_empty() && !app.ui.layers_filter.is_on() && let Some(drag) = egui::DragAndDrop::payload::(ui.ctx()) && let LayersDrag::Rows(ids) = &*drag && let Some(bottom) = doc.layers.first() && !ids.is_empty() - && !ids.contains(&bottom.id) + && (alt || !ids.contains(&bottom.id)) && ids.iter().all(|i| doc.node(*i).is_some_and(Node::is_layer)) && let Some(p) = ui.input(|i| i.pointer.hover_pos()) && list_rect.contains(p) diff --git a/crates/ui-egui/src/panels/layers/controls.rs b/crates/ui-egui/src/panels/layers/controls.rs index 4cea41db75..573c18adb9 100644 --- a/crates/ui-egui/src/panels/layers/controls.rs +++ b/crates/ui-egui/src/panels/layers/controls.rs @@ -83,7 +83,7 @@ pub(super) fn bottom_bar(app: &mut VectorcraftApp, ui: &mut Ui, view: &View, doc actions.push(("layer.new".into(), json!({"top": m.command}))); } } - // Rows dropped on the trash are deleted, on New Layer duplicated, as in Illustrator. Both are + // Rows dropped on the trash are deleted, on New Layer duplicated. Both are // outlined while rows (or, on the trash, a target circle) hang over them. Guide rows dropped on // the trash delete their guides (`guide.remove`); New Layer does not take them. for (button, cmd) in [(&trash, "ui.layerDelete"), (&new_layer, "layer.duplicate")] { @@ -116,8 +116,11 @@ pub(super) fn bottom_bar(app: &mut VectorcraftApp, ui: &mut Ui, view: &View, doc if widgets::icon_button(&mut child, "frame", tl!("Make/Release Clipping Mask"), false, 24.0).clicked() { actions.push(("layer.clippingMask.toggle".into(), json!({}))); } - if widgets::icon_button(&mut child, "search", tl!("Locate Object"), false, 24.0).clicked() { - actions.push(("layer.locate".into(), json!({}))); + // With Show Layers Only on, Locate Object becomes Locate Layer: it highlights the layer row. + let layers_only = view.opts.layers_only; + let locate = if layers_only { tl!("Locate Layer") } else { tl!("Locate Object") }; + if widgets::icon_button(&mut child, "search", locate, false, 24.0).clicked() { + actions.push(("layer.locate".into(), json!({ "layersOnly": layers_only }))); } } @@ -132,6 +135,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { let current = st.current_layer(); let has_sel = !st.selection.is_empty(); let isolated = st.isolation.is_some(); + let layers_only = app.ui.layers_panel.layers_only; let targets: Vec = if rows.is_empty() { current.into_iter().collect() } else { rows.clone() }; let one_container = match targets.as_slice() { [id] => doc.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. })), @@ -166,7 +170,11 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { }); items.extend([ None, - Some(("Locate Object", "layer.locate", json!({}), has_sel, false)), + Some(if layers_only { + ("Locate Layer", "layer.locate", json!({"layersOnly": true}), has_sel, false) + } else { + ("Locate Object", "layer.locate", json!({}), has_sel, false) + }), // Sentinel: rendered as the Save Selection submenu (the Select menu's saved-selection items). Some(("Save Selection", "", json!({}), true, false)), None, diff --git a/crates/ui-egui/src/panels/layers/rows.rs b/crates/ui-egui/src/panels/layers/rows.rs index 62e32f1097..447133e7d6 100644 --- a/crates/ui-egui/src/panels/layers/rows.rs +++ b/crates/ui-egui/src/panels/layers/rows.rs @@ -510,9 +510,10 @@ fn row_context_menu(ui: &mut Ui, view: &View, n: &Node, collect_ids: &[u64], out } } ui.separator(); - // Locate Object - if widgets::menu_item(ui, "Locate Object", true, false) { - out.actions.push(("layer.locate".into(), json!({ "id": n.id.0 }))); + // Locate Object, or Locate Layer with Show Layers Only on + let layers_only = view.opts.layers_only; + if widgets::menu_item(ui, if layers_only { "Locate Layer" } else { "Locate Object" }, true, false) { + out.actions.push(("layer.locate".into(), json!({ "id": n.id.0, "layersOnly": layers_only }))); ui.close(); } ui.separator(); @@ -674,15 +675,20 @@ fn drop_target(ui: &Ui, view: &View, n: &Node, r: egui::Rect, indent: f32, open: return; } }; - // Never into itself or a row inside it. + // Never into itself or a row inside it. With Alt, rows held over one of their own rows copy + // beside it, above or below, as `layer.move` places a copy there (#8237). + let alt = ui.input(|i| i.modifiers.alt); + let beside_itself = alt && matches!(&*drag, LayersDrag::Rows(_)) && moving.contains(&n.id); let around = doc.ancestry(n.id).unwrap_or_default(); - if moving.is_empty() || moving.iter().any(|m| around.contains(m)) { + if moving.is_empty() || moving.iter().any(|m| around.contains(m) && !(beside_itself && *m == n.id)) { return; } let Some(p) = ui.input(|i| i.pointer.hover_pos()) else { return }; let rel = (p.y - r.top()) / r.height().max(1.0); let inside = takes(n, &drag, &moving, doc); let place = match &*drag { + LayersDrag::Rows(_) if beside_itself && rel < 0.5 => Place::Above, + LayersDrag::Rows(_) if beside_itself => Place::Below, LayersDrag::Art if inside => Place::Inside, LayersDrag::Art => Place::Above, LayersDrag::Rows(_) if inside && rel >= 0.25 && (rel <= 0.75 || open) => Place::Inside, diff --git a/crates/ui-egui/src/panels/layers/tests.rs b/crates/ui-egui/src/panels/layers/tests.rs index 2570e77df7..1f03ee5d86 100644 --- a/crates/ui-egui/src/panels/layers/tests.rs +++ b/crates/ui-egui/src/panels/layers/tests.rs @@ -1462,6 +1462,57 @@ fn dragging_a_layer_into_the_empty_space_under_the_rows_moves_it_to_the_bottom() assert_eq!(ids(&app), vec![top, bottom], "the top layer is now the bottom one"); } +/// #8237: with Alt, the top layer dropped on the top edge of its own row copies above itself, and +/// the bottom layer dropped in the empty space under the list copies below itself. Without Alt, +/// neither drop changes anything. +#[test] +fn alt_dragging_the_top_layer_up_or_the_bottom_layer_down_copies_it() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + app.session.execute("layer.new", &json!({"top": true})).unwrap(); + let ids = |app: &VectorcraftApp| app.session.active().unwrap().doc.layers.iter().map(|l| l.id).collect::>(); + let [bottom, top] = ids(&app)[..] else { panic!("two layers") }; + let ctx = egui::Context::default(); + // Rows: the top layer, the bottom layer, then empty space. + let (circles, _) = frame(&mut app, &ctx, vec![], false); + assert_eq!(circles.len(), 2); + let row = |y: f32| egui::pos2(150.0, y); + let top_edge = |y: f32| egui::pos2(150.0, y - ROW_MEDIUM * 0.4); + let under = |y: f32| egui::pos2(150.0, y + 3.0 * ROW_MEDIUM); + drag(&mut app, &ctx, row(circles[0].y), top_edge(circles[0].y), false); + drag(&mut app, &ctx, row(circles[1].y), under(circles[1].y), false); + assert_eq!(ids(&app), vec![bottom, top], "moved onto their own places, nothing changes"); + drag(&mut app, &ctx, row(circles[0].y), top_edge(circles[0].y), true); + let after = ids(&app); + assert_eq!((after.len(), &after[..2]), (3, &[bottom, top][..]), "a copy above the top layer"); + // Rows: the copy, the top layer, the bottom layer, then empty space. + let (circles, _) = frame(&mut app, &ctx, vec![], false); + assert_eq!(circles.len(), 3); + drag(&mut app, &ctx, row(circles[2].y), under(circles[2].y), true); + let after = ids(&app); + assert_eq!((after.len(), after[1]), (4, bottom), "a copy below the bottom layer"); +} + +/// #8237: a document's only layer, Alt-dragged up onto its own row or down into the empty space, +/// is copied above or below itself. +#[test] +fn a_lone_layer_alt_dragged_up_or_down_is_copied() { + for (up, at) in [(true, 0), (false, 1)] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let ids = |app: &VectorcraftApp| app.session.active().unwrap().doc.layers.iter().map(|l| l.id).collect::>(); + let [only] = ids(&app)[..] else { panic!("one layer") }; + let ctx = egui::Context::default(); + let (circles, _) = frame(&mut app, &ctx, vec![], false); + assert_eq!(circles.len(), 1); + let y = circles[0].y; + let to = if up { y - ROW_MEDIUM * 0.4 } else { y + 3.0 * ROW_MEDIUM }; + drag(&mut app, &ctx, egui::pos2(150.0, y), egui::pos2(150.0, to), true); + let after = ids(&app); + assert_eq!((after.len(), after[at]), (2, only), "up: {up}"); + } +} + #[test] fn dragging_rows_moves_them_into_other_layers_and_alt_copies() { let (mut app, [layer, sub, g, _, a, c]) = nested(); @@ -2133,6 +2184,97 @@ fn the_panel_menu_lists_every_operation() { } } +/// With Show Layers Only on, Locate Object becomes Locate Layer in the panel menu and a row's +/// menu, and the bottom bar's Locate button highlights the sublayer holding the selected art, +/// opening the layer around it. Off, the button highlights the art's own row. +#[test] +fn with_show_layers_only_locate_object_becomes_locate_layer() { + let (mut app, [layer, sub, _, b, _, _]) = nested(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let shown = |app: &mut VectorcraftApp, events: Vec, f: fn(&mut VectorcraftApp, &mut egui::Ui)| { + super::super::tests_appearance::frame_events(&ctx, app, events, f).into_iter().map(|(t, _)| t.trim().to_string()).collect::>() + }; + let has = |texts: &[String], s: &str| texts.iter().any(|t| t == s); + app.session.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + let off = shown(&mut app, vec![], menu); + assert!(has(&off, "Locate Object") && !has(&off, "Locate Layer"), "{off:?}"); + let locate = |app: &mut VectorcraftApp| { + let at = bar_buttons(app, &ctx)[4]; + click_with(app, &ctx, at, egui::Modifiers::NONE); + }; + locate(&mut app); + assert_eq!(rows_of(&app), vec![b], "off: the art's own row"); + + app.ui.layers_panel.layers_only = true; + let on = shown(&mut app, vec![], menu); + assert!(has(&on, "Locate Layer") && !has(&on, "Locate Object"), "{on:?}"); + app.session.active_mut().unwrap().layers_open.set(layer, false); + shown(&mut app, vec![], show); + locate(&mut app); + assert_eq!(rows_of(&app), vec![sub], "on: the sublayer holding the art"); + shown(&mut app, vec![], show); + assert!(app.session.active().unwrap().layers_open.contains(layer), "the layer around the sublayer opens"); + assert!(has(&shown(&mut app, vec![], show), "Sub"), "the sublayer's row shows"); + + // A row's menu says Locate Layer too. + let c = frame(&mut app, &ctx, vec![], false).0; + let at = egui::pos2(150.0, c[0].y); + let right = egui::PointerButton::Secondary; + for e in [egui::Event::PointerMoved(at), button_by(at, true, right), button_by(at, false, right)] { + frame(&mut app, &ctx, vec![e], false); + } + let row_menu = shown(&mut app, vec![], show); + assert!(has(&row_menu, "Locate Layer") && !has(&row_menu, "Locate Object"), "{row_menu:?}"); +} + +/// Locate Layer or Locate Object run again on the row it already highlighted reveals that row +/// again: the layers around it that were closed since open, once per Locate. +#[test] +fn a_repeated_locate_reveals_the_row_it_already_highlighted() { + let (mut app, [layer, sub, g, b, _, _]) = nested(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let draw = |app: &mut VectorcraftApp| { + super::super::tests_appearance::frame_events(&ctx, app, vec![], show).into_iter().map(|(t, _)| t.trim().to_string()).collect::>() + }; + let open = |app: &VectorcraftApp, id: NodeId| app.session.active().unwrap().layers_open.contains(id); + let close = |app: &mut VectorcraftApp, ids: &[NodeId]| { + for id in ids { + app.session.active_mut().unwrap().layers_open.set(*id, false); + } + }; + app.session.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + + // Locate Layer: the sublayer stays highlighted while its layer is closed, and Locate Layer again opens it. + app.ui.layers_panel.layers_only = true; + app.session.execute("layer.locate", &json!({"layersOnly": true})).unwrap(); + draw(&mut app); + assert_eq!(rows_of(&app), vec![sub]); + close(&mut app, &[layer]); + assert!(!draw(&mut app).iter().any(|t| t == "Sub"), "the closed layer hides the sublayer"); + app.session.execute("layer.locate", &json!({"layersOnly": true})).unwrap(); + assert!(draw(&mut app).iter().any(|t| t == "Sub"), "the sublayer's row shows again"); + assert!(open(&app, layer), "the layer around the sublayer opens again"); + assert_eq!(rows_of(&app), vec![sub]); + // Once per Locate: a later frame leaves a layer closed after that alone. + close(&mut app, &[layer]); + draw(&mut app); + assert!(!open(&app, layer), "a frame without a Locate opens nothing"); + + // Locate Object: the same for the object's row inside a closed sublayer and group. + app.ui.layers_panel.layers_only = false; + app.session.execute("layer.locate", &json!({})).unwrap(); + draw(&mut app); + assert_eq!(rows_of(&app), vec![b]); + close(&mut app, &[sub, g]); + draw(&mut app); + app.session.execute("layer.locate", &json!({})).unwrap(); + draw(&mut app); + assert!(open(&app, layer) && open(&app, sub) && open(&app, g), "the layers and group around the object open again"); + assert_eq!(rows_of(&app), vec![b]); +} + /// ≡ › Save Selection lists the saved selections: choosing one recalls it, Update Selection /// makes it hold the selected objects, and Save Selection… opens the name dialog. #[test] diff --git a/crates/ui-egui/src/panels/library_panel.rs b/crates/ui-egui/src/panels/library_panel.rs index fdfb2f7c3b..01c3af49a2 100644 --- a/crates/ui-egui/src/panels/library_panel.rs +++ b/crates/ui-egui/src/panels/library_panel.rs @@ -576,7 +576,7 @@ fn set(app: &mut VectorcraftApp, panel: &str, mut params: Value) { /// (symbol and brush libraries: any document). pub(crate) fn library_pick_filters(kind: &str) -> Vec<(&'static str, &'static [&'static str])> { match kind { - super::swatches::SwatchLibraries::KIND => fileio::library_open_filters("Swatch libraries", swatchlib::LIBRARY_EXTS).collect(), + super::swatches::SwatchLibraries::KIND => fileio::library_open_filters("Swatch libraries", swatchlib::LIBRARY_PICK_EXTS).collect(), super::graphic_styles::GraphicStyleLibraries::KIND => fileio::library_open_filters("Graphic Style Libraries", &[STYLES_EXT]).collect(), _ => fileio::builtin_open_filters().collect(), } diff --git a/crates/ui-egui/src/panels/links.rs b/crates/ui-egui/src/panels/links.rs index 611c9e472a..cf68e1d5bd 100644 --- a/crates/ui-egui/src/panels/links.rs +++ b/crates/ui-egui/src/panels/links.rs @@ -54,7 +54,7 @@ impl Default for Options { /// `links.list` and the first selected image's `links.info`, with what they were fetched for. #[derive(Clone, Default)] -struct Cache { +pub(super) struct Cache { /// (document uid, revision, show, sort, Show DCS Transparency Interactions). key: Option<(u64, u64, &'static str, Option<&'static str>, bool)>, at: f64, @@ -83,23 +83,23 @@ fn set_options(ctx: &egui::Context, f: impl FnOnce(&mut Options)) { } /// The rows to show (cached per document revision, the files looked at again every [`RECHECK`] -/// seconds) and the Link Info of the first selected image when the section is open. -fn cached(app: &mut VectorcraftApp, ctx: &egui::Context, o: &Options) -> Option { +/// seconds) and the Link Info of the first selected image when the section is open. A frame that +/// fetches nothing returns the stored cache without copying it and stores nothing. +fn cached(app: &mut VectorcraftApp, ctx: &egui::Context, o: &Options) -> Option> { let st = app.session.active()?; let key = Some((st.uid, st.revision, o.show, o.sort, o.dcs)); let first = selected_links(app, ctx).first().copied(); let now = ctx.input(|i| i.time); - let mut c: Cache = pstate(ctx, "links-cache"); + let mut c: std::sync::Arc = 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); + let list = app.session.execute("links.list", &json!({ "show": o.show, "sort": o.sort, "dcsTransparency": o.dcs })).ok()?; // 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. 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"] + let want: std::collections::HashSet = list["links"] .as_array() .into_iter() .flatten() @@ -110,18 +110,22 @@ fn cached(app: &mut VectorcraftApp, ctx: &egui::Context, o: &Options) -> Option< .collect(); // 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 { + let nested = if same_doc && want.iter().all(|id| c.nested_node(*id).is_some()) { + c.nested.clone() + } else { + match doc { Some(d) if !want.is_empty() => stored_objects(d, want), _ => vec![], - }; - } + } + }; + c = std::sync::Arc::new(Cache { key, at: now, list, info: None, nested }); } let want = first.filter(|_| o.info); if stale || c.info.as_ref().map(|(id, _)| *id) != want { - c.info = want.and_then(|id| Some((id, app.session.execute("links.info", &json!({ "id": id })).ok()?))); + let info = want.and_then(|id| Some((id, app.session.execute("links.info", &json!({ "id": id })).ok()?))); + std::sync::Arc::make_mut(&mut c).info = info; + set_pstate(ctx, "links-cache", c.clone()); } - set_pstate(ctx, "links-cache", c.clone()); // Files change on disk without a frame of ours: look again later. ctx.request_repaint_after(std::time::Duration::from_secs_f64(RECHECK)); Some(c) @@ -335,6 +339,37 @@ pub(crate) fn unembed(app: &mut VectorcraftApp, id: u64, name: &str) { }); } +/// Whether Unembed… can act on `embedded` selected embedded images: one goes to a picked file, +/// several to a picked folder (the web downloads each one). +pub(crate) fn can_unembed(app: &VectorcraftApp, embedded: usize) -> bool { + match embedded { + 0 => false, + 1 => true, + _ => app.services.download.is_some() || app.services.pick_folder.is_some(), + } +} + +/// Write embedded images `ids` to new files in a picked folder and link each one to its file, in +/// one undo step (the web downloads each one and links none). +pub(crate) fn unembed_several(app: &mut VectorcraftApp, ids: Vec) { + if app.services.download.is_some() { + for id in ids { + unembed(app, id, ""); + } + return; + } + crate::picks::button(app, move |app| unembed_to_picked_folder(app, ids.clone())); +} + +fn unembed_to_picked_folder(app: &mut VectorcraftApp, ids: Vec) { + let Some(folder) = crate::picks::folder(app) else { return }; + let r = app.run("links.unembed", json!({ "ids": ids, "folder": folder })); + report(app, r, |v| { + let n = v["unembedded"].as_array().map_or(0, Vec::len); + crate::i18n::msg_n(n as u64, "Unembedded {n} image to {folder}", "Unembedded {n} images to {folder}", &[("folder", &folder)]) + }); +} + /// The UI commands `links.editOriginal` (open the linked file in its app) and `links.reveal` /// (show it in its folder) for image `id` (default: the selected linked image) → `{path}`. pub(crate) fn open_file(app: &mut VectorcraftApp, p: &Value, reveal: bool) -> Result { @@ -788,9 +823,10 @@ fn link_info(ui: &mut Ui, info: Option<&Value>, units: vectorcraft_doc::Unit) { pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { let o = options(ui.ctx()); // The rows the panel shows (the menu opens from it). - let list = pstate::(ui.ctx(), "links-cache").list; + let cache = pstate::>(ui.ctx(), "links-cache"); + let list = &cache.list; let selected = selected_links(app, ui.ctx()); - let sel = selected_rows(&list, &selected); + let sel = selected_rows(list, &selected); let linked = ids(&sel, |r| r["linked"] == true); let embedded: Vec<&Value> = sel.iter().copied().filter(|r| status_is(r, "embedded")).collect(); let any = !sel.is_empty(); @@ -834,12 +870,16 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { } }); } - if menu_item(ui, tl!("Unembed…"), embedded.len() == 1, false) - && let Some(r) = embedded.first() - && let Some(id) = r["id"].as_u64() - { - let name = r["name"].as_str().unwrap_or("Image").to_string(); - unembed(app, id, &name); + if menu_item(ui, tl!("Unembed…"), can_unembed(app, embedded.len()), false) { + match &embedded[..] { + [r] => { + if let Some(id) = r["id"].as_u64() { + let name = r["name"].as_str().unwrap_or("Image").to_string(); + unembed(app, id, &name); + } + } + rows => unembed_several(app, rows.iter().filter_map(|r| r["id"].as_u64()).collect()), + } } if menu_item(ui, tl!("Placement Options…"), any, false) { crate::menus::invoke(app, "ui.placementOptionsDialog", json!({ "ids": ids(&sel, |_| true) })); diff --git a/crates/ui-egui/src/panels/navigator.rs b/crates/ui-egui/src/panels/navigator.rs index 60eb4c18d0..c1307871db 100644 --- a/crates/ui-egui/src/panels/navigator.rs +++ b/crates/ui-egui/src/panels/navigator.rs @@ -2,7 +2,8 @@ //! cached by document revision, off the UI thread for heavy documents and not during drags: see //! [`crate::thumb_worker`]) with the view box you drag to pan, zoom out/in buttons, a zoom slider //! and a zoom field. Panel Options… sets the view box's color and whether the thumbnail draws -//! dashed lines as solid lines ([`PanelOptions`]). +//! dashed lines as solid lines, and the panel menu's View Artboard Contents Only (on by default) +//! limits the thumbnail to the art inside the artboards ([`PanelOptions`]). use std::sync::Arc; @@ -13,7 +14,6 @@ use vectorcraft_color::Color; use vectorcraft_doc::LAYER_COLORS; use vectorcraft_geom::{Point, Rect as DRect}; -use super::{pstate, set_pstate}; use crate::VectorcraftApp; use crate::theme::Tokens; use crate::thumb_worker::{Settle, ThumbWorker}; @@ -39,7 +39,8 @@ pub fn resolve(color: &str) -> Option<[u8; 3]> { Some([byte(0)?, byte(2)?, byte(4)?]) } -/// Navigator panel options (≡ › Panel Options…), kept with the UI state. +/// Navigator panel options (≡ › Panel Options… and ≡ › View Artboard Contents Only), kept with the +/// UI state. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] pub struct PanelOptions { @@ -48,12 +49,16 @@ pub struct PanelOptions { /// Draw Dashed Lines as Solid Lines (off by default): the thumbnail draws dashed strokes /// without their dashes. The canvas, printing and exports keep the dashes. pub solid_dashes: bool, + /// View Artboard Contents Only (the panel menu; on by default, and on for UI state saved + /// without it): the thumbnail fits the artboards and draws only the art inside them, cut at + /// each artboard's edges. Off, it also fits and draws the art on the pasteboard. + pub view_artboard_contents_only: bool, } impl Default for PanelOptions { fn default() -> Self { let [r, g, b] = VIEW_BOX_RED; - Self { color: Color::rgb8(r, g, b).to_hex(), solid_dashes: false } + Self { color: Color::rgb8(r, g, b).to_hex(), solid_dashes: false, view_artboard_contents_only: true } } } @@ -65,11 +70,11 @@ impl PanelOptions { } } -/// `ui.navigatorPanelOptions {color?, solidDashes?}`: with neither, open Panel Options on the -/// panel's options; otherwise set the ones given and answer the options. +/// `ui.navigatorPanelOptions {color?, solidDashes?, viewArtboardContentsOnly?}`: with none, open +/// Panel Options on the panel's options; otherwise set the ones given and answer the options. pub fn set_options(app: &mut VectorcraftApp, p: &Value) -> Result { - let (color, solid) = (p.get("color"), p.get("solidDashes")); - if color.is_none() && solid.is_none() { + let (color, solid, contents_only) = (p.get("color"), p.get("solidDashes"), p.get("viewArtboardContentsOnly")); + if color.is_none() && solid.is_none() && contents_only.is_none() { return crate::dialogs::navigator_panel_options::open(app); } let mut o = app.ui.navigator_panel.clone(); @@ -84,6 +89,10 @@ pub fn set_options(app: &mut VectorcraftApp, p: &Value) -> Result let key = "solidDashes"; o.solid_dashes = s.as_bool().ok_or_else(|| format!("`{key}` must be true or false"))?; } + if let Some(v) = contents_only { + let key = "viewArtboardContentsOnly"; + o.view_artboard_contents_only = v.as_bool().ok_or_else(|| format!("`{key}` must be true or false"))?; + } app.ui.navigator_panel = o; Ok(serde_json::to_value(&app.ui.navigator_panel).unwrap_or_default()) } @@ -218,10 +227,17 @@ impl Cache { } /// How the image `key` names is drawn: as exported (template layers and guides left out), -/// transparent, with images far smaller than they are sampling their mip levels, and with Draw -/// Dashed Lines as Solid Lines, dashed strokes without their dashes. +/// transparent, with images far smaller than they are sampling their mip levels, with Draw +/// Dashed Lines as Solid Lines, dashed strokes without their dashes, and with View Artboard +/// Contents Only, the art cut to the artboards (none in the gaps between them). fn image_options(key: ImageKey) -> vectorcraft_render::RenderOptions { - vectorcraft_render::RenderOptions { skip_templates: true, image_mips: true, solid_dashes: key.solid_dashes, ..Default::default() } + vectorcraft_render::RenderOptions { + skip_templates: true, + image_mips: true, + solid_dashes: key.solid_dashes, + trim: key.artboard_only, + ..Default::default() + } } thread_local! { @@ -282,7 +298,7 @@ fn view_box(region: DRect, thumb: Rect, canvas: Rect, v: &crate::state::View, ui pts } -/// Slider position (0..1) ↔ zoom percent on Illustrator's log range 3.13 %–64 000 %. +/// Slider position (0..1) ↔ zoom percent on a log range, 3.13 %–64 000 %. pub fn zoom_to_slider(z: f64) -> f64 { ((z.clamp(3.13, 64000.0)).ln() - 3.13f64.ln()) / (64000f64.ln() - 3.13f64.ln()) } @@ -296,7 +312,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { super::empty_state(ui, "map", tl!("No document"), tl!("Open a document to navigate it.")); return; }; - let artboard_only: bool = pstate(ui.ctx(), "nav-ab-only"); + let artboard_only = app.ui.navigator_panel.view_artboard_contents_only; let doc = st.doc.clone(); let (uid, revision) = (st.uid, st.revision); // A drag in progress: every pointer move makes a new revision. The image waits for its end. @@ -373,9 +389,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { - let ab: bool = pstate(ui.ctx(), "nav-ab-only"); - if menu_item(ui, tl!("View Artboard Only"), true, ab) { - set_pstate(ui.ctx(), "nav-ab-only", !ab); + let ab = app.ui.navigator_panel.view_artboard_contents_only; + if menu_item(ui, tl!("View Artboard Contents Only"), true, ab) { + app.run("ui.navigatorPanelOptions", json!({"viewArtboardContentsOnly": !ab})).ok(); } if menu_item(ui, tl!("Panel Options…"), true, false) { app.run("ui.navigatorPanelOptions", json!({})).ok(); @@ -547,7 +563,7 @@ mod tests { let shown = || CACHE.with(|c| c.borrow().shown.map(|(k, _)| k.solid_dashes)); assert_eq!(shown(), Some(false)); let set = app.run("ui.navigatorPanelOptions", json!({"color": "light blue", "solidDashes": true})).unwrap(); - assert_eq!(set, json!({"color": "#4f80ff", "solidDashes": true})); + assert_eq!(set, json!({"color": "#4f80ff", "solidDashes": true, "viewArtboardContentsOnly": true})); assert_eq!((boxes(&mut app, red), boxes(&mut app, blue)), (0, 1)); for _ in 0..12 { boxes(&mut app, blue); @@ -560,11 +576,15 @@ mod tests { json!({"color": "#f00"}), json!({"color": null}), json!({"color": "Red", "solidDashes": "yes"}), + json!({"color": "Red", "viewArtboardContentsOnly": "no"}), + json!({"solidDashes": false, "viewArtboardContentsOnly": 0}), + json!({"viewArtboardContentsOnly": null}), ]; for bad in bad { assert!(app.run("ui.navigatorPanelOptions", bad.clone()).is_err(), "{bad}"); } - assert_eq!(serde_json::to_value(&app.ui.navigator_panel).unwrap(), json!({"color": "#4f80ff", "solidDashes": true}), "nothing changed"); + let want = json!({"color": "#4f80ff", "solidDashes": true, "viewArtboardContentsOnly": true}); + assert_eq!(serde_json::to_value(&app.ui.navigator_panel).unwrap(), want, "nothing changed"); app.run("ui.navigatorPanelOptions", json!({"color": "#123456"})).unwrap(); assert!(app.ui.navigator_panel.solid_dashes, "an option left out keeps its value"); } @@ -600,6 +620,113 @@ mod tests { assert_eq!(draw(&line(false), on), solid, "a solid stroke draws as it did"); } + /// View Artboard Contents Only is on by default, and on for UI state saved without it, whether + /// the panel's options are missing or saved before the option existed; a saved off stays off. + #[test] + fn view_artboard_contents_only_is_on_by_default_and_a_saved_off_stays_off() { + assert!(PanelOptions::default().view_artboard_contents_only); + let none: crate::UiState = serde_json::from_value(json!({})).unwrap(); + assert!(none.navigator_panel.view_artboard_contents_only, "UI state saved without the panel's options"); + let older: crate::UiState = serde_json::from_value(json!({"navigator_panel": {"color": "#123456", "solidDashes": true}})).unwrap(); + let o = &older.navigator_panel; + assert!(o.view_artboard_contents_only && o.solid_dashes && o.color == "#123456", "options saved before the option existed: {o:?}"); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + assert!(app.ui.navigator_panel.view_artboard_contents_only); + let set = app.run("ui.navigatorPanelOptions", json!({"viewArtboardContentsOnly": false})).unwrap(); + assert_eq!(set, json!({"color": "#ff3030", "solidDashes": false, "viewArtboardContentsOnly": false})); + let back: crate::UiState = serde_json::from_value(serde_json::to_value(&app.ui).unwrap()).unwrap(); + assert!(!back.navigator_panel.view_artboard_contents_only, "a saved off stays off"); + } + + /// The panel menu's View Artboard Contents Only starts checked, and a click turns it off (the + /// same option `ui.navigatorPanelOptions` sets), then on again. + #[test] + fn view_artboard_contents_only_is_checked_in_the_panel_menu_and_a_click_toggles_it() { + use crate::widgets::accessibility_tests::{named, tree}; + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + named(&tree(|ui| menu(&mut app, ui)), "✓ View Artboard Contents Only"); + let ctx = egui::Context::default(); + let screen = Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(240.0, 400.0))); + let raw = |events| egui::RawInput { events, screen_rect: screen, ..Default::default() }; + let click = |app: &mut VectorcraftApp| { + let mut out = ctx.run_ui(raw(vec![]), |ui| menu(app, ui)); + out.textures_delta.clear(); + let item = out + .shapes + .iter() + .find_map(|c| match &c.shape { + egui::Shape::Text(t) if t.galley.text().ends_with("View Artboard Contents Only") => Some(t.visual_bounding_rect().center()), + _ => None, + }) + .expect("the menu item"); + let button = + |pressed| egui::Event::PointerButton { pos: item, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + ctx.run_ui(raw(vec![egui::Event::PointerMoved(item), button(true), button(false)]), |ui| menu(app, ui)).textures_delta.clear(); + }; + click(&mut app); + assert!(!app.ui.navigator_panel.view_artboard_contents_only, "a click turns it off"); + named(&tree(|ui| menu(&mut app, ui)), " View Artboard Contents Only"); + click(&mut app); + assert!(app.ui.navigator_panel.view_artboard_contents_only, "a second click turns it on"); + } + + /// With View Artboard Contents Only the thumbnail draws only the art inside the artboards: a + /// shape in the gap between two artboards is left out and one that crosses an artboard's edge + /// is cut there. Without it both draw. + #[test] + fn the_thumbnail_draws_only_the_art_inside_the_artboards_with_the_option() { + use vectorcraft_color::Paint; + use vectorcraft_doc::{Appearance, Document, Node}; + let mut d = Document::new(100.0, 100.0); + let mut second = d.artboards[0].clone(); + second.id = d.artboards.iter().map(|a| a.id).max().unwrap_or(0) + 1; + second.rect = DRect::new(150.0, 0.0, 250.0, 100.0); + d.artboards.push(second); + let l = d.layers[0].id; + for (x0, y0, x1, y1) in [(110.0, 20.0, 140.0, 80.0), (20.0, 80.0, 60.0, 130.0)] { + let mut bp = vectorcraft_geom::BezPath::new(); + bp.move_to((x0, y0)); + bp.line_to((x1, y0)); + bp.line_to((x1, y1)); + bp.line_to((x0, y1)); + bp.close_path(); + let id = d.alloc_id(); + let n = Node::path(id, vectorcraft_geom::PathData::from_bezpath(&bp), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)); + d.insert(Some(l), 0, n).unwrap(); + } + let alpha = |artboard_only: bool, x: u32, y: u32| { + let key = ImageKey { uid: 1, revision: 1, w: 260, h: 140, artboard_only, solid_dashes: false }; + vectorcraft_render::Renderer::new().render_region_with(&d, DRect::new(0.0, 0.0, 260.0, 140.0), 1.0, &image_options(key)).pixel(x, y)[3] + }; + assert_eq!([alpha(true, 125, 50), alpha(true, 40, 90), alpha(true, 40, 120)], [0, 255, 0], "the gap and below the artboard are empty"); + assert_eq!([alpha(false, 125, 50), alpha(false, 40, 90), alpha(false, 40, 120)], [255, 255, 255], "all the art draws"); + } + + /// Turning View Artboard Contents Only off makes the thumbnail again, fitted to the art on the + /// pasteboard as well as the artboards; turning it on fits it to the artboards again. + #[test] + fn the_thumbnail_is_made_again_when_view_artboard_contents_only_changes() { + use vectorcraft_engine::Session; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + app.session.execute("shape.rectangle", &json!({"x": 400, "y": 50, "width": 50, "height": 50})).unwrap(); + let ctx = egui::Context::default(); + let frames = |app: &mut VectorcraftApp| { + for _ in 0..12 { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(app, ui)); + out.textures_delta.clear(); + } + CACHE.with(|c| c.borrow().shown.map(|(k, r)| (k.artboard_only, r.x1))) + }; + let Some((true, right)) = frames(&mut app) else { panic!("an image of the artboards only") }; + assert!(right < 300.0, "fitted to the artboard: {right}"); + app.run("ui.navigatorPanelOptions", json!({"viewArtboardContentsOnly": false})).unwrap(); + let Some((false, right)) = frames(&mut app) else { panic!("an image with the pasteboard's art") }; + assert!(right > 450.0, "fitted to the art on the pasteboard too: {right}"); + app.run("ui.navigatorPanelOptions", json!({"viewArtboardContentsOnly": true})).unwrap(); + assert!(matches!(frames(&mut app), Some((true, r)) if r < 300.0)); + } + #[test] fn zoom_slider_roundtrip() { assert!((zoom_to_slider(3.13)).abs() < 1e-9); diff --git a/crates/ui-egui/src/panels/opentype.rs b/crates/ui-egui/src/panels/opentype.rs index fe144edbf9..4cfcb27e89 100644 --- a/crates/ui-egui/src/panels/opentype.rs +++ b/crates/ui-egui/src/panels/opentype.rs @@ -1,7 +1,7 @@ //! OpenType panel: per-character OpenType features (ligatures, alternates, swashes, small caps, -//! ordinals, fractions, figure style, position, and with the East Asian options the menu's H or V -//! Style and Roman Italics) for the selected text (every frame of each selected threaded story) or -//! the Type tool's selected characters. +//! ordinals, fractions, figure style, position, stylistic sets from the panel or its menu, and with +//! the East Asian options the menu's H or V Style and Roman Italics) for the selected text (every +//! frame of each selected threaded story) or the Type tool's selected characters. use egui::Ui; use serde_json::json; @@ -257,18 +257,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { change = Some(Change::Toggle(flag, shown != Some(true))); } } - // The font, not the text, decides which numbered sets can be offered. Each set is an - // independent feature, so the menu permits several at once. A font's own label wins over - // the numbered fallback. See the public Stylistic Sets help page. A set is checked when every - // character has it. - let sets: Vec<(StylisticSet, Flag, bool)> = offered_sets(&st) - .into_iter() - .map(|set| { - let flag = Flag::Extra(EXTRA_FEATURES[usize::from(set.number - 1)]); - let on = shown_flag(app, flag) == Some(true); - (set, flag, on) - }) - .collect(); + let sets = set_entries(app, &st); ui.add_enabled_ui(!sets.is_empty(), |ui| { ui.menu_button(tl!("Stylistic Sets"), |ui| { widgets::menu_scroll(ui, |ui| { @@ -300,6 +289,22 @@ fn tracking_drops_ligatures(app: &VectorcraftApp) -> bool { }) } +/// The Stylistic Sets entries of the panel's button and of the panel menu's submenu: each set the +/// font `st` names offers, the feature it turns on and off, and whether it is checked. The font, +/// not the text, decides which numbered sets can be offered. Each set is an independent feature, +/// so the menu permits several at once. A font's own label wins over the numbered fallback. See +/// the public Stylistic Sets help page. A set is checked when every character has it. +fn set_entries(app: &VectorcraftApp, st: &CharStyle) -> Vec<(StylisticSet, Flag, bool)> { + offered_sets(st) + .into_iter() + .map(|set| { + let flag = Flag::Extra(EXTRA_FEATURES[usize::from(set.number - 1)]); + let on = shown_flag(app, flag) == Some(true); + (set, flag, on) + }) + .collect() +} + /// The stylistic sets of the font `st` names. A font that is not available offers none, rather than /// the sets of the face drawn in its place. fn offered_sets(st: &vectorcraft_doc::CharStyle) -> Vec { @@ -345,10 +350,31 @@ fn east_asian_items() -> [Toggle; 2] { } pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { - let has = text_style(app).is_some(); + let style = text_style(app); + let has = style.is_some(); if menu_item(ui, tl!("Reset OpenType Features"), has, false) { set(app, OtFeatures::default()); } + // Stylistic Sets: the sets, labels and checks of the panel's Stylistic Sets button. A set chosen + // while only some characters have it turns it on for all of them. Disabled with no text or when + // the font offers no sets. + let sets = style.map(|(st, _)| set_entries(app, &st)).unwrap_or_default(); + let mut toggle = None; + ui.add_enabled_ui(!sets.is_empty(), |ui| { + // Indented like the items beside it (their check column). + ui.menu_button(format!(" {}", tl!("Stylistic Sets")), |ui| { + widgets::menu_scroll(ui, |ui| { + for (set, flag, on) in &sets { + if widgets::menu_item_name(ui, &set_label(set), true, *on) { + toggle = Some(Change::Toggle(*flag, !on)); + } + } + }); + }); + }); + if let Some(c) = toggle { + edit(app, c); + } if app.session.prefs.show_east_asian_options { ui.separator(); // Checked when every character it changes has it; chosen then, it turns it off. @@ -767,6 +793,48 @@ mod tests { assert_eq!(undo_steps(&app), undo + 1); } + /// The panel menu's Stylistic Sets submenu lists the font's sets with the labels of the panel's + /// Stylistic Sets button. Chosen, a set turns on for the selected type in one undo step and + /// shows checked, keeping the other features; chosen again, it turns off. With no text + /// selected the submenu is disabled and does not open. + #[test] + fn the_panel_menu_stylistic_sets_submenu_turns_sets_on_and_off() { + let mut app = selected_text(); + let Some((st, _)) = text_style(&app) else { panic!("no text style") }; + let sets = set_entries(&app, &st); + // Builds without the bundled fonts have no face that offers sets. + let Some((first, _, _)) = sets.first() else { return }; + let (label, tag) = (set_label(first), EXTRA_FEATURES[usize::from(first.number - 1)]); + set(&mut app, OtFeatures { small_caps: true, ..Default::default() }); + let entry = |t: &str| t.trim_start_matches(['✓', ' ']).to_string(); + // Opens the submenu in a fresh context and returns the drawn text of `label`'s entry and + // its rect, if the submenu shows it. + let open = |app: &mut VectorcraftApp, ctx: &egui::Context| { + crate::theme::install_fonts(ctx); + let texts = super::super::tests_appearance::frame_events(ctx, app, vec![], menu); + let sub = super::super::tests_appearance::text_rect(&texts, " Stylistic Sets"); + super::super::tests_appearance::click(ctx, app, sub.center(), menu); + let texts = super::super::tests_appearance::frame_events(ctx, app, vec![], menu); + texts.into_iter().find(|(t, _)| entry(t) == label && t != " Stylistic Sets") + }; + let ctx = egui::Context::default(); + let Some((text, at)) = open(&mut app, &ctx) else { panic!("{label} missing from the submenu") }; + assert!(!text.starts_with('✓'), "{text:?}"); + let undo = undo_steps(&app); + super::super::tests_appearance::click(&ctx, &mut app, at.center(), menu); + assert_eq!(undo_steps(&app), undo + 1); + let on = text_style(&app).unwrap().0.features; + assert!(on.iter().any(|f| f == tag) && on.iter().any(|f| f == "smcp"), "{on:?}"); + let ctx = egui::Context::default(); + let Some((text, at)) = open(&mut app, &ctx) else { panic!("{label} missing from the reopened submenu") }; + assert!(text.starts_with('✓'), "{text:?}"); + super::super::tests_appearance::click(&ctx, &mut app, at.center(), menu); + assert_eq!(text_style(&app).unwrap().0.features, ["smcp"]); + app.session.execute("select.set", &json!({"ids": []})).unwrap(); + let ctx = egui::Context::default(); + assert!(open(&mut app, &ctx).is_none(), "the submenu opened with no text selected"); + } + /// H or V Style and Roman Italics are in the panel menu with the East Asian options only. #[test] fn kana_style_and_roman_italics_show_with_the_east_asian_options() { diff --git a/crates/ui-egui/src/panels/paragraph.rs b/crates/ui-egui/src/panels/paragraph.rs index 52b3135cc2..de5864565a 100644 --- a/crates/ui-egui/src/panels/paragraph.rs +++ b/crates/ui-egui/src/panels/paragraph.rs @@ -94,8 +94,7 @@ fn para_cmd(app: &mut VectorcraftApp, cmd: &str, p: Value) { /// the Selection tool these are the paragraphs of every frame of the selected stories /// ([`super::character::selected_stories`]). pub(crate) fn run_on_paragraphs(app: &mut VectorcraftApp, cmd: &str, mut p: Value) -> Result { - if let Some((id, a, b)) = super::character::text_editing(app) { - super::character::end_typing(app); + if let Some((id, a, b)) = super::character::text_editing_kept(app)? { match super::character::text_story(app) { // After Select All in threaded text: every paragraph of every frame. Some(story) => p["ids"] = json!(story.iter().map(|f| f.0).collect::>()), diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index 5dede1697b..02870c371f 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -1,4 +1,4 @@ -//! The Properties panel: context-sensitive sections like Illustrator's. +//! The Properties panel: sections that change with the selection. use egui::Ui; use serde_json::json; @@ -26,7 +26,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let editing_artboards = app.session.tool_id() == "artboard"; // Ruler guides selected on their own (a click on one): their position. let guides = super::transform::selected_guides(app); - let label = heading(first.as_ref(), n_sel, editing_artboards, guides.is_some()); + let label = heading(first.as_deref(), n_sel, editing_artboards, guides.is_some()); ui.label(egui::RichText::new(label).size(11.5).color(t.text_dim)); ui.add_space(4.0); if editing_artboards { @@ -985,7 +985,7 @@ fn width_profile_row(app: &mut VectorcraftApp, ui: &mut Ui) { } ui.horizontal(|ui| { dim_label(ui, tl!("Profile:")); - if let Some(id) = super::stroke::profile_dropdown(app, ui, profile) { + if let Some(id) = super::stroke::profile_dropdown(app, ui, stroke.as_ref()) { app.run("stroke.set", json!({"profile": id})).ok(); } }); diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index c91d01a2bf..613eb73793 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -1515,6 +1515,26 @@ fn the_width_profile_shows_for_a_variable_width_or_the_width_tool() { assert_eq!(WidthProfile::id_of(profile.as_ref()), "taperStart"); } +/// A brushed stroke with a variable width: the Width Profile list lists only Uniform, which removes +/// the profile. +#[test] +fn the_width_profile_of_a_brushed_stroke_offers_only_uniform() { + let mut app = new_app(); + let line = app.run("shape.line", json!({"x1": 20, "y1": 100, "x2": 300, "y2": 100})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [line]})).unwrap(); + app.run("stroke.set", json!({"profile": "lens"})).unwrap(); + app.run("brush.apply", json!({"ids": [line], "name": "3 pt. Round"})).unwrap(); + let ctx = egui::Context::default(); + let texts = tall(&mut app, &ctx, vec![]); + let spacing = ctx.global_style().spacing.item_spacing.x; + let texts = press(&mut app, &ctx, text_at(&texts, "Profile:").right_center() + vec2(spacing + 50.0, 0.0)); + assert!(!shows(&texts, "Taper Start"), "{texts:?}"); + press(&mut app, &ctx, text_at(&texts, "Uniform").center()); + let profile = + app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(line.as_u64().unwrap())).unwrap().appearance.stroke().unwrap().profile.clone(); + assert_eq!(profile, None); +} + /// With Direct Selection, a path whose corner is selected shows that corner's kind and radius; /// each edit sets that corner alone in one undo step. Not with the Selection tool, nor with the /// whole path selected; a live rectangle keeps its own Corner Radius row instead. diff --git a/crates/ui-egui/src/panels/separations.rs b/crates/ui-egui/src/panels/separations.rs index bdb4210920..2b3e112c5f 100644 --- a/crates/ui-egui/src/panels/separations.rs +++ b/crates/ui-egui/src/panels/separations.rs @@ -1,5 +1,6 @@ //! Separations Preview panel: process plates C/M/Y/K plus spot plates with eye toggles (one visible -//! plate renders as greyscale ink coverage; Alt-click an eye to show only that plate), and the +//! plate renders as grayscale ink coverage; Alt-click an eye to show only that plate, and Alt-click +//! the eye of the plate shown alone to show every plate), and the //! colour-management controls behind Edit → Color Settings… / Assign Profile… and View → Proof //! Setup (working spaces, color management policies, intent, black-point compensation, proof //! target, gamut check). @@ -59,11 +60,11 @@ fn plates_section(app: &mut VectorcraftApp, ui: &mut Ui) { let vis = visible(&p.name); let mut clicked = false; ui.add_enabled_ui(on, |ui| { - clicked = widgets::toggle_icon(ui, "eye", vis, 18.0, tl!("Show/hide plate (Alt-click: only this plate)")); + clicked = + widgets::toggle_icon(ui, "eye", vis, 18.0, tl!("Show/hide plate (Alt-click: only this plate; Alt-click again: all plates)")); }); if clicked && on { - let key = if alt { "only" } else { "toggle" }; - run(app, "view.separationsPreview", json!({ key: p.name })); + run(app, "view.separationsPreview", eye_click(&p.name, alt)); } let (r, _) = ui.allocate_exact_size(vec2(14.0, 14.0), Sense::hover()); let q = |x: f32| (x.clamp(0.0, 1.0) * 255.0).round() as u8; @@ -75,6 +76,12 @@ fn plates_section(app: &mut VectorcraftApp, ui: &mut Ui) { }); } +/// The `view.separationsPreview` params for a click on plate `name`'s eye: with Alt, that plate +/// alone, or every plate when it already shows alone; without, the plate shown or hidden. +fn eye_click(name: &str, alt: bool) -> Value { + if alt { json!({"soloToggle": name}) } else { json!({"toggle": name}) } +} + /// A dropdown of the `kind` profiles after `extra` (a built-in entry, shown in the UI language); /// profile names are shown as they are. Returns the chosen name. pub(crate) fn profile_dropdown(ui: &mut Ui, id: &str, current: &str, kind: ProfileKind, extra: Option<&str>) -> Option { @@ -345,6 +352,16 @@ mod tests { assert!(panel.iter().all(|(id, _)| cms::ProofTarget::parse(id).is_some_and(|t| t.id() == *id))); } + /// An Alt-click on a plate's eye sends `soloToggle`, which `view.separationsPreview` takes, and + /// a plain click sends `toggle`. + #[test] + fn an_alt_click_on_a_plates_eye_sends_solo_toggle() { + assert_eq!(eye_click("Cyan", true), json!({"soloToggle": "Cyan"})); + assert_eq!(eye_click("Brand Orange", false), json!({"toggle": "Brand Orange"})); + let spec = vectorcraft_engine::cmd::command_specs().iter().find(|c| c.id == "view.separationsPreview"); + assert!(spec.is_some_and(|c| c.params.contains("soloToggle?:"))); + } + /// Assign Profile's three choices: no profile, the working space assigned as the profile, or /// another profile; a choice the document already has runs nothing. #[test] diff --git a/crates/ui-egui/src/panels/stroke.rs b/crates/ui-egui/src/panels/stroke.rs index c667f01200..33faeec41e 100644 --- a/crates/ui-egui/src/panels/stroke.rs +++ b/crates/ui-egui/src/panels/stroke.rs @@ -76,7 +76,7 @@ fn dash_state(dash: Option<&Dash>, last: Option<(Vec, bool)>) -> (Vec, } /// Six dash/gap fields → a dash pattern: stops at the first empty dash; a dash without a gap -/// repeats its length as the gap (Illustrator's behaviour). +/// repeats its length as the gap. pub fn dash_pattern(fields: &[Option; 6]) -> Vec { edited_dash_pattern(fields, &[]) } @@ -355,10 +355,10 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // Profile. ui.horizontal(|ui| { row_label(ui, tl!("Profile:")); - if let Some(id) = profile_dropdown(app, ui, st.as_ref().and_then(|s| s.profile.as_ref())) { + if let Some(id) = profile_dropdown(app, ui, st.as_ref()) { set(app, json!({"profile": id})); } - let can_flip = st.as_ref().is_some_and(|s| s.profile.is_some()); + let can_flip = st.as_ref().is_some_and(|s| s.profile.is_some()) && brush_keeps_size(app, ui.ctx(), st.as_ref()).is_none(); // Lucide names these icons for their mirror line: the vertical-line icon flips the // profile along the path, while the horizontal-line icon flips it across the path. if widgets::icon_button_enabled(ui, "flip-vertical-2", tl!("Flip Along"), false, can_flip, 22.0).clicked() { @@ -416,7 +416,7 @@ pub(super) fn arrow_doc(mut a: Option, start: bool, w: f64, h: f64) - /// Draw an arrowhead preview (the head as the canvas draws it) in `r`: a line with the head at the /// left (`start`) or right end. -fn paint_arrow(ui: &Ui, r: Rect, a: Option<&Arrowhead>, start: bool, color: Color32) { +pub(crate) fn paint_arrow(ui: &Ui, r: Rect, a: Option<&Arrowhead>, start: bool, color: Color32) { if let Some(tex) = widgets::doc_preview(ui, &format!("arrow:{}:{start}", arrow_key(a)), r.size(), |w, h| arrow_doc(a.cloned(), start, w, h)) { ui.painter().image(tex.id(), r, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), color); } @@ -498,24 +498,66 @@ pub fn paint_profile(ui: &Ui, r: Rect, points: Option<&[(f64, f64, f64)]>, color /// The width of the [`profile_dropdown`] button. pub(crate) const PROFILE_DROPDOWN_WIDTH: f32 = 100.0; -/// The Profile dropdown (Stroke panel, Control bar): the stroke's own silhouette on the button -/// (a custom profile too), the built-in profiles and then the saved ones in the list. Returns the -/// id or name picked. -pub(crate) fn profile_dropdown(app: &VectorcraftApp, ui: &mut Ui, cur: Option<&WidthProfile>) -> Option { +/// While a width profile changes none of the strokes the Profile list edits, because each draws +/// with a brush: whether any of them has a profile. None while a profile changes one of them. +/// With nothing selected the list sets up the next object drawn, whose stroke is `shown` (the +/// stroke the panels show). Otherwise it edits the strokes `stroke.set` targets +/// ([`vectorcraft_engine::Session::brushed_strokes_profiled`], cached per document revision and +/// active Appearance row), such as a selected group's own stroke while `shown` is its first +/// member's. +pub(crate) fn brush_keeps_size(app: &VectorcraftApp, ctx: &egui::Context, shown: Option<&StrokeLayer>) -> Option { + let st = app.session.active()?; + if st.selection.objects.is_empty() && st.selection.subjects().is_empty() { + let s = shown?; + let name = s.brush.as_deref()?; + return super::brushes::document_brushes(st).iter().any(|b| b.name == name).then_some(s.profile.is_some()); + } + let key = (st.uid, st.revision, app.session.appearance_item()); + match pstate::), Option)>>(ctx, "stroke-brushed") { + Some((k, v)) if k == key => v, + _ => { + let v = app.session.brushed_strokes_profiled(); + set_pstate(ctx, "stroke-brushed", Some((key, v))); + v + } + } +} + +/// The Profile dropdown (Stroke panel, Properties panel, Control bar): the stroke's own silhouette +/// on the button (a custom profile too), the built-in profiles and then the saved ones in the list. +/// Returns the id or name picked. While the strokes draw with a brush ([`brush_keeps_size`]), the +/// button is dimmed and says why when hovered; it opens no list while every one is uniform, and +/// only the Uniform row, which removes the profiles, while one has a profile. +pub(crate) fn profile_dropdown(app: &VectorcraftApp, ui: &mut Ui, shown: Option<&StrokeLayer>) -> Option { let t = Tokens::get(ui.ctx()); - let (r, resp) = ui.allocate_exact_size(vec2(PROFILE_DROPDOWN_WIDTH, 24.0), Sense::click()); + let cur = shown.and_then(|s| s.profile.as_ref()); + let brushed = brush_keeps_size(app, ui.ctx(), shown); + let keeps_size = brushed.is_some(); + let uniform = brushed == Some(false); + let sense = if uniform { Sense::hover() } else { Sense::click() }; + let (r, resp) = ui.allocate_exact_size(vec2(PROFILE_DROPDOWN_WIDTH, 24.0), sense); ui.painter().rect_filled(r, 2, t.input); - ui.painter().rect_stroke(r, 2, Stroke::new(1.0, if resp.hovered() { t.text } else { t.input_border }), StrokeKind::Inside); + let border = if resp.hovered() && !uniform { t.text } else { t.input_border }; + ui.painter().rect_stroke(r, 2, Stroke::new(1.0, border), StrokeKind::Inside); let body = Rect::from_min_max(r.min + vec2(6.0, 5.0), pos2(r.right() - 20.0, r.bottom() - 5.0)); - paint_profile(ui, body, cur.and_then(|p| silhouette(&p.points)), t.text_strong); - icons::paint(ui, "chevron-down", Rect::from_center_size(pos2(r.right() - 9.0, r.center().y), vec2(10.0, 10.0)), t.icon); - let resp = resp.on_hover_text(tl!("Variable Width Profile")); + let (shape, icon) = if keeps_size { (t.text_disabled, t.text_disabled) } else { (t.text_strong, t.icon) }; + paint_profile(ui, body, cur.and_then(|p| silhouette(&p.points)), shape); + icons::paint(ui, "chevron-down", Rect::from_center_size(pos2(r.right() - 9.0, r.center().y), vec2(10.0, 10.0)), icon); + let tip = if keeps_size { + tl!("The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile.") + } else { + tl!("Variable Width Profile") + }; + let resp = resp.on_hover_text(tip); + if uniform { + return None; + } let mut out = None; egui::Popup::menu(&resp).show(|ui| { egui::ScrollArea::vertical().max_height(360.0).show(ui, |ui| { // A divider between the built-in profiles and the saved ones. let mut divide = true; - for e in app.session.profile_entries() { + for e in app.session.profile_entries().filter(|e| !keeps_size || e.matches(None)) { if !e.built_in && std::mem::take(&mut divide) { ui.separator(); } diff --git a/crates/ui-egui/src/panels/swatches.rs b/crates/ui-egui/src/panels/swatches.rs index 7b70844dcc..da789a9944 100644 --- a/crates/ui-egui/src/panels/swatches.rs +++ b/crates/ui-egui/src/panels/swatches.rs @@ -14,7 +14,7 @@ use vectorcraft_color::libraries::{BuiltinLibrary, GRADIENT_LIBRARIES, SWATCH_LI use vectorcraft_color::swatch::REGISTRATION; use vectorcraft_color::{Color, GradientKind, Paint, Swatch, SwatchLibrary}; use vectorcraft_doc::Document; -use vectorcraft_engine::cmd::patternlib::{self, PATTERN_LIBRARIES}; +use vectorcraft_engine::cmd::patternlib::PATTERN_LIBRARIES; use vectorcraft_engine::cmd::swatchlib; use super::library_panel::{self, LibraryKind, LibraryRef, Row}; diff --git a/crates/ui-egui/src/panels/swatches/actions.rs b/crates/ui-egui/src/panels/swatches/actions.rs index 1779f9dfa6..8850b2ed6c 100644 --- a/crates/ui-egui/src/panels/swatches/actions.rs +++ b/crates/ui-egui/src/panels/swatches/actions.rs @@ -5,16 +5,19 @@ use super::{ widgets, }; -/// The selected swatches and groups that can be deleted (all but None and Registration). -pub(super) fn deletable(sel: &[String]) -> Vec { - sel.iter().filter(|n| !n.starts_with('[')).cloned().collect() +/// The selected swatches and groups that can be deleted: every color group in the document and +/// every swatch that `Swatch::is_reserved` does not reserve (None and Registration). Names the +/// document does not hold are left out. +pub(super) fn deletable(app: &VectorcraftApp, sel: &[String]) -> Vec { + let Some(d) = app.session.active().map(|st| &st.doc) else { return vec![] }; + sel.iter().filter(|n| d.swatch(n).map_or_else(|| d.swatch_groups.iter().any(|g| g.name == **n), |w| !w.is_reserved())).cloned().collect() } /// The selected swatch when exactly one swatch with an editor is selected (not None, Registration /// or a group). -fn editable(app: &VectorcraftApp, sel: &[String]) -> Option { +pub(super) fn editable(app: &VectorcraftApp, sel: &[String]) -> Option { match sel { - [n] if !n.starts_with('[') && app.session.active().is_some_and(|st| st.doc.swatch(n).is_some()) => Some(n.clone()), + [n] if app.session.active().and_then(|st| st.doc.swatch(n)).is_some_and(|w| !w.is_reserved()) => Some(n.clone()), _ => None, } } @@ -80,7 +83,7 @@ pub(super) fn bottom(app: &mut VectorcraftApp, ui: &mut Ui, sel: &[String]) { } ui.add_space((ui.available_width() - 3.0 * 28.0).max(0.0)); if widgets::icon_button(ui, "dc-folder", tl!("New Color Group"), false, 24.0).clicked() { - app.run("ui.newColorGroup", json!({"swatches": deletable(sel)})).ok(); + app.run("ui.newColorGroup", json!({"swatches": deletable(app, sel)})).ok(); } // Alt-click skips the dialog; Ctrl/Cmd-click makes a spot color, and Ctrl/Cmd+Shift-click // makes a global process color. @@ -89,7 +92,7 @@ pub(super) fn bottom(app: &mut VectorcraftApp, ui: &mut Ui, sel: &[String]) { } // Alt-click deletes without asking. Swatches or color groups dragged from the list can be // dropped on it, also with nothing selected: the button is enabled while they are held. - let del = deletable(sel); + let del = deletable(app, sel); let dragged = dragged_deletable(app, ui.ctx()); let trash = widgets::icon_button_enabled(ui, "trash-2", tl!("Delete Swatch"), false, !del.is_empty() || !dragged.is_empty(), 24.0); if trash.clicked() && !del.is_empty() { @@ -111,7 +114,7 @@ fn dragged_deletable(app: &VectorcraftApp, ctx: &egui::Context) -> Vec { return vec![]; } match egui::DragAndDrop::payload::(ctx).as_deref() { - Some(PanelDrag::Paint { rows: Some(r), .. }) => deletable(&r.names).into_iter().filter(|n| st.doc.swatch_name_taken(n)).collect(), + Some(PanelDrag::Paint { rows: Some(r), .. }) => deletable(app, &r.names).into_iter().filter(|n| st.doc.swatch_name_taken(n)).collect(), _ => vec![], } } @@ -164,7 +167,7 @@ pub(super) fn new_swatch(app: &mut VectorcraftApp, sel: &[String], m: egui::Modi pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { let view = app.ui.swatches_view; let selected = selection(app, ui); - let del = deletable(&selected); + let del = deletable(app, &selected); let opts = editable(app, &selected); if menu_item(ui, tl!("New Swatch…"), true, false) { new_swatch(app, &selected, egui::Modifiers::NONE); @@ -239,6 +242,6 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { ui.separator(); ui.menu_button(tl!("Open Swatch Library"), |ui| library_panel::library_menu::(app, ui)); if menu_item(ui, tl!("Save Swatch Library…"), true, false) { - app.run("ui.saveSwatchLibrary", json!({ "names": deletable(&selected) })).ok(); + app.run("ui.saveSwatchLibrary", json!({ "names": deletable(app, &selected) })).ok(); } } diff --git a/crates/ui-egui/src/panels/swatches/dnd.rs b/crates/ui-egui/src/panels/swatches/dnd.rs index ea3282db68..d8cd2534ab 100644 --- a/crates/ui-egui/src/panels/swatches/dnd.rs +++ b/crates/ui-egui/src/panels/swatches/dnd.rs @@ -308,7 +308,8 @@ pub(crate) fn drag_preview(app: &VectorcraftApp, ctx: &egui::Context) { None => return, }, PanelDrag::GraphicStyle(name) => return pointer_chip(ctx, |ui, r| crate::panels::graphic_styles::paint_style(app, ui, r, name)), - PanelDrag::Symbol(name) => match app.session.active() { + // Drawn from the document it was dragged from, whichever document is active now. + PanelDrag::Symbol { document, name } => match app.session.documents().iter().find(|st| st.uid == *document) { Some(st) => { return pointer_chip(ctx, |ui, r| crate::panels::symbols::chip(ui, &st.doc, &crate::panels::symbols::document_symbols(st), r, name)); } diff --git a/crates/ui-egui/src/panels/swatches/libraries.rs b/crates/ui-egui/src/panels/swatches/libraries.rs index 864f6ae7e0..183231971c 100644 --- a/crates/ui-egui/src/panels/swatches/libraries.rs +++ b/crates/ui-egui/src/panels/swatches/libraries.rs @@ -3,7 +3,7 @@ use super::dnd::selection; use super::tiles::{describe, global_mark, list_icons, pattern_thumb_in}; use super::{ Arc, BuiltinLibrary, GRADIENT_LIBRARIES, Item, LibraryKind, LibraryRef, PATTERN_LIBRARIES, Rect, Row, SWATCH_LIBRARIES, Swatch, SwatchLibrary, - Ui, Value, VectorcraftApp, json, library_panel, menu_item, patternlib, swatch_tile, swatchlib, + Ui, Value, VectorcraftApp, json, library_panel, menu_item, swatch_tile, swatchlib, }; fn library_refs(libs: Vec) -> Vec { @@ -97,10 +97,10 @@ impl LibraryKind for SwatchLibraries { } out } - fn draw(_: &VectorcraftApp, ui: &Ui, r: Rect, w: &Swatch, selected: bool, hovered: bool) { + fn draw(app: &VectorcraftApp, ui: &Ui, r: Rect, w: &Swatch, selected: bool, hovered: bool) { swatch_tile(ui, r, &w.paint, selected, hovered); - // A built-in pattern library's pattern, drawn from the library. - if let Some(src) = patternlib::swatch_source(w) { + // A pattern library's pattern, or a loaded library's, drawn from the library. + if let Some(src) = swatchlib::pattern_source(&app.session, w) { pattern_thumb_in(&src, ui, r.shrink(1.0), &w.paint); } if w.global { @@ -142,7 +142,7 @@ impl LibraryKind for SwatchLibraries { app.status(e); } if menu_item(ui, tl!("Save Swatch Library…"), app.session.active().is_some(), false) { - let names = deletable(&selection(app, ui)); + let names = deletable(app, &selection(app, ui)); app.run("ui.saveSwatchLibrary", json!({ "names": names })).ok(); } } diff --git a/crates/ui-egui/src/panels/swatches/tests.rs b/crates/ui-egui/src/panels/swatches/tests.rs index a67e604f2b..20c57ac769 100644 --- a/crates/ui-egui/src/panels/swatches/tests.rs +++ b/crates/ui-egui/src/panels/swatches/tests.rs @@ -281,7 +281,27 @@ fn delete_asks_then_removes_the_selection_and_unlinks_art() { assert!(app.session.doc().unwrap().doc.swatch("Orange").is_some()); delete(&mut app, vec!["Orange".into()], true); assert!(app.ui.dialog.is_none() && app.session.doc().unwrap().doc.swatch("Orange").is_none()); - assert_eq!(deletable(&["[None]".into(), REGISTRATION.into(), "Grays".into()]), ["Grays"]); + assert_eq!(deletable(&app, &["[None]".into(), REGISTRATION.into(), "Grays".into()]), ["Grays"]); +} + +/// Only None and Registration are reserved: a user swatch or color group whose name starts with +/// `[` can be deleted, the swatch can be edited, and names the document does not hold are left out. +#[test] +fn bracketed_user_swatches_and_groups_can_be_deleted_and_edited() { + let mut app = app(); + app.run("swatch.new", json!({"name": "[Mine]", "color": "#336699"})).unwrap(); + app.run("swatch.newGroup", json!({"name": "[Team]", "colors": ["#ff0000"]})).unwrap(); + let names = |v: &[&str]| v.iter().map(|n| n.to_string()).collect::>(); + assert_eq!(deletable(&app, &names(&["[None]", REGISTRATION, "[Mine]", "[Team]", "Gone"])), ["[Mine]", "[Team]"]); + assert_eq!(actions::editable(&app, &names(&["[Mine]"])).as_deref(), Some("[Mine]")); + for name in ["[None]", REGISTRATION, "[Team]", "Gone"] { + assert_eq!(actions::editable(&app, &names(&[name])), None, "{name}"); + } + let doomed = deletable(&app, &names(&["[Mine]"])); + delete(&mut app, doomed, false); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.str("message")).as_deref(), Some("Delete “[Mine]”?")); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.session.doc().unwrap().doc.swatch("[Mine]").is_none()); } /// The prompt for several swatches and groups gives the form the language's plural rule picks for the count. diff --git a/crates/ui-egui/src/panels/symbols.rs b/crates/ui-egui/src/panels/symbols.rs index 0be9e7111c..b50b7876cc 100644 --- a/crates/ui-egui/src/panels/symbols.rs +++ b/crates/ui-egui/src/panels/symbols.rs @@ -19,6 +19,7 @@ use super::library_panel::{self, LibraryKind, LibraryRef, Row}; use super::memo::Memo; use super::{pstate, set_pstate}; use crate::VectorcraftApp; +use crate::caches::SymbolInstances; use crate::menus::Item; use crate::theme::Tokens; use crate::widgets::{self, PanelDrag, menu_item}; @@ -139,21 +140,37 @@ fn current(app: &VectorcraftApp) -> Option { app.session.active().and_then(|st| vectorcraft_engine::cmd::current_symbol(&st.doc)) } -/// Does the selection hold (in it or in its groups) a symbol instance that `wanted` takes? -fn instance_selected(app: &VectorcraftApp, wanted: impl Fn(&Node) -> bool) -> bool { - app.session.active().is_some_and(|st| { - st.selection.objects.iter().any(|id| { - let mut any = false; - if let Some(n) = st.doc.node(*id) { - n.walk(&mut |c| any |= matches!(c.kind, NodeKind::SymbolInstance { .. }) && wanted(c)); - } - any - }) - }) +#[cfg(test)] +thread_local! { + /// How many times [`selected_instances`] walked the selection on this thread. + static INSTANCE_SCANS: std::cell::Cell = const { std::cell::Cell::new(0) }; } -fn has_instances_selected(app: &VectorcraftApp) -> bool { - instance_selected(app, |_| true) +/// The symbol instances in the selection and in its groups, found in one walk of the selected +/// subtrees per (document uid, revision) ([`crate::caches::CanvasCache::symbol_instances`]); +/// `None` without a document. +fn selected_instances(app: &mut VectorcraftApp) -> Option<&mut SymbolInstances> { + let st = app.session.active()?; + let key = (st.uid, st.revision); + if app.canvas.symbol_instances.as_ref().is_none_or(|(k, _)| *k != key) { + #[cfg(test)] + INSTANCE_SCANS.with(|n| n.set(n.get() + 1)); + let mut found = SymbolInstances::default(); + for n in st.selection.objects.iter().filter_map(|id| st.doc.node(*id)) { + n.walk(&mut |c| { + if matches!(c.kind, NodeKind::SymbolInstance { .. }) { + found.changed |= !c.extras().symbol_overrides.is_empty(); + found.ids.push(c.id); + } + }); + } + app.canvas.symbol_instances = Some((key, found)); + } + app.canvas.symbol_instances.as_mut().map(|(_, found)| found) +} + +fn has_instances_selected(app: &mut VectorcraftApp) -> bool { + selected_instances(app).is_some_and(|found| !found.ids.is_empty()) } /// Collect the IDs of selected instances of symbol `name` (including inside groups). @@ -221,15 +238,19 @@ fn item_context_menu(app: &mut VectorcraftApp, ui: &mut Ui, name: &str) { /// Does the selection hold a symbol instance with appearance changes of its own (a dynamic /// symbol's), which Reset drops? -pub(crate) fn changed_instances_selected(app: &VectorcraftApp) -> bool { - instance_selected(app, |c| !c.extras().symbol_overrides.is_empty()) +pub(crate) fn changed_instances_selected(app: &mut VectorcraftApp) -> bool { + selected_instances(app).is_some_and(|found| found.changed) } /// Does the selection hold a symbol instance whose scale, rotation or shear differs from its /// symbol's, which Reset Transformation restores? -fn transformed_instances_selected(app: &VectorcraftApp) -> bool { +fn transformed_instances_selected(app: &mut VectorcraftApp) -> bool { let Some(doc) = app.session.active().map(|st| st.doc.clone()) else { return false }; - instance_selected(app, |c| vectorcraft_engine::cmd::reset_transformation_changes(&doc, c)) + let Some(found) = selected_instances(app) else { return false }; + let ids = &found.ids; + *found + .transformed + .get_or_insert_with(|| ids.iter().filter_map(|id| doc.node(*id)).any(|n| vectorcraft_engine::cmd::reset_transformation_changes(&doc, n))) } /// The symbols of the selected objects when every one is a symbol instance; `None` otherwise. @@ -296,7 +317,7 @@ pub(crate) fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui, reserve: f32) { pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let t = Tokens::get(ui.ctx()); - let Some((doc, keys)) = app.session.active().map(|d| (d.doc.clone(), document_symbols(d))) else { return }; + let Some((doc, keys, document)) = app.session.active().map(|d| (d.doc.clone(), document_symbols(d), d.uid)) else { return }; let names: Vec = doc.symbols.iter().map(|s| s.name.clone()).collect(); let view = app.ui.symbols_view; let sel = current(app); @@ -305,6 +326,10 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // The symbols drawn selected: the ones Select All Unused picked, else the current one. let on = |n: &str| if marked.is_empty() { sel.as_deref() == Some(n) } else { marked.iter().any(|m| m == n) }; let mut clicked: Option<(String, bool)> = None; + // Art released on a symbol with Alt (Option) held redefines that symbol; while Alt art is over + // a symbol, the list does not take it as a new symbol. + let mut redefine: Option<(String, Vec)> = None; + let mut over_symbol = false; let list_rect = widgets::list_box(ui, |ui| { ui.set_min_height(110.0); ui.set_width(ui.available_width()); @@ -316,7 +341,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { for n in &names { let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), h), Sense::click_and_drag()); // Dragged onto the canvas, the symbol is placed there. - drag_symbol(ui, &resp, n, uid); + widgets::drag_source(ui, &resp, || PanelDrag::Symbol { document, name: n.clone() }); if on(n) { ui.painter().rect_filled(r, 0.0, t.row_selected); } else if resp.hovered() { @@ -324,6 +349,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } chip(ui, &doc, &keys, egui::Rect::from_center_size(r.left_center() + vec2(3.0 + side / 2.0, 0.0), vec2(side, side)), n); ui.painter().text(r.left_center() + vec2(side + 10.0, 0.0), egui::Align2::LEFT_CENTER, n, egui::FontId::proportional(text), t.text); + if let Some(ids) = art_redefine_drop(ui, &resp, &doc, uid, &mut over_symbol) { + redefine = Some((n.clone(), ids)); + } let resp = resp.on_hover_text(n); if resp.double_clicked() { clicked = Some((n.clone(), true)); @@ -342,7 +370,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { ui.horizontal_wrapped(|ui| { for n in &names { let (r, resp) = ui.allocate_exact_size(vec2(44.0, 44.0), Sense::click_and_drag()); - drag_symbol(ui, &resp, n, uid); + widgets::drag_source(ui, &resp, || PanelDrag::Symbol { document, name: n.clone() }); chip(ui, &doc, &keys, r.shrink(2.0), n); let on = on(n); ui.painter().rect_stroke( @@ -351,6 +379,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { Stroke::new(if on { 2.0 } else { 1.0 }, if on { t.accent } else { t.border }), StrokeKind::Inside, ); + if let Some(ids) = art_redefine_drop(ui, &resp, &doc, uid, &mut over_symbol) { + redefine = Some((n.clone(), ids)); + } let resp = resp.on_hover_text(n); if resp.double_clicked() { clicked = Some((n.clone(), true)); @@ -370,8 +401,19 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { ui.min_rect() }); let zone = ui.interact(list_rect, ui.scope_id().with("symbols-drop"), Sense::hover()); - if let Some(ids) = widgets::art_drop(ui, &zone) - && let Err(e) = app.run("symbol.new", json!({ "ids": ids, "type": "dynamic" })) + if !over_symbol && let Some(ids) = widgets::art_drop(ui, &zone) { + // Shift held at the release keeps the dropped art as ordinary art. + let mut p = json!({ "ids": ids, "type": "dynamic" }); + if modifiers_at_release(ui).shift { + p["keepArt"] = json!(true); + } + if let Err(e) = app.run("symbol.new", p) { + app.status(e); + } + } + // Redefine Symbol with the dropped art, which becomes an instance of it, in one undo step. + if let Some((name, ids)) = redefine + && let Err(e) = app.run("symbol.update", json!({ "name": name, "ids": ids })) { app.status(e); } @@ -399,6 +441,11 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if widgets::icon_button_enabled(ui, "link-2-off", tl!("Break Link to Symbol"), false, inst, 24.0).clicked() { app.run("symbol.breakLink", json!({})).ok(); } + // Opens Symbol Options on the current symbol, as the panel menu's Symbol Options… does; + // Alt does the same. + if widgets::icon_button_enabled(ui, "dc-options", tl!("Symbol Options"), false, sel.is_some(), 24.0).clicked() { + app.run("ui.symbolOptions", json!({"edit": true, "name": sel})).ok(); + } ui.add_space((ui.available_width() - 2.0 * 28.0).max(0.0)); let new = widgets::icon_button_enabled(ui, "dc-new-item", tl!("New Symbol"), false, has_sel, 24.0); // A symbol dragged from the panel and dropped on New Symbol is duplicated, with or without @@ -409,8 +456,12 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } } else if new.clicked() { // Alt skips Symbol Options: the symbol is made under the default name, dynamic as the - // dialog's default. - let (cmd, p) = if ui.input(|i| i.modifiers.alt) { ("symbol.new", json!({"type": "dynamic"})) } else { ("ui.symbolOptions", json!({})) }; + // dialog's default. Shift keeps the selected art as ordinary art, with or without Alt. + let m = ui.input(|i| i.modifiers); + let (cmd, mut p) = if m.alt { ("symbol.new", json!({"type": "dynamic"})) } else { ("ui.symbolOptions", json!({})) }; + if m.shift { + p["keepArt"] = json!(true); + } app.run(cmd, p).ok(); } // Alt deletes an unused symbol without asking; a symbol with instances still asks. @@ -434,9 +485,13 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { let has_sel = app.session.active().is_some_and(|d| !d.selection.is_empty()); let inst = has_instances_selected(app); let name = json!({"name": sel}); + // Shift keeps the selected art as ordinary art instead of making it an instance. + let shift = ui.input(|i| i.modifiers.shift); + let redefine = if shift { json!({"name": sel, "keepArt": true}) } else { name.clone() }; + let new = if shift { json!({"keepArt": true}) } else { json!({}) }; let items: [(&str, bool, &str, Value); 3] = [ - (tl!("New Symbol…"), has_sel, "ui.symbolOptions", json!({})), - (tl!("Redefine Symbol"), has_sel && sel.is_some(), "symbol.update", name.clone()), + (tl!("New Symbol…"), has_sel, "ui.symbolOptions", new), + (tl!("Redefine Symbol"), has_sel && sel.is_some(), "symbol.update", redefine), (tl!("Duplicate Symbol"), sel.is_some(), "symbol.duplicate", name.clone()), ]; for (label, enabled, cmd, params) in items { @@ -499,26 +554,14 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { } } -/// The panel state key of the document (`uid`) the symbol being dragged from the panel belongs to. -const DRAG_DOC: &str = "sym-drag-doc"; - -/// Make `resp` a drag source of the symbol `name` of the document `uid`, and keep `uid` while it -/// is dragged. -fn drag_symbol(ui: &Ui, resp: &egui::Response, name: &str, uid: Option) { - if resp.drag_started_by(egui::PointerButton::Primary) { - set_pstate(ui.ctx(), DRAG_DOC, uid); - } - widgets::drag_source(ui, resp, || PanelDrag::Symbol(name.to_string())); -} - /// The symbol of the active document (`uid`, whose symbols are `names`) dragged from the panel and /// released on `button` this frame, if any; `button` is outlined while one is held over it, also /// when it is disabled for clicks. A symbol dragged from another document is ignored. Only the /// release of the primary button drops the symbol; the release of another button ends the drag. fn symbol_dropped(ui: &Ui, button: &egui::Response, names: &[String], uid: Option) -> Option { let held = button.dnd_hover_payload::()?; - let PanelDrag::Symbol(name) = &*held else { return None }; - if !names.contains(name) || pstate::>(ui.ctx(), DRAG_DOC) != uid { + let PanelDrag::Symbol { document, name } = &*held else { return None }; + if !names.contains(name) || Some(*document) != uid { return None; } widgets::drop_target_outline(ui, button.rect); @@ -528,6 +571,49 @@ fn symbol_dropped(ui: &Ui, button: &egui::Response, names: &[String], uid: Optio button.dnd_release_payload::().map(|_| name.clone()) } +/// The ids of the art dragged off the canvas of the active document `doc` (`uid`) and released +/// with Alt (Option) held on the symbol tile or row `item` this frame, if any. While such art is +/// held over `item` with Alt, `over` is set and `item` is outlined. Art of another document, or +/// whose objects `doc` no longer has, is not taken. Only the release of the primary button drops +/// the art; the release of another button ends the drag. +fn art_redefine_drop(ui: &Ui, item: &egui::Response, doc: &Document, uid: Option, over: &mut bool) -> Option> { + if !alt_at_release(ui) { + return None; + } + let held = item.dnd_hover_payload::()?; + let PanelDrag::Art(ids) = &*held else { return None }; + *over = true; + let ours = uid.is_some() && widgets::art_drag_doc(ui.ctx()) == uid; + if !ours || ids.is_empty() || !ids.iter().all(|id| doc.node(*id).is_some_and(|n| !n.is_layer())) { + return None; + } + widgets::drop_target_outline(ui, item.rect); + if !ui.input(|i| i.pointer.button_released(egui::PointerButton::Primary)) { + return None; + } + item.dnd_release_payload::().map(|_| ids.iter().map(|id| id.0).collect()) +} + +/// Whether Alt (Option) is held for a drop: when the primary button went up in this frame, as it +/// went up, else now. +fn alt_at_release(ui: &Ui) -> bool { + modifiers_at_release(ui).alt +} + +/// The modifiers held for a drop: when the primary button went up in this frame, as it went up, +/// else now. +fn modifiers_at_release(ui: &Ui) -> egui::Modifiers { + ui.input(|i| { + i.events + .iter() + .find_map(|e| match e { + egui::Event::PointerButton { button: egui::PointerButton::Primary, pressed: false, modifiers, .. } => Some(*modifiers), + _ => None, + }) + .unwrap_or(i.modifiers) + }) +} + /// The panel state key of the symbols Select All Unused picked. const MARKED: &str = "sym-unused"; @@ -760,6 +846,11 @@ mod tests { egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() } } + /// The primary button going up at `at` with Alt (Option) held. + fn alt_release(at: Pos2) -> egui::Event { + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::ALT } + } + fn symbols(app: &mut VectorcraftApp) -> Vec { let list = app.run("symbol.list", json!({})).unwrap(); list["symbols"].as_array().unwrap().iter().map(|s| s["name"].as_str().unwrap_or_default().to_string()).collect() @@ -813,13 +904,14 @@ mod tests { let doc = &app.session.active().unwrap().doc; let first = doc.layers[0].children().unwrap().first().unwrap(); assert!(matches!(first.kind, NodeKind::SymbolInstance { .. }), "the art became an instance"); - // Dragging the symbol's tile out of the panel carries the symbol. + // Dragging the symbol's tile out of the panel carries the symbol and its document. frame(&ctx, &mut app, vec![]); let tile = pos2(26.0, 26.0); frame(&ctx, &mut app, vec![egui::Event::PointerMoved(tile), button(tile, true)]); frame(&ctx, &mut app, vec![egui::Event::PointerMoved(tile + vec2(40.0, 40.0))]); frame(&ctx, &mut app, vec![egui::Event::PointerMoved(tile + vec2(80.0, 80.0))]); - assert_eq!(egui::DragAndDrop::payload::(&ctx).as_deref(), Some(&PanelDrag::Symbol(names[0].clone()))); + let document = app.session.active().unwrap().uid; + assert_eq!(egui::DragAndDrop::payload::(&ctx).as_deref(), Some(&PanelDrag::Symbol { document, name: names[0].clone() })); } /// One headless frame of the panel menu; returns its painted labels. @@ -838,6 +930,193 @@ mod tests { menu_frame(ctx, app, vec![button(item, false)]); } + /// Clicks the menu item labeled `label` with `modifiers` held. + fn click_menu_held(ctx: &egui::Context, app: &mut VectorcraftApp, label: &str, modifiers: egui::Modifiers) { + let held = egui::Event::ModifiersChanged(modifiers); + let labels = menu_frame(ctx, app, vec![held.clone()]); + let item = labels.iter().find(|(t, _)| t.trim() == label).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("{label} in the menu")); + let press = |pressed| egui::Event::PointerButton { pos: item, button: egui::PointerButton::Primary, pressed, modifiers }; + menu_frame(ctx, app, vec![held.clone(), egui::Event::PointerMoved(item), press(true)]); + menu_frame(ctx, app, vec![held, press(false)]); + } + + /// Redefine Symbol in the panel menu with Shift held updates the symbol and leaves the + /// selected art as ordinary art, still selected; without Shift the art becomes an instance. + #[test] + fn shift_redefine_symbol_in_the_menu_keeps_the_art_as_ordinary_art() { + let mut app = leaf_and_dot(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let rect = NodeId(app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 60, "height": 20})).unwrap()["id"].as_u64().unwrap()); + app.run("select.set", json!({"ids": [rect.0]})).unwrap(); + let dot_art = |app: &VectorcraftApp| app.session.active().unwrap().doc.symbols.iter().find(|s| s.name == "Dot").map(|s| s.art.clone()); + let before = dot_art(&app); + click_menu_held(&ctx, &mut app, "Redefine Symbol", egui::Modifiers::SHIFT); + assert_ne!(dot_art(&app), before, "Dot is redefined"); + assert_eq!(art(&app, "Dot"), (0, 1), "the rectangle stays ordinary art"); + assert_eq!(app.session.active().unwrap().selection.objects, vec![rect], "and stays selected"); + click_menu_held(&ctx, &mut app, "Redefine Symbol", egui::Modifiers::NONE); + assert_eq!(art(&app, "Dot"), (1, 0), "without Shift the rectangle becomes an instance"); + } + + /// `leaf_and_dot` with a selected 60 × 20 rectangle; returns its id. + fn leaf_dot_and_rect() -> (VectorcraftApp, NodeId) { + let mut app = leaf_and_dot(); + let rect = NodeId(app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 60, "height": 20})).unwrap()["id"].as_u64().unwrap()); + app.run("select.set", json!({"ids": [rect.0]})).unwrap(); + (app, rect) + } + + /// New Symbol… in the panel menu with Shift held opens Symbol Options, and its OK makes the + /// symbol and leaves the selected art as ordinary art, still selected, in one undo step, though + /// Shift is let go before OK; Cancel makes no symbol. Without Shift, OK makes the art an + /// instance. + #[test] + fn shift_new_symbol_in_the_menu_keeps_the_art_as_ordinary_art() { + let (mut app, rect) = leaf_dot_and_rect(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + click_menu_held(&ctx, &mut app, "New Symbol…", egui::Modifiers::SHIFT); + assert_eq!(dialog_kind(&app), Some(crate::dialogs::symbol_options::KIND)); + crate::dialogs::cancel(&mut app); + assert_eq!(symbols(&mut app), ["Leaf", "Dot"], "Cancel makes no symbol"); + click_menu_held(&ctx, &mut app, "New Symbol…", egui::Modifiers::SHIFT); + menu_frame(&ctx, &mut app, vec![egui::Event::ModifiersChanged(egui::Modifiers::NONE)]); + let undo = undo_len(&app); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(symbols(&mut app), ["Leaf", "Dot", "New Symbol"]); + assert_eq!(art(&app, "New Symbol"), (0, 1), "the rectangle stays ordinary art"); + assert_eq!(app.session.active().unwrap().selection.objects, vec![rect], "and stays selected"); + assert_eq!(undo_len(&app), undo + 1, "one undo step"); + click_menu_held(&ctx, &mut app, "New Symbol…", egui::Modifiers::NONE); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(art(&app, "New Symbol 2"), (1, 0), "without Shift the rectangle becomes an instance"); + } + + /// Clicks the panel's New Symbol button with `modifiers` held. + fn click_new(app: &mut VectorcraftApp, modifiers: egui::Modifiers) { + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + let out = frame_held(&ctx, app, vec![], modifiers); + let at = clickable(&out).into_iter().find(|(l, _)| l == "New Symbol").expect("a New Symbol button").1; + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers }; + frame_held(&ctx, app, vec![egui::Event::PointerMoved(at), press(true), press(false)], modifiers); + } + + /// The New Symbol button with Shift held opens Symbol Options, whose OK keeps the selected art + /// as ordinary art; with Shift and Alt it makes the symbol at once under the default name and + /// keeps the art. Alt alone still makes the art an instance at once. + #[test] + fn shift_new_symbol_button_keeps_the_art_with_or_without_alt() { + let (mut app, rect) = leaf_dot_and_rect(); + click_new(&mut app, egui::Modifiers::SHIFT); + assert_eq!(dialog_kind(&app), Some(crate::dialogs::symbol_options::KIND)); + assert_eq!(symbols(&mut app).len(), 2, "no symbol before OK"); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(art(&app, "New Symbol"), (0, 1), "Shift: the rectangle stays ordinary art"); + assert_eq!(app.session.active().unwrap().selection.objects, vec![rect]); + let undo = undo_len(&app); + click_new(&mut app, egui::Modifiers::SHIFT | egui::Modifiers::ALT); + assert_eq!(dialog_kind(&app), None, "Alt skips Symbol Options"); + assert_eq!(symbols(&mut app), ["Leaf", "Dot", "New Symbol", "New Symbol 2"]); + assert_eq!(art(&app, "New Symbol 2"), (0, 1), "Shift and Alt: the rectangle stays ordinary art"); + assert_eq!(app.session.active().unwrap().selection.objects, vec![rect]); + assert_eq!(undo_len(&app), undo + 1, "one undo step"); + click_new(&mut app, egui::Modifiers::ALT); + assert_eq!(art(&app, "New Symbol 3"), (1, 0), "Alt alone: the rectangle becomes an instance"); + } + + /// The center of the panel's Symbol Options button, and of Break Link to Symbol and New Symbol + /// beside it, in a frame of `app`. + fn options_button(app: &mut VectorcraftApp) -> (Pos2, Pos2, Pos2) { + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + let found = clickable(&frame_held(&ctx, app, vec![], egui::Modifiers::NONE)); + let at = |label: &str| found.iter().find(|(l, _)| l == label).unwrap_or_else(|| panic!("a {label} button")).1; + (at("Break Link to Symbol"), at("Symbol Options"), at("New Symbol")) + } + + /// Clicks the panel at `at` with `modifiers` held. + fn click_at(app: &mut VectorcraftApp, at: Pos2, modifiers: egui::Modifiers) { + let ctx = egui::Context::default(); + frame_held(&ctx, app, vec![], modifiers); + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers }; + frame_held(&ctx, app, vec![egui::Event::PointerMoved(at), press(true), press(false)], modifiers); + } + + /// The bottom bar's Symbol Options button sits between Break Link to Symbol and New Symbol and + /// opens Symbol Options on the current symbol, as the panel menu's item does, with or without + /// Alt, and adds no undo step; in a document without symbols it is disabled and opens nothing. + #[test] + fn symbol_options_button_edits_the_current_symbol() { + let mut app = leaf_and_dot(); + app.run("select.all", json!({})).unwrap(); + let (break_link, options, new) = options_button(&mut app); + assert!(break_link.x < options.x && options.x < new.x, "Break Link, Symbol Options, New Symbol: {break_link:?} {options:?} {new:?}"); + let undo = undo_len(&app); + for (current, modifiers) in [("Dot", egui::Modifiers::NONE), ("Leaf", egui::Modifiers::ALT)] { + app.run("symbol.setCurrent", json!({ "name": current })).unwrap(); + click_at(&mut app, options, modifiers); + let d = app.ui.dialog.as_ref().expect("Symbol Options opens"); + assert_eq!(d.kind, crate::dialogs::symbol_options::KIND); + assert_eq!((d.fields.get("name"), d.fields.get("__edit")), (Some(&json!(current)), Some(&json!(true))), "{modifiers:?}"); + crate::dialogs::cancel(&mut app); + } + assert_eq!(undo_len(&app), undo, "opening the dialog adds no undo step"); + assert_eq!(symbols(&mut app), ["Leaf", "Dot"]); + let mut empty = VectorcraftApp::new(Session::new(), Default::default()); + empty.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + for (app, disabled) in [(&mut app, false), (&mut empty, true)] { + let out = frame_held(&ctx, app, vec![], egui::Modifiers::NONE); + let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; + let button = &nodes.iter().find(|(_, n)| n.label().is_some_and(|l| l.trim() == "Symbol Options")).expect("a Symbol Options button").1; + assert_eq!(button.is_disabled(), disabled, "disabled without a current symbol"); + } + click_at(&mut empty, options, egui::Modifiers::NONE); + assert_eq!(dialog_kind(&empty), None, "no symbol, no dialog"); + } + + /// Art dropped on the panel with Shift held as the primary button goes up becomes a new + /// symbol and stays ordinary art, still selected, though Shift is let go later in the same + /// frame; dropped without Shift, it becomes an instance. + #[test] + fn shift_art_drop_on_the_panel_keeps_the_art_as_ordinary_art() { + let (mut app, rect) = leaf_dot_and_rect(); + let ctx = egui::Context::default(); + let at = pos2(180.0, 60.0); + let release = |modifiers| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers }; + widgets::drag_art(&ctx, uid(&app).unwrap(), vec![rect]); + frame_held(&ctx, &mut app, vec![egui::Event::PointerMoved(at)], egui::Modifiers::SHIFT); + let undo = undo_len(&app); + let let_go = egui::Event::ModifiersChanged(egui::Modifiers::NONE); + frame_held(&ctx, &mut app, vec![release(egui::Modifiers::SHIFT), let_go], egui::Modifiers::SHIFT); + assert_eq!(symbols(&mut app).len(), 3, "a new symbol"); + assert_eq!(art(&app, "New Symbol"), (0, 1), "the rectangle stays ordinary art"); + assert_eq!(app.session.active().unwrap().selection.objects, vec![rect], "and stays selected"); + assert_eq!(undo_len(&app), undo + 1, "one undo step"); + widgets::drag_art(&ctx, uid(&app).unwrap(), vec![rect]); + frame_held(&ctx, &mut app, vec![egui::Event::PointerMoved(at)], egui::Modifiers::NONE); + frame_held(&ctx, &mut app, vec![release(egui::Modifiers::NONE)], egui::Modifiers::NONE); + assert_eq!(art(&app, "New Symbol 2"), (1, 0), "without Shift the rectangle becomes an instance"); + } + + /// `ui.symbolOptions` takes `keepArt` only as true or false, and only for a new symbol. + #[test] + fn symbol_options_checks_keep_art() { + let (mut app, _) = leaf_dot_and_rect(); + for bad in [json!("yes"), json!(1)] { + let e = app.run("ui.symbolOptions", json!({ "keepArt": bad })).unwrap_err(); + assert!(e.contains("`keepArt` must be true or false"), "{bad}: {e}"); + } + let e = app.run("ui.symbolOptions", json!({"edit": true, "name": "Dot", "keepArt": true})).unwrap_err(); + assert!(e.contains("only to a new symbol"), "{e}"); + assert_eq!(dialog_kind(&app), None); + app.run("ui.symbolOptions", json!({"edit": true, "name": "Dot", "keepArt": false})).unwrap(); + assert_eq!(dialog_kind(&app), Some(crate::dialogs::symbol_options::KIND)); + } + /// #4918: Select All Unused picks the symbols nothing places, Delete Symbol asks once and /// deletes them all in one undo step, and a click on a symbol picks one again. #[test] @@ -1008,6 +1287,134 @@ mod tests { assert_eq!(app.run("symbol.list", json!({})).unwrap()["symbols"][0]["alignToPixelGrid"], false); } + /// Does the selection hold a symbol instance that `wanted` takes, found by walking every + /// selected subtree on each call: what the cached flags must match. + fn walked(app: &VectorcraftApp, wanted: impl Fn(&Node) -> bool) -> bool { + app.session.active().is_some_and(|st| { + st.selection.objects.iter().any(|id| { + let mut any = false; + if let Some(n) = st.doc.node(*id) { + n.walk(&mut |c| any |= matches!(c.kind, NodeKind::SymbolInstance { .. }) && wanted(c)); + } + any + }) + }) + } + + /// Any instance, one with appearance changes, one Reset Transformation changes: walked again. + fn walked_flags(app: &VectorcraftApp) -> [bool; 3] { + let Some(doc) = app.session.active().map(|st| st.doc.clone()) else { return [false; 3] }; + [ + walked(app, |_| true), + walked(app, |c| !c.extras().symbol_overrides.is_empty()), + walked(app, |c| vectorcraft_engine::cmd::reset_transformation_changes(&doc, c)), + ] + } + + fn cached_flags(app: &mut VectorcraftApp) -> [bool; 3] { + [has_instances_selected(app), changed_instances_selected(app), transformed_instances_selected(app)] + } + + fn scans() -> usize { + INSTANCE_SCANS.with(std::cell::Cell::get) + } + + /// The Symbols and Properties panels' instance flags (Break Link, Reset Symbol Instance and the + /// Properties panel's Reset, Reset Transformation) are those a walk of the selection gives, for + /// plain, changed, scaled and grouped instances, several selected objects, nothing selected, + /// Undo and another document; the selection is walked once per document revision, however + /// often they are read. + #[test] + fn instance_flags_are_found_once_per_revision_and_match_a_walk_of_the_selection() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + let id = |v: Value| v["id"].as_u64().unwrap(); + let rect = id(app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap()); + let second = id(app.run("shape.rectangle", json!({"x": 60, "y": 10, "width": 40, "height": 40})).unwrap()); + let other = id(app.run("shape.rectangle", json!({"x": 300, "y": 10, "width": 40, "height": 40})).unwrap()); + // Reads every flag several times; the walk runs only when the revision changed. + let check = |app: &mut VectorcraftApp, want: [bool; 3], what: &str| { + let before = scans(); + for _ in 0..3 { + assert_eq!(cached_flags(app), want, "{what}"); + } + assert_eq!(walked_flags(app), want, "{what}: a walk of the selection agrees"); + assert!(scans() - before <= 1, "{what}: walked {} times", scans() - before); + }; + app.run("select.set", json!({"ids": [rect]})).unwrap(); + check(&mut app, [false; 3], "no instance"); + // Two objects, so the instance's art is a group whose first object can be painted. + let inst = id(app.run("symbol.new", json!({"name": "S", "ids": [rect, second], "type": "dynamic"})).unwrap()); + app.run("select.set", json!({"ids": [inst]})).unwrap(); + check(&mut app, [true, false, false], "a plain instance"); + app.run("symbol.instance.setAppearance", json!({"id": inst, "path": [0], "fill": "#ff0000"})).unwrap(); + app.run("select.set", json!({"ids": [inst]})).unwrap(); + check(&mut app, [true, true, false], "an instance with appearance changes"); + let scaled = id(app.run("symbol.place", json!({"name": "S", "x": 200, "y": 100})).unwrap()); + app.run("select.set", json!({"ids": [scaled]})).unwrap(); + app.run("object.scale", json!({"sx": 150, "sy": 50})).unwrap(); + check(&mut app, [true, false, true], "a scaled instance"); + app.run("select.set", json!({"ids": [scaled, other]})).unwrap(); + let group = id(app.run("object.group", json!({})).unwrap()); + app.run("select.set", json!({"ids": [group]})).unwrap(); + check(&mut app, [true, false, true], "an instance in a selected group"); + app.run("select.set", json!({"ids": [inst, group]})).unwrap(); + check(&mut app, [true, true, true], "several selected objects"); + app.run("select.set", json!({"ids": [other]})).unwrap(); + check(&mut app, [false; 3], "select.set to a path"); + app.run("select.none", json!({})).unwrap(); + check(&mut app, [false; 3], "nothing selected"); + // Undo takes the group apart again. + app.run("edit.undo", json!({})).unwrap(); + let undone = walked_flags(&app); + check(&mut app, undone, "after Undo"); + // At one revision the walk runs once; a new revision walks again. + app.run("select.set", json!({"ids": [inst, scaled]})).unwrap(); + let before = scans(); + cached_flags(&mut app); + cached_flags(&mut app); + assert_eq!(scans(), before + 1); + app.run("select.set", json!({"ids": [inst]})).unwrap(); + cached_flags(&mut app); + assert_eq!(scans(), before + 2); + // Another document has its own uid, so its flags are found again. + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + let plain = id(app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap()); + app.run("select.set", json!({"ids": [plain]})).unwrap(); + check(&mut app, [false; 3], "another document"); + } + + /// The Properties panel (its Reset quick action) and the Symbols panel (Break Link) share one + /// walk of the selection while the document does not change. + #[test] + fn properties_and_symbols_panels_walk_the_selection_once_per_revision() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let rect = |app: &mut VectorcraftApp, x: f64| { + app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap() + }; + let ids = [rect(&mut app, 10.0), rect(&mut app, 60.0)]; + let inst = app.run("symbol.new", json!({"name": "S", "ids": ids, "type": "dynamic"})).unwrap()["id"].as_u64().unwrap(); + app.run("symbol.instance.setAppearance", json!({"id": inst, "path": [0], "fill": "#ff0000"})).unwrap(); + app.run("select.set", json!({"ids": [inst]})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let before = scans(); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| super::super::properties::show(&mut app, ui)); + out.textures_delta.clear(); + assert_eq!(scans(), before + 1, "the Properties panel reads the flags"); + for _ in 0..3 { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + super::super::properties::show(&mut app, ui); + show(&mut app, ui); + }); + out.textures_delta.clear(); + } + assert_eq!(scans(), before + 1, "one walk for both panels over four frames"); + assert_eq!(cached_flags(&mut app), [true, true, false]); + assert_eq!(scans(), before + 1); + } + /// F8 is Symbol Options… (`ui.symbolOptions`) by default, on every platform. Shift+F8 and Cmd+F8 /// are still the Transform and Info panels' keys, and Cmd+Shift+F8 is still Edit Pattern's. No /// other command, tool or panel has F8 by default. @@ -1979,7 +2386,12 @@ mod tests { frame(&ctx, &mut app, vec![egui::Event::PointerMoved(from), button(from, true)]); frame(&ctx, &mut app, vec![egui::Event::PointerMoved(from + vec2(40.0, 40.0))]); frame(&ctx, &mut app, vec![egui::Event::PointerMoved(from + vec2(80.0, 80.0))]); - assert_eq!(egui::DragAndDrop::payload::(&ctx).as_deref(), Some(&PanelDrag::Symbol("Leaf".into())), "{view}"); + let document = uid(&app).expect("an active document"); + assert_eq!( + egui::DragAndDrop::payload::(&ctx).as_deref(), + Some(&PanelDrag::Symbol { document, name: "Leaf".into() }), + "{view}" + ); let out = frame_held(&ctx, &mut app, vec![egui::Event::PointerMoved(new.center())], egui::Modifiers::NONE); assert!(outlined(&out, new), "{view}: outlined while Leaf is held over it"); frame(&ctx, &mut app, vec![button(new.center(), false)]); @@ -2008,14 +2420,14 @@ mod tests { let undo = app.session.active().unwrap().history.undo.len(); let ctx = egui::Context::default(); // The payloads are set directly, as if dragged from this document's panel. - set_pstate(&ctx, DRAG_DOC, uid(&app)); + let document = uid(&app).expect("an active document"); let new = button_rect(&ctx, &mut app, "New Symbol"); let elsewhere = new.center() - vec2(0.0, 60.0); let cases = [ ("a library symbol", PanelDrag::LibrarySymbol { library: "basic-shapes".into(), name: "Leaf".into() }, new.center()), ("art", PanelDrag::Art(vec![leaf]), new.center()), - ("a stale name", PanelDrag::Symbol("Gone".into()), new.center()), - ("a symbol released elsewhere", PanelDrag::Symbol("Leaf".into()), elsewhere), + ("a stale name", PanelDrag::Symbol { document, name: "Gone".into() }, new.center()), + ("a symbol released elsewhere", PanelDrag::Symbol { document, name: "Leaf".into() }, elsewhere), ]; for (case, drag, at) in cases { egui::DragAndDrop::set_payload(&ctx, drag); @@ -2042,7 +2454,8 @@ mod tests { frame(&ctx, &mut app, vec![egui::Event::PointerMoved(tile), button(tile, true)]); frame(&ctx, &mut app, vec![egui::Event::PointerMoved(tile + vec2(40.0, 40.0))]); frame(&ctx, &mut app, vec![egui::Event::PointerMoved(tile + vec2(80.0, 80.0))]); - assert_eq!(egui::DragAndDrop::payload::(&ctx).as_deref(), Some(&PanelDrag::Symbol("Leaf".into()))); + let document = uid(&app).expect("an active document"); + assert_eq!(egui::DragAndDrop::payload::(&ctx).as_deref(), Some(&PanelDrag::Symbol { document, name: "Leaf".into() })); // While Leaf is held, a new document with a Leaf of its own becomes active. app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 30})).unwrap(); @@ -2222,14 +2635,14 @@ mod tests { let ctx = egui::Context::default(); crate::theme::install_fonts(&ctx); // The payloads are set directly, as if dragged from this document's panel. - set_pstate(&ctx, DRAG_DOC, uid(&app)); + let document = uid(&app).expect("an active document"); let trash = button_rect(&ctx, &mut app, "Delete Symbol"); let elsewhere = trash.center() - vec2(0.0, 60.0); let cases = [ ("a library symbol", PanelDrag::LibrarySymbol { library: "basic-shapes".into(), name: "Leaf".into() }, trash.center()), ("art", PanelDrag::Art(vec![leaf]), trash.center()), - ("a stale name", PanelDrag::Symbol("Gone".into()), trash.center()), - ("a symbol released elsewhere", PanelDrag::Symbol("Dot".into()), elsewhere), + ("a stale name", PanelDrag::Symbol { document, name: "Gone".into() }, trash.center()), + ("a symbol released elsewhere", PanelDrag::Symbol { document, name: "Dot".into() }, elsewhere), ]; for (case, drag, at) in cases { egui::DragAndDrop::set_payload(&ctx, drag); @@ -2246,7 +2659,7 @@ mod tests { frame(&ctx, &mut app, vec![egui::Event::PointerMoved(tile), button(tile, true)]); frame(&ctx, &mut app, vec![egui::Event::PointerMoved(tile + vec2(40.0, 40.0))]); frame(&ctx, &mut app, vec![egui::Event::PointerMoved(tile + vec2(80.0, 80.0))]); - assert_eq!(egui::DragAndDrop::payload::(&ctx).as_deref(), Some(&PanelDrag::Symbol("Leaf".into()))); + assert_eq!(egui::DragAndDrop::payload::(&ctx).as_deref(), Some(&PanelDrag::Symbol { document, name: "Leaf".into() })); app.run("symbol.delete", json!({"name": "Leaf"})).unwrap(); let undo = app.session.active().unwrap().history.undo.len(); let out = frame_held(&ctx, &mut app, vec![egui::Event::PointerMoved(trash.center())], egui::Modifiers::NONE); @@ -2258,7 +2671,7 @@ mod tests { frame(&ctx, &mut app, vec![egui::Event::PointerMoved(tile), button(tile, true)]); frame(&ctx, &mut app, vec![egui::Event::PointerMoved(tile + vec2(40.0, 40.0))]); frame(&ctx, &mut app, vec![egui::Event::PointerMoved(tile + vec2(80.0, 80.0))]); - assert_eq!(egui::DragAndDrop::payload::(&ctx).as_deref(), Some(&PanelDrag::Symbol("Dot".into()))); + assert_eq!(egui::DragAndDrop::payload::(&ctx).as_deref(), Some(&PanelDrag::Symbol { document, name: "Dot".into() })); app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 30})).unwrap(); app.run("symbol.new", json!({"name": "Dot"})).unwrap(); @@ -2274,6 +2687,177 @@ mod tests { assert_eq!(symbols(&mut app), ["Dot"], "the first document keeps its Dot"); } + /// The rects `out` outlines as drop targets (1.5 pt strokes). + fn drop_outlines(out: &egui::FullOutput) -> Vec { + out.shapes + .iter() + .filter_map(|c| match &c.shape { + egui::Shape::Rect(r) if (r.stroke.width - 1.5).abs() < 0.01 => Some(r.rect), + _ => None, + }) + .collect() + } + + /// Where symbol `name`'s tile or row is in the panel: its name in the list views, its tile (the + /// 44 pt squares, in panel order) in Thumbnail View. + fn item_at(ctx: &egui::Context, app: &mut VectorcraftApp, name: &str) -> Pos2 { + if app.ui.symbols_view != View::Thumbnail { + return panel_labels(ctx, app, &[name]).first().map(|l| l.1).unwrap_or_else(|| panic!("a {name} row")); + } + let out = frame_held(ctx, app, vec![], egui::Modifiers::NONE); + let tiles: Vec = out + .shapes + .iter() + .filter_map(|c| match &c.shape { + egui::Shape::Rect(r) if (r.rect.width() - 44.0).abs() < 0.01 && (r.rect.height() - 44.0).abs() < 0.01 => Some(r.rect), + _ => None, + }) + .collect(); + let i = symbols(app).iter().position(|n| n == name).unwrap_or_else(|| panic!("a {name} symbol")); + tiles.get(i).map(|r| r.center()).unwrap_or_else(|| panic!("a {name} tile in {tiles:?}")) + } + + /// The art of symbol `name` in the active document. + fn symbol_art(app: &VectorcraftApp, name: &str) -> Arc { + let doc = &app.session.active().unwrap().doc; + doc.symbols.iter().find(|s| s.name == name).map(|s| s.art.clone()).unwrap_or_else(|| panic!("a {name} symbol")) + } + + fn undo_len(app: &VectorcraftApp) -> usize { + app.session.active().unwrap().history.undo.len() + } + + /// Art dragged off the canvas and released with Alt (Option on macOS) held on a symbol's tile + /// or row, in each view, redefines that symbol and not the current one: its instances take the + /// art, the art becomes an instance of it, and no symbol is added, in one undo step. Only that + /// tile or row is outlined while the art is held over it with Alt. + #[test] + fn alt_art_drop_on_a_symbol_redefines_that_symbol_in_one_step() { + for view in ["thumbnail", "smallList", "largeList"] { + let mut app = leaf_and_dot(); + app.run("ui.panelView", json!({"panel": "symbols", "view": view})).unwrap(); + let shape = app.run("shape.rectangle", json!({"x": 200, "y": 120, "width": 40, "height": 20})).unwrap()["id"].as_u64().unwrap(); + let (leaf, dot) = (symbol_art(&app, "Leaf"), symbol_art(&app, "Dot")); + let placed = instance_of(&app, "Leaf").expect("a Leaf instance"); + let undo = undo_len(&app); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let (at, other) = (item_at(&ctx, &mut app, "Leaf"), item_at(&ctx, &mut app, "Dot")); + widgets::drag_art(&ctx, uid(&app).unwrap(), vec![NodeId(shape)]); + let out = frame_held(&ctx, &mut app, vec![egui::Event::PointerMoved(at)], egui::Modifiers::ALT); + let outlines = drop_outlines(&out); + assert_eq!(outlines.len(), 1, "{view}: only the Leaf item is outlined: {outlines:?}"); + assert!(outlines[0].contains(at) && !outlines[0].contains(other), "{view}: {outlines:?}"); + frame_held(&ctx, &mut app, vec![alt_release(at)], egui::Modifiers::ALT); + assert_eq!(symbols(&mut app), ["Leaf", "Dot"], "{view}: no symbol added"); + assert_eq!(undo_len(&app), undo + 1, "{view}: one undo step"); + // The Leaf instance there was takes the 40 × 20 rectangle's shape, where the old art was square. + let doc = app.session.active().unwrap().doc.clone(); + let shape = doc.node(placed).and_then(|n| n.geometric_bounds()).map(|b| b.width() / b.height()); + assert!(shape.is_some_and(|r| (r - 2.0).abs() < 1e-6), "{view}: Leaf is the dropped art: {shape:?}"); + assert!(Arc::ptr_eq(&dot, &symbol_art(&app, "Dot")), "{view}: the current symbol Dot is unchanged"); + assert_eq!(art(&app, "Leaf"), (2, 0), "{view}: the art became a Leaf instance"); + app.run("edit.undo", json!({})).unwrap(); + assert!(Arc::ptr_eq(&leaf, &symbol_art(&app, "Leaf")), "{view}: undo restores Leaf"); + assert_eq!(art(&app, "Leaf"), (1, 1), "{view}: undo restores the art"); + app.run("edit.redo", json!({})).unwrap(); + assert_eq!(art(&app, "Leaf"), (2, 0), "{view}: redo"); + } + } + + /// Alt held as the primary button goes up redefines the symbol, though Alt is let go later in + /// the same frame. + #[test] + fn alt_let_go_after_the_release_in_the_same_frame_still_redefines() { + let mut app = leaf_and_dot(); + let shape = app.run("shape.rectangle", json!({"x": 200, "y": 120, "width": 40, "height": 20})).unwrap()["id"].as_u64().unwrap(); + let leaf = symbol_art(&app, "Leaf"); + let undo = undo_len(&app); + let ctx = egui::Context::default(); + let at = item_at(&ctx, &mut app, "Leaf"); + widgets::drag_art(&ctx, uid(&app).unwrap(), vec![NodeId(shape)]); + frame_held(&ctx, &mut app, vec![egui::Event::PointerMoved(at)], egui::Modifiers::ALT); + frame_held(&ctx, &mut app, vec![alt_release(at), egui::Event::ModifiersChanged(egui::Modifiers::NONE)], egui::Modifiers::ALT); + assert_eq!(symbols(&mut app), ["Leaf", "Dot"], "no symbol added"); + assert!(!Arc::ptr_eq(&leaf, &symbol_art(&app, "Leaf")), "Leaf is redefined"); + assert_eq!(undo_len(&app), undo + 1, "one undo step"); + } + + /// Art released on a symbol without Alt makes a new symbol, as a drop elsewhere on the list + /// does, and leaves the symbol under the pointer as it was; nothing is outlined but the list. + #[test] + fn a_plain_art_drop_on_a_symbol_makes_a_new_symbol() { + let mut app = leaf_and_dot(); + let shape = app.run("shape.rectangle", json!({"x": 200, "y": 120, "width": 40, "height": 20})).unwrap()["id"].as_u64().unwrap(); + let leaf = symbol_art(&app, "Leaf"); + let ctx = egui::Context::default(); + let at = item_at(&ctx, &mut app, "Leaf"); + widgets::drag_art(&ctx, uid(&app).unwrap(), vec![NodeId(shape)]); + let out = frame_held(&ctx, &mut app, vec![egui::Event::PointerMoved(at)], egui::Modifiers::NONE); + let outlines = drop_outlines(&out); + assert!(outlines.len() == 1 && outlines[0].width() > 100.0, "the list is outlined, not the tile: {outlines:?}"); + frame(&ctx, &mut app, vec![button(at, false)]); + assert_eq!(symbols(&mut app).len(), 3, "a new symbol"); + assert!(Arc::ptr_eq(&leaf, &symbol_art(&app, "Leaf")), "Leaf is unchanged"); + } + + /// An Alt drop that cannot redefine the symbol under the pointer changes nothing, makes no new + /// symbol and adds no undo step: art of another document, objects the document no longer has, + /// no objects, and a release away from the panel are not outlined, and art holding an instance + /// of the symbol is refused when it is released. + #[test] + fn an_alt_art_drop_that_cannot_redefine_changes_nothing() { + let mut app = leaf_and_dot(); + let shape = app.run("shape.rectangle", json!({"x": 200, "y": 120, "width": 40, "height": 20})).unwrap()["id"].as_u64().unwrap(); + let instance = instance_of(&app, "Leaf").expect("a Leaf instance"); + let leaf = symbol_art(&app, "Leaf"); + let undo = undo_len(&app); + let ctx = egui::Context::default(); + let at = item_at(&ctx, &mut app, "Leaf"); + let doc = uid(&app).unwrap(); + let away = pos2(230.0, 395.0); + let cases = [ + ("another document's art", doc + 1, vec![NodeId(shape)], at, false), + ("objects the document lacks", doc, vec![NodeId(u64::MAX)], at, false), + ("no objects", doc, vec![], at, false), + ("a release away from the panel", doc, vec![NodeId(shape)], away, false), + ("a Leaf instance", doc, vec![instance], at, true), + ]; + for (case, from, ids, to, outline) in cases { + widgets::drag_art(&ctx, from, ids); + let out = frame_held(&ctx, &mut app, vec![egui::Event::PointerMoved(to)], egui::Modifiers::ALT); + assert_eq!(drop_outlines(&out).len(), usize::from(outline), "{case}: {:?}", drop_outlines(&out)); + frame_held(&ctx, &mut app, vec![alt_release(to)], egui::Modifiers::ALT); + egui::DragAndDrop::clear_payload(&ctx); + assert_eq!(symbols(&mut app), ["Leaf", "Dot"], "{case}: no symbol added"); + assert!(Arc::ptr_eq(&leaf, &symbol_art(&app, "Leaf")), "{case}: Leaf is unchanged"); + assert_eq!(undo_len(&app), undo, "{case}: no undo step"); + } + } + + /// Art held over a symbol, with Alt or without, and released with the secondary button is not + /// dropped: no symbol is redefined or added and no undo step is added. + #[test] + fn a_secondary_button_release_drops_no_art() { + let mut app = leaf_and_dot(); + let shape = app.run("shape.rectangle", json!({"x": 200, "y": 120, "width": 40, "height": 20})).unwrap()["id"].as_u64().unwrap(); + let leaf = symbol_art(&app, "Leaf"); + let undo = undo_len(&app); + let ctx = egui::Context::default(); + let at = item_at(&ctx, &mut app, "Leaf"); + let secondary = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Secondary, pressed: false, modifiers: Default::default() }; + for (case, modifiers) in [("with Alt", egui::Modifiers::ALT), ("without Alt", egui::Modifiers::NONE)] { + widgets::drag_art(&ctx, uid(&app).unwrap(), vec![NodeId(shape)]); + let out = frame_held(&ctx, &mut app, vec![egui::Event::PointerMoved(at)], modifiers); + assert_eq!(drop_outlines(&out).len(), 1, "{case}: the art is held over a target"); + frame_held(&ctx, &mut app, vec![secondary.clone()], modifiers); + egui::DragAndDrop::clear_payload(&ctx); + assert_eq!(symbols(&mut app), ["Leaf", "Dot"], "{case}: no symbol added"); + assert!(Arc::ptr_eq(&leaf, &symbol_art(&app, "Leaf")), "{case}: Leaf is unchanged"); + assert_eq!(undo_len(&app), undo, "{case}: no undo step"); + } + } + /// CPU time of this thread in nanoseconds where the system reports it (Linux), else `None`. fn thread_cpu_ns() -> Option { std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok() diff --git a/crates/ui-egui/src/panels/tabs.rs b/crates/ui-egui/src/panels/tabs.rs index 2f45f62f75..a09c634967 100644 --- a/crates/ui-egui/src/panels/tabs.rs +++ b/crates/ui-egui/src/panels/tabs.rs @@ -431,8 +431,8 @@ fn stops_json(stops: &[TabStop]) -> Value { /// frame of the selected stories ([`super::character::selected_stories`]). Returns false when it /// fails. fn apply(app: &mut VectorcraftApp, stops: &[TabStop]) -> bool { - if let Some((id, a, b)) = super::character::text_editing(app) { - super::character::end_typing(app); + let Ok(editing) = super::character::text_editing_kept(app) else { return false }; + if let Some((id, a, b)) = editing { let p = match super::character::text_story(app) { // After Select All in threaded text: every paragraph of every frame. Some(story) => json!({"stops": stops_json(stops), "ids": story.iter().map(|f| f.0).collect::>()}), diff --git a/crates/ui-egui/src/panels/tests_appearance.rs b/crates/ui-egui/src/panels/tests_appearance.rs index 1db803b636..5ef1d8ce4a 100644 --- a/crates/ui-egui/src/panels/tests_appearance.rs +++ b/crates/ui-egui/src/panels/tests_appearance.rs @@ -2064,3 +2064,49 @@ fn a_dash_typed_in_a_stroke_popup_sticks_when_a_click_outside_closes_it() { assert!(!texts.iter().any(|(t, _)| t == "Dashed Line"), "{link}: the popup closed"); } } + +/// `first_selected` gives the `Arc` the document holds for the first selected object, nested in a +/// group too, not a copy of it; nothing with nothing selected or no document open. +#[test] +fn first_selected_is_the_node_the_document_holds() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + assert!(first_selected(&app).is_none(), "no document"); + run(&mut app, "file.new", json!({"width": 200, "height": 200})); + let a = run(&mut app, "shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50}))["id"].clone(); + let b = run(&mut app, "shape.ellipse", json!({"x": 70, "y": 10, "width": 50, "height": 50}))["id"].clone(); + let held = |app: &VectorcraftApp, id: &Value| layers::node_arc(&app.session.active().unwrap().doc, NodeId(id.as_u64().unwrap())).unwrap(); + run(&mut app, "select.set", json!({ "ids": [a, b] })); + let id = app.session.active().unwrap().selection.objects[0]; + let first = first_selected(&app).expect("a selected object"); + assert_eq!(first.id, id, "the first of the selection"); + assert!(Arc::ptr_eq(&first, &held(&app, &json!(id.0))), "the first selected object, as the document holds it"); + run(&mut app, "object.group", json!({})); + run(&mut app, "select.set", json!({ "ids": [a] })); + assert!(Arc::ptr_eq(&first_selected(&app).expect("the rectangle"), &held(&app, &a)), "a node inside a group"); + run(&mut app, "select.none", json!({})); + assert!(first_selected(&app).is_none(), "nothing selected"); +} + +/// Properties, Appearance and Transparency show the selected object's current opacity after an +/// edit and after Undo, never an earlier one. +#[test] +fn panels_show_the_selected_object_after_an_edit_and_after_undo() { + type Panel = fn(&mut VectorcraftApp, &mut egui::Ui); + let panels: [(&str, Panel); 3] = [("Properties", properties::show), ("Appearance", appearance::show), ("Transparency", transparency::show)]; + let mut app = app_with_rect(); + // One context per panel, kept across the edits, as the app keeps its own. + let ctxs: Vec = panels.iter().map(|_| egui::Context::default()).collect(); + let shows = |app: &mut VectorcraftApp, want: &str, not: &str| { + for ((name, panel), ctx) in panels.iter().zip(&ctxs) { + let texts = frame_in(ctx, app, *panel); + assert!(texts.iter().any(|t| t.contains(want)), "{name} shows {want}: {texts:?}"); + assert!(!texts.iter().any(|t| t.contains(not)), "{name} no longer shows {not}: {texts:?}"); + } + }; + run(&mut app, "transparency.set", json!({"opacity": 60})); + shows(&mut app, "60%", "35%"); + run(&mut app, "transparency.set", json!({"opacity": 35})); + shows(&mut app, "35%", "60%"); + run(&mut app, "edit.undo", json!({})); + shows(&mut app, "60%", "35%"); +} diff --git a/crates/ui-egui/src/panels/tests_color_wheel_box.rs b/crates/ui-egui/src/panels/tests_color_wheel_box.rs new file mode 100644 index 0000000000..0b59a44d98 --- /dev/null +++ b/crates/ui-egui/src/panels/tests_color_wheel_box.rs @@ -0,0 +1,374 @@ +//! The Color Wheel panel's box view drawn headless: `ui.colorWheel`, the field and the strip of +//! each channel, the panel menu, the saved settings, the arrow keys and what screen readers read, +//! and the Color Picker's channel slider, which is the same widget as the strip. + +use egui::accesskit::{Action, ActionData, ActionRequest}; +use egui::{Event, Modifiers, PointerButton, Pos2, Rect, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; +use vectorcraft_color::Color; +use vectorcraft_color::cms; +use vectorcraft_engine::Session; + +use super::color_wheel::{Settings, View, box_pick, box_pos, display_hsb, show}; +use crate::VectorcraftApp; +use crate::dialogs::color_picker::Channel; + +/// An app with a selected rectangle filled with `fill`, its Color Wheel panel on the box of +/// `channel`. +fn app(fill: serde_json::Value, channel: &str) -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + app.run("paint.setFill", json!({"color": fill})).unwrap(); + app.run("ui.colorWheel", json!({"view": "box", "channel": channel})).unwrap(); + app +} + +/// The panel in a 260-point-wide flyout, with the app's shortcuts after it as in a frame of the app. +fn harness(app: VectorcraftApp) -> Harness<'static, VectorcraftApp> { + let mut h = Harness::builder().with_size(vec2(260.0, 320.0)).build_ui_state( + |ui, app: &mut VectorcraftApp| { + show(app, ui); + crate::shortcuts::handle(app, ui.ctx()); + }, + app, + ); + h.run_steps(2); + h +} + +fn rect_of(h: &Harness<'static, VectorcraftApp>, label: &str) -> Rect { + h.get_by_label(label).rect() +} + +/// The point (x across, y up; 0..1 each) of `r`. +fn at(r: Rect, x: f32, y: f32) -> Pos2 { + Pos2::new(r.left() + x * r.width(), r.bottom() - y * r.height()) +} + +fn press(h: &mut Harness<'static, VectorcraftApp>, pos: Pos2, pressed: bool) { + h.event(Event::PointerMoved(pos)); + h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + h.run_steps(1); +} + +fn click(h: &mut Harness<'static, VectorcraftApp>, pos: Pos2) { + press(h, pos, true); + press(h, pos, false); + h.run_steps(1); +} + +/// A drag through `points`, pressed at the first and released at the last. +fn drag(h: &mut Harness<'static, VectorcraftApp>, points: &[Pos2]) { + let (Some(first), Some(last)) = (points.first(), points.last()) else { return }; + press(h, *first, true); + for p in points { + for _ in 0..2 { + h.event(Event::PointerMoved(*p)); + h.run_steps(1); + } + } + press(h, *last, false); + h.run_steps(1); +} + +fn key(h: &mut Harness<'static, VectorcraftApp>, key: egui::Key) { + h.key_press_modifiers(Modifiers::NONE, key); + h.run_steps(1); +} + +fn fill(app: &VectorcraftApp) -> Color { + crate::panels::current_paints(app).0.color().expect("a solid fill") +} + +fn hsb(c: &Color) -> [f32; 3] { + display_hsb(&cms::active(), c) +} + +fn rgb(c: &Color) -> [f32; 3] { + cms::active().display_rgb(c) +} + +fn near(a: [f32; 3], b: [f32; 3], tol: f32) -> bool { + (0..3).all(|i| (a[i] - b[i]).abs() <= tol) +} + +fn undo_len(app: &VectorcraftApp) -> usize { + app.session.doc().unwrap().history.undo.len() +} + +/// With Hue as the channel and a red fill, the field's top-left corner is white, its top-right +/// corner red and its bottom edge black. +#[test] +fn the_hue_box_picks_saturation_across_and_brightness_up() { + let mut h = harness(app(json!("#ff0000"), "hue")); + let field = rect_of(&h, "Color box"); + click(&mut h, field.left_top() + vec2(0.2, 0.2)); + assert!(near(rgb(&fill(h.state())), [1.0, 1.0, 1.0], 0.01), "{:?}", rgb(&fill(h.state()))); + click(&mut h, field.right_top() + vec2(-0.2, 0.2)); + assert!(near(rgb(&fill(h.state())), [1.0, 0.0, 0.0], 0.01), "the hue is kept through white: {:?}", rgb(&fill(h.state()))); + click(&mut h, at(field, 0.5, 0.0) + vec2(0.0, -0.2)); + assert!(near(rgb(&fill(h.state())), [0.0, 0.0, 0.0], 0.01), "{:?}", rgb(&fill(h.state()))); +} + +/// Red puts blue across and green up, as the Color Picker's field does, and red stays as it was. +#[test] +fn the_red_box_puts_blue_across_and_green_up() { + let mut h = harness(app(json!([0.2, 0.4, 0.6]), "red")); + let field = rect_of(&h, "Color box"); + let red = rgb(&fill(h.state()))[0]; + click(&mut h, at(field, 0.75, 0.25)); + assert!(near(rgb(&fill(h.state())), [red, 0.25, 0.75], 0.01), "{:?}", rgb(&fill(h.state()))); + let read = h.get_by_label("Color box").value().unwrap_or_default(); + assert!(read.starts_with("Blue ") && read.contains(", Green "), "{read}"); +} + +/// A drag in the field is one undo step, and a drag on the strip sets the third component. +#[test] +fn a_drag_in_the_field_is_one_undo_step_and_the_strip_sets_the_channel() { + let mut h = harness(app(json!([0.6, 0.3, 0.3]), "hue")); + let field = rect_of(&h, "Color box"); + let undo = undo_len(h.state()); + drag(&mut h, &[at(field, 0.2, 0.2), at(field, 0.5, 0.5), at(field, 0.8, 0.9)]); + assert_eq!(undo_len(h.state()), undo + 1, "one undo step"); + assert!(near(hsb(&fill(h.state())), [0.0, 0.8, 0.9], 0.01), "{:?}", hsb(&fill(h.state()))); + let strip = rect_of(&h, "Hue"); + drag(&mut h, &[strip.center_bottom() + vec2(0.0, -1.0), strip.center()]); + let after = hsb(&fill(h.state())); + assert!((after[0] - 180.0).abs() < 2.0 && (after[1] - 0.8).abs() < 0.01 && (after[2] - 0.9).abs() < 0.01, "{after:?}"); + assert_eq!(undo_len(h.state()), undo + 2); +} + +/// After a click on the strip, ↑ raises the channel by one unit, and the strip declares its range +/// and its adjust actions to screen readers. +#[test] +fn the_strip_takes_the_arrow_keys_and_screen_readers_actions() { + let mut h = harness(app(json!([0.6, 0.3, 0.3]), "brightness")); + let strip = rect_of(&h, "Brightness"); + click(&mut h, at(strip, 0.5, 0.5)); + let b = (hsb(&fill(h.state()))[2] * 100.0).round(); + key(&mut h, egui::Key::ArrowUp); + assert!((hsb(&fill(h.state()))[2] * 100.0 - (b + 1.0)).abs() < 0.01, "{:?}", hsb(&fill(h.state()))); + let node = h.get_by_label("Brightness").accesskit_node(); + assert!([Action::Increment, Action::Decrement, Action::SetValue].iter().all(|a| node.data().supports_action(*a))); + assert_eq!((node.data().min_numeric_value(), node.data().max_numeric_value()), (Some(0.0), Some(100.0))); + let (target_node, target_tree) = node.locate(); + let data = Some(ActionData::NumericValue(25.0)); + h.event(Event::AccessKitActionRequest(ActionRequest { target_node, target_tree, action: Action::SetValue, data })); + h.run_steps(1); + assert!((hsb(&fill(h.state()))[2] - 0.25).abs() < 0.01, "{:?}", hsb(&fill(h.state()))); +} + +/// `ui.colorWheel` sets the keys it is given and keeps the others, `{}` reads them, a value off the +/// list answers an error that names the accepted values and changes nothing, and `ui.inspect` +/// reports the settings. +#[test] +fn ui_color_wheel_sets_and_reads_the_view_and_the_channel() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + assert_eq!(app.run("ui.colorWheel", json!({})).unwrap(), json!({"view": "wheel", "channel": "hue"})); + assert_eq!(app.run("ui.colorWheel", json!({"view": "box"})).unwrap(), json!({"view": "box", "channel": "hue"})); + assert_eq!(app.run("ui.colorWheel", json!({"channel": "green"})).unwrap(), json!({"view": "box", "channel": "green"})); + let e = app.run("ui.colorWheel", json!({"view": "triangle"})).unwrap_err(); + assert_eq!(e, "`view` must be wheel or box"); + let e = app.run("ui.colorWheel", json!({"view": "wheel", "channel": 7})).unwrap_err(); + assert_eq!(e, "`channel` must be hue, saturation, brightness, red, green or blue"); + assert_eq!(app.ui.color_wheel, Settings { view: View::Box, channel: Channel::Green }, "an error changes nothing"); + let ui = crate::control::inspect(&app, &egui::Context::default()); + assert_eq!(ui["ui"]["color_wheel"], json!({"view": "box", "channel": "green"})); +} + +/// The command's errors are translated in the catalogs that translate status and error messages, +/// and each translation keeps the accepted values. +#[test] +fn ui_color_wheel_errors_are_translated() { + let errors = [ + ("`view` must be wheel or box", &["wheel", "box"][..]), + ("`channel` must be hue, saturation, brightness, red, green or blue", &["hue", "saturation", "brightness", "red", "green", "blue"][..]), + ]; + for code in [ + "cs", "de", "el", "es", "fr", "hi", "hu", "it", "ja", "ka", "ko", "pl", "pt-br", "ru", "sv", "uk", "vi", "zh-hans", "zh-hant", "fi", "tr", + "ca", "nl", "bs", "da", "id", + ] { + let lang = crate::i18n::Lang::from_code(code).expect("registered"); + for (error, values) in errors { + let shown = crate::i18n::message(lang, error); + assert_ne!(shown, error, "{code}"); + assert!(values.iter().all(|v| shown.contains(v)), "{code}: {shown}"); + } + } +} + +/// Params that are not an object, and a key the command does not take, are errors that change +/// nothing. +#[test] +fn ui_color_wheel_rejects_other_params() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("ui.colorWheel", json!({"view": "box", "channel": "red"})).unwrap(); + let e = app.run("ui.colorWheel", json!("box")).unwrap_err(); + assert_eq!(e, "the params must be an object, not \"box\""); + let e = app.run("ui.colorWheel", json!([1])).unwrap_err(); + assert_eq!(e, "the params must be an object, not [1]"); + let e = app.run("ui.colorWheel", json!({"veiw": "wheel"})).unwrap_err(); + assert_eq!(e, "unknown parameter `veiw`; the command takes: view, channel"); + let e = app.run("ui.colorWheel", json!({"view": "wheel", "chanel": "blue"})).unwrap_err(); + assert_eq!(e, "unknown parameter `chanel`; the command takes: view, channel"); + assert_eq!(app.ui.color_wheel, Settings { view: View::Box, channel: Channel::Red }, "an error changes nothing"); +} + +/// With None there is no color to edit: the strip reads 0 to screen readers, as the hue ring does, +/// and its actions still set the fill from the last solid color the box shows. +#[test] +fn with_a_none_fill_the_strip_reads_zero_and_its_actions_set_the_fill() { + let mut app = app(json!("#ff0000"), "brightness"); + app.run("paint.setFill", json!({"none": true})).unwrap(); + let mut h = harness(app); + assert_eq!(h.get_by_label("Color box").value(), None, "no marker in the field"); + let node = h.get_by_label("Brightness").accesskit_node(); + assert_eq!(node.data().numeric_value(), Some(0.0), "no value on the strip"); + let last = hsb(&h.state().session.last_solid); + let (target_node, target_tree) = node.locate(); + let data = Some(ActionData::NumericValue(25.0)); + h.event(Event::AccessKitActionRequest(ActionRequest { target_node, target_tree, action: Action::SetValue, data })); + h.run_steps(1); + assert!(near(hsb(&fill(h.state())), [last[0], last[1], 0.25], 0.01), "{last:?} → {:?}", hsb(&fill(h.state()))); +} + +/// With None, a screen reader's set-value action or an increment at the top of the strip sets the +/// fill, even when the number equals the last solid color's. +#[test] +fn with_a_none_fill_the_strip_applies_an_action_that_leaves_its_number() { + let mut app = app(json!("#ff0000"), "brightness"); + app.run("paint.setFill", json!({"none": true})).unwrap(); + let mut h = harness(app); + let last = hsb(&h.state().session.last_solid); + assert!((last[2] - 1.0).abs() < 0.01, "{last:?}"); + for (action, data) in [(Action::SetValue, Some(ActionData::NumericValue(100.0))), (Action::Increment, None)] { + h.state_mut().run("paint.setFill", json!({"none": true})).unwrap(); + h.run_steps(1); + let (target_node, target_tree) = h.get_by_label("Brightness").accesskit_node().locate(); + h.event(Event::AccessKitActionRequest(ActionRequest { target_node, target_tree, action, data })); + h.run_steps(1); + let paint = crate::panels::current_paints(h.state()).0; + let c = paint.color().unwrap_or_else(|| panic!("{action:?} left the fill as {paint:?}")); + assert!(near(hsb(&c), last, 0.01), "{action:?}: {last:?} → {:?}", hsb(&c)); + } +} + +/// `ui.colorWheel` answers every junk parameter without a panic. +#[test] +fn ui_color_wheel_answers_junk_params_without_a_panic() { + let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == "ui.colorWheel").expect("registered").3; + let mut app = app(json!("#336699"), "hue"); + for p in vectorcraft_testkit::strategies::junk_params(doc, "/nonexistent").into_iter().chain(vectorcraft_testkit::strategies::junk_values()) { + let _ = app.run("ui.colorWheel", p); + } +} + +/// The settings survive a JSON round trip of the preferences, and a saved value this build does +/// not know reads as the key's default without losing the other preferences. +#[test] +fn the_settings_are_kept_and_read_leniently() { + let ui = crate::UiState { color_wheel: Settings { view: View::Box, channel: Channel::Blue }, color_rgb_percent: true, ..Default::default() }; + let saved = serde_json::to_value(&ui).unwrap(); + let back: crate::UiState = serde_json::from_value(saved.clone()).unwrap(); + assert_eq!(back.color_wheel, ui.color_wheel); + let mut odd = saved.clone(); + odd["color_wheel"] = json!({"view": "triangle", "channel": 7, "later": true}); + let back: crate::UiState = serde_json::from_value(odd).unwrap(); + assert_eq!(back.color_wheel, Settings::default()); + assert!(back.color_rgb_percent, "the other preferences are kept"); + // Each key reads on its own: an unknown channel does not reset a known view, or the reverse. + let mut odd = saved.clone(); + odd["color_wheel"] = json!({"view": "box", "channel": 7}); + let back: crate::UiState = serde_json::from_value(odd).unwrap(); + assert_eq!(back.color_wheel, Settings { view: View::Box, channel: Channel::default() }); + let mut odd = saved.clone(); + odd["color_wheel"] = json!({"view": "triangle", "channel": "blue"}); + let back: crate::UiState = serde_json::from_value(odd).unwrap(); + assert_eq!(back.color_wheel, Settings { view: View::Wheel, channel: Channel::Blue }); + let mut odd = saved; + odd["color_wheel"] = json!("box"); + let back: crate::UiState = serde_json::from_value(odd).unwrap(); + assert_eq!(back.color_wheel, Settings::default()); + assert!(back.color_rgb_percent); +} + +/// The panel menu lists Wheel View and Box View with the shown one checked, and Box Channel; its +/// items set the view and the channel. +#[test] +fn the_panel_menu_switches_the_view_and_the_channel() { + let mut app = app(json!("#ff0000"), "hue"); + app.run("ui.colorWheel", json!({"view": "wheel"})).unwrap(); + let mut fonts = false; + let mut h = Harness::builder().with_size(vec2(260.0, 320.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + // The fonts, which draw the check mark, take effect from the next frame. + if !fonts { + crate::theme::install_fonts(ui.ctx()); + fonts = true; + return; + } + assert!(super::panel_menu_items(app, ui, super::color_wheel::ID)); + }, + app, + ); + h.run_steps(3); + assert!(h.query_by_label("✓ Wheel View").is_some()); + h.get_by_label(" Box View").click(); + h.run_steps(2); + assert_eq!(h.state().ui.color_wheel.view, View::Box); + assert!(h.query_by_label("✓ Box View").is_some()); +} + +/// Every channel's box puts each color back where it reads it, and the strip's value is the +/// channel's own component. +#[test] +fn box_pick_inverts_box_pos_for_every_channel() { + for ch in Channel::ALL { + for hsb in [[30.0, 0.6, 0.8], [200.0, 0.25, 0.5], [300.0, 1.0, 1.0]] { + let (z, x, y) = box_pos(ch, hsb); + let back = box_pick(ch, z, x, y, [0.0, 0.0, 0.0]); + assert!(near(back, hsb, 1e-3), "{ch:?}: {hsb:?} → {back:?}"); + } + } + // A gray picked in an RGB channel keeps the hue it had. + assert_eq!(box_pick(Channel::Red, 0.5, 0.5, 0.5, [120.0, 0.3, 0.3])[0], 120.0); +} + +/// The Color Picker's channel slider is the same widget as the strip: after a click on it, ↑ raises +/// its channel by one unit. +#[test] +fn the_color_pickers_channel_slider_takes_the_arrow_keys() { + let mut app = app(json!([0.6, 0.3, 0.3]), "hue"); + app.run("ui.colorPicker", json!({})).unwrap(); + let mut fonts = false; + let mut h = Harness::builder().with_size(vec2(1000.0, 800.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + // The fonts take effect from the next frame. + if !fonts { + crate::theme::install_fonts(ui.ctx()); + fonts = true; + return; + } + crate::dialogs::show(app, ui.ctx()); + }, + app, + ); + h.run_steps(3); + // The H field beside the values has the same name; the slider is the tall one. + let rail = h.get_all_by_label("H").map(|n| n.rect()).find(|r| r.height() > 100.0).expect("the channel slider"); + click(&mut h, rail.center()); + let picked = |h: &Harness<'static, VectorcraftApp>| -> [f32; 3] { + serde_json::from_value(h.state().ui.dialog.as_ref().unwrap().fields["__hsb"].clone()).unwrap() + }; + let before = picked(&h); + key(&mut h, egui::Key::ArrowUp); + let after = picked(&h); + assert!((after[0] - (before[0].round() + 1.0)).abs() < 1e-3, "{before:?} → {after:?}"); + assert!(near([0.0, after[1], after[2]], [0.0, before[1], before[2]], 1e-4), "{before:?} → {after:?}"); + let slider = h.get_all_by_label("H").find(|n| n.rect().height() > 100.0).expect("the channel slider"); + let node = slider.accesskit_node(); + assert!([Action::Increment, Action::Decrement, Action::SetValue].iter().all(|a| node.data().supports_action(*a))); +} diff --git a/crates/ui-egui/src/panels/tests_links.rs b/crates/ui-egui/src/panels/tests_links.rs index 781c4f5840..1d38e6eb9b 100644 --- a/crates/ui-egui/src/panels/tests_links.rs +++ b/crates/ui-egui/src/panels/tests_links.rs @@ -136,6 +136,36 @@ fn the_panel_lists_the_images_with_link_info_for_the_selected_one() { } } +/// A frame that fetches nothing keeps the stored rows and Link Info as they are, without a copy; the +/// two-second recheck, another first selected image and an edit each store a new cache. +#[test] +fn frames_that_fetch_nothing_reuse_the_cached_rows() { + let dir = Folder::new("cache"); + let (mut app, linked, _) = app(&dir); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let frame = |app: &mut VectorcraftApp, time: f64| { + let raw = egui::RawInput { time: Some(time), ..Default::default() }; + let text: Vec = super::tests_appearance::frame_raw(&ctx, app, raw, super::links::show).into_iter().map(|(t, _)| t).collect(); + (super::pstate::>(&ctx, "links-cache"), text) + }; + let (first, text) = frame(&mut app, 1.0); + assert!(text.iter().any(|t| t == "linked.png") && text.iter().any(|t| t == "40 × 20 px"), "{text:?}"); + let (same, text) = frame(&mut app, 1.5); + assert!(std::sync::Arc::ptr_eq(&first, &same), "a frame that fetches nothing stores no new cache"); + assert!(text.iter().any(|t| t == "linked.png") && text.iter().any(|t| t == "40 × 20 px"), "{text:?}"); + let (rechecked, _) = frame(&mut app, 3.6); + assert!(!std::sync::Arc::ptr_eq(&same, &rechecked), "the files are looked at again after two seconds"); + app.run("select.set", json!({"ids": [linked]})).unwrap(); + let (picked, text) = frame(&mut app, 3.7); + assert!(!std::sync::Arc::ptr_eq(&rechecked, &picked), "Link Info follows the first selected image"); + assert!(text.iter().any(|t| t == "300 × 200 px"), "{text:?}"); + app.run("edit.clear", json!({"ids": [linked]})).unwrap(); + let (edited, text) = frame(&mut app, 3.8); + assert!(!std::sync::Arc::ptr_eq(&picked, &edited), "an edit lists the rows again"); + assert!(!text.iter().any(|t| t == "linked.png") && text.iter().any(|t| t == "embedded.png"), "{text:?}"); +} + /// Copy Info copies the file names of the selected links, or of `ids` in the order given, one per /// line; it is off with nothing selected, and a bad `ids` leaves the clipboard as it was. #[test] @@ -500,6 +530,36 @@ fn properties_shows_the_selected_image_and_its_link_actions() { assert!(text.contains("Linked File") && text.contains("Edit Original") && text.contains("Embed"), "{text}"); } +/// Unembed… acts on several selected embedded images: it asks for one folder, writes a file for +/// each image there and links each one to its file; with no folder picked, nothing changes. +#[test] +fn unembed_writes_several_images_to_one_picked_folder() { + let dir = Folder::new("unembed-several"); + let (mut app, _, embedded) = app(&dir); + let c = dir.file("other.png", &png(30, 10)); + let other = app.run("file.place", json!({"path": c, "at": [50, 50], "link": false})).unwrap()["ids"][0].as_u64().unwrap(); + assert!(super::links::can_unembed(&app, 1)); + assert!(!super::links::can_unembed(&app, 0)); + assert!(!super::links::can_unembed(&app, 2), "no folder to pick"); + let out = dir.0.join("out"); + std::fs::create_dir_all(&out).unwrap(); + // No folder picked: nothing written or linked. + app.services.pick_folder = Some(Box::new(|| None)); + assert!(super::links::can_unembed(&app, 2)); + super::links::unembed_several(&mut app, vec![embedded, other]); + assert_eq!(std::fs::read_dir(&out).unwrap().count(), 0); + assert_eq!(app.run("links.info", json!({"id": embedded})).unwrap()["status"], "embedded"); + let picked = out.to_string_lossy().into_owned(); + let answer = picked.clone(); + app.services.pick_folder = Some(Box::new(move || Some(answer.clone()))); + super::links::unembed_several(&mut app, vec![embedded, other]); + for (id, name) in [(embedded, "embedded.png"), (other, "other.png")] { + let info = app.run("links.info", json!({"id": id})).unwrap(); + assert_eq!(info["path"], out.join(name).to_string_lossy().as_ref(), "{info}"); + } + assert_eq!(app.ui.status, format!("Unembedded 2 images to {picked}")); +} + #[test] fn the_links_menu_items_run_commands() { let tree = crate::menus::menu_tree(); diff --git a/crates/ui-egui/src/panels/tests_strokedepth.rs b/crates/ui-egui/src/panels/tests_strokedepth.rs index 1d80cc1c66..c4f2a9fff4 100644 --- a/crates/ui-egui/src/panels/tests_strokedepth.rs +++ b/crates/ui-egui/src/panels/tests_strokedepth.rs @@ -1,5 +1,6 @@ //! Headless frames of the Stroke panel's width profile library: the ≡ menu's Add to Profiles…, -//! Delete Profile and Reset Profiles, and the Profile dropdown listing saved profiles. +//! Delete Profile and Reset Profiles, and the Profile dropdown listing saved profiles and dimmed +//! while the strokes draw with a brush. use serde_json::json; use vectorcraft_doc::WidthProfile; @@ -88,6 +89,206 @@ fn dropdown_lists_saved_profiles_and_applies_them() { assert_eq!(profile_points(&app), Some(custom().points)); } +/// The Stroke panel's Profile dropdown button, right of the "Profile:" label. +fn profile_button(ctx: &egui::Context, app: &mut VectorcraftApp) -> egui::Pos2 { + let t = frame_events(ctx, app, vec![], stroke::show); + let label = text_rect(&t, "Profile:"); + egui::pos2(label.right() + ctx.global_style().spacing.item_spacing.x + 50.0, label.center().y) +} + +/// Is the Profile dropdown dimmed for the stroke the panels show? +fn dimmed(ctx: &egui::Context, app: &VectorcraftApp) -> bool { + stroke::brush_keeps_size(app, ctx, current_stroke(app).as_ref()).is_some() +} + +/// The rows the Profile dropdown lists after a click on it. +fn listed(ctx: &egui::Context, app: &mut VectorcraftApp) -> Vec<&'static str> { + let button = profile_button(ctx, app); + click(ctx, app, button, stroke::show); + let t = frame_events(ctx, app, vec![], stroke::show); + let out = WidthProfile::PRESETS.iter().map(|p| p.label).filter(|l| t.iter().any(|(s, _)| s == l)).collect(); + // Close the list. + let escape = egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + frame_events(ctx, app, vec![escape], stroke::show); + out +} + +/// A stroke drawn with a brush (here the 3 pt. Round calligraphic brush) keeps the brush's size, +/// so a width profile does not change it: the Profile dropdown is dimmed, opens no list on a +/// uniform stroke, and lists only Uniform on a stroke that has a profile (which resets it). +/// Without the brush, the full list comes back. +#[test] +fn dropdown_is_dimmed_while_the_brush_keeps_its_size() { + let ctx = egui::Context::default(); + let mut app = app_with_line(); + let id = app.session.active().unwrap().selection.objects[0].0; + run(&mut app, "brush.apply", json!({"ids": [id], "name": "3 pt. Round"})); + assert!(dimmed(&ctx, &app)); + assert_eq!(listed(&ctx, &mut app), Vec::<&str>::new(), "no list on a uniform stroke"); + + set_profile(&mut app, custom()); + assert_eq!(listed(&ctx, &mut app), ["Uniform"]); + let button = profile_button(&ctx, &mut app); + click(&ctx, &mut app, button, stroke::show); + let t = frame_events(&ctx, &mut app, vec![], stroke::show); + click(&ctx, &mut app, text_rect(&t, "Uniform").center(), stroke::show); + assert_eq!(profile_points(&app), None, "Uniform resets the profile"); + + run(&mut app, "brush.remove", json!({"ids": [id]})); + assert!(!dimmed(&ctx, &app)); + assert_eq!(listed(&ctx, &mut app).len(), WidthProfile::PRESETS.len()); +} + +/// With an Appearance panel stroke row active, the dropdown follows that row: a brushed row below +/// a plain top stroke dims it, and the plain row does not. +#[test] +fn the_active_stroke_row_decides_whether_the_dropdown_is_dimmed() { + let ctx = egui::Context::default(); + let mut app = app_with_line(); + let id = app.session.active().unwrap().selection.objects[0].0; + run(&mut app, "brush.apply", json!({"ids": [id], "name": "3 pt. Round"})); + run(&mut app, "appearance.addStroke", json!({})); + let items = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.items.clone(); + let rows: Vec<(usize, bool)> = items + .iter() + .enumerate() + .filter_map(|(i, it)| if let vectorcraft_doc::AppearanceItem::Stroke(s) = it { Some((i, s.brush.is_some())) } else { None }) + .collect(); + let [(lower, true), (top, false)] = rows[..] else { panic!("{rows:?}") }; + assert!(!dimmed(&ctx, &app), "the top stroke has no brush"); + run(&mut app, "appearance.setActiveItem", json!({"index": lower})); + assert!(dimmed(&ctx, &app)); + assert_eq!(listed(&ctx, &mut app), Vec::<&str>::new()); + run(&mut app, "appearance.setActiveItem", json!({"index": top})); + assert!(!dimmed(&ctx, &app)); +} + +/// A selected group with a brushed stroke of its own dims the dropdown, though the panel shows its +/// first member's plain stroke: the list edits the group's stroke. +#[test] +fn a_groups_own_brushed_stroke_dims_the_dropdown() { + let ctx = egui::Context::default(); + let mut app = app_with_line(); + let a = app.session.active().unwrap().selection.objects[0].0; + run(&mut app, "shape.line", json!({"x1": 10, "y1": 150, "x2": 150, "y2": 150})); + let b = app.session.active().unwrap().selection.objects[0].0; + let g = run(&mut app, "object.group", json!({"ids": [a, b]}))["id"].as_u64().unwrap(); + run(&mut app, "appearance.addStroke", json!({"ids": [g]})); + app.session + .edit("Brush", |d, _| { + d.node_mut(vectorcraft_doc::NodeId(g)).unwrap().appearance.stroke_mut().unwrap().brush = Some("3 pt. Round".into()); + Ok(()) + }) + .unwrap(); + run(&mut app, "select.set", json!({"ids": [g]})); + assert!(current_stroke(&app).is_some_and(|s| s.brush.is_none()), "the panel shows a member's plain stroke"); + assert!(dimmed(&ctx, &app)); + assert_eq!(listed(&ctx, &mut app), Vec::<&str>::new()); +} + +/// A selection change with no edit between decides whether the dropdown is dimmed: from a brushed +/// line to a plain one and back. +#[test] +fn selecting_another_object_without_an_edit_updates_the_dimming() { + let ctx = egui::Context::default(); + let mut app = app_with_line(); + let a = app.session.active().unwrap().selection.objects[0].0; + run(&mut app, "shape.line", json!({"x1": 10, "y1": 150, "x2": 150, "y2": 150})); + let b = app.session.active().unwrap().selection.objects[0].0; + run(&mut app, "brush.apply", json!({"ids": [a], "name": "3 pt. Round"})); + run(&mut app, "select.set", json!({"ids": [a]})); + assert!(dimmed(&ctx, &app)); + run(&mut app, "select.set", json!({"ids": [b]})); + assert!(!dimmed(&ctx, &app), "the plain line follows a profile"); + run(&mut app, "select.set", json!({"ids": [a]})); + assert!(dimmed(&ctx, &app)); +} + +/// The Flip Along and Flip Across buttons beside a dimmed dropdown do not flip a brushed stroke's +/// profile, which does not change what the stroke draws. +#[test] +fn flip_buttons_leave_a_brushed_strokes_profile_alone() { + let ctx = egui::Context::default(); + let mut app = app_with_line(); + set_profile(&mut app, custom()); + let spacing = ctx.global_style().spacing.item_spacing.x; + // The dropdown is 100 pt wide and the Flip Along button, 22 pt wide, follows it. + let flip = |ctx: &egui::Context, app: &mut VectorcraftApp| { + let button = profile_button(ctx, app); + let at = egui::pos2(button.x + stroke::PROFILE_DROPDOWN_WIDTH / 2.0 + spacing + 11.0, button.y); + click(ctx, app, at, stroke::show); + }; + flip(&ctx, &mut app); + let flipped = profile_points(&app); + assert_ne!(flipped, Some(custom().points), "Flip Along flips a plain stroke's profile"); + let id = app.session.active().unwrap().selection.objects[0].0; + run(&mut app, "brush.apply", json!({"ids": [id], "name": "3 pt. Round"})); + assert!(dimmed(&ctx, &app)); + let before = profile_points(&app); + assert!(before.is_some()); + flip(&ctx, &mut app); + assert_eq!(profile_points(&app), before, "the buttons are off on a brushed stroke"); +} + +/// With several objects selected, the dropdown is dimmed only while every one of their strokes +/// draws with a brush: a profile still changes the strokes without one. A brush name the +/// document's brushes lack draws a plain stroke, which follows the profile. +#[test] +fn mixed_selection_dims_the_dropdown_only_when_every_stroke_has_a_brush() { + let ctx = egui::Context::default(); + let mut app = app_with_line(); + let a = app.session.active().unwrap().selection.objects[0].0; + run(&mut app, "shape.line", json!({"x1": 10, "y1": 150, "x2": 150, "y2": 150})); + let b = app.session.active().unwrap().selection.objects[0].0; + run(&mut app, "brush.apply", json!({"ids": [a], "name": "3 pt. Round"})); + // The first selected object is the brushed one, whose stroke the panel shows. + run(&mut app, "select.set", json!({"ids": [a, b]})); + assert!(current_stroke(&app).and_then(|s| s.brush).is_some()); + assert!(!dimmed(&ctx, &app)); + assert_eq!(listed(&ctx, &mut app).len(), WidthProfile::PRESETS.len()); + + run(&mut app, "brush.apply", json!({"ids": [b], "name": "3 pt. Round"})); + run(&mut app, "select.set", json!({"ids": [a, b]})); + assert!(dimmed(&ctx, &app)); + assert_eq!(listed(&ctx, &mut app), Vec::<&str>::new()); + + // The shown stroke is uniform and the other has a profile: Uniform still removes it. + let edit = |app: &mut VectorcraftApp, f: &dyn Fn(&mut vectorcraft_doc::Appearance)| { + app.session + .edit("Edit", |d, _| { + f(&mut d.node_mut(vectorcraft_doc::NodeId(b)).unwrap().appearance); + Ok(()) + }) + .unwrap(); + }; + edit(&mut app, &|ap| ap.stroke_mut().unwrap().profile = Some(custom())); + assert_eq!(current_stroke(&app).and_then(|s| s.profile), None); + assert_eq!(listed(&ctx, &mut app), ["Uniform"]); + let button = profile_button(&ctx, &mut app); + click(&ctx, &mut app, button, stroke::show); + let t = frame_events(&ctx, &mut app, vec![], stroke::show); + click(&ctx, &mut app, text_rect(&t, "Uniform").center(), stroke::show); + let node = |app: &VectorcraftApp| app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(b)).unwrap().clone(); + assert_eq!(node(&app).appearance.stroke().unwrap().profile, None, "Uniform reset the other stroke"); + + edit(&mut app, &|ap| ap.stroke_mut().unwrap().brush = Some("No Such Brush".into())); + assert!(!dimmed(&ctx, &app)); + + // An object without a stroke item takes a plain stroke from a profile. + edit(&mut app, &|ap| ap.items.retain(|i| !matches!(i, vectorcraft_doc::AppearanceItem::Stroke(_)))); + assert!(node(&app).appearance.stroke().is_none()); + assert!(!dimmed(&ctx, &app)); + assert_eq!(listed(&ctx, &mut app).len(), WidthProfile::PRESETS.len()); +} + +/// The dimmed dropdown's hover text is the Width tool's status message, word for word, so the two +/// share their catalog rows. +#[test] +fn the_hover_text_is_the_width_tools_status_message() { + let literal = format!("tl!(\"{}\")", vectorcraft_tools::distort::KEEPS_SIZE); + assert!(include_str!("stroke.rs").contains(&literal), "panels/stroke.rs has no {literal}"); +} + #[test] fn every_arrowhead_preview_draws_its_head() { use vectorcraft_doc::Arrowhead; diff --git a/crates/ui-egui/src/panels/tests_three_d.rs b/crates/ui-egui/src/panels/tests_three_d.rs index 5ff986af13..1226b292d7 100644 --- a/crates/ui-egui/src/panels/tests_three_d.rs +++ b/crates/ui-egui/src/panels/tests_three_d.rs @@ -1259,6 +1259,180 @@ fn export_3d_object_leaves_out_a_group_with_a_3d_fill() { assert_eq!(list.iter().map(|a| a["nodes"].clone()).collect::>(), [json!([a])]); } +/// Whether Export 3D Object is available as the panel reads it ([`super::can_export_3d_shown`]), +/// checked against the state worked out from scratch ([`super::can_export_3d`]); with a document +/// open, the panel keeps it for the document's uid and revision. +fn exportable(app: &mut VectorcraftApp, why: &str) -> bool { + let fresh = super::can_export_3d(app); + assert_eq!(super::can_export_3d_shown(app), fresh, "{why}"); + if let Some(key) = app.session.active().map(|st| (st.uid, st.revision)) { + assert_eq!(app.canvas.three_d_exportable, Some((key, fresh)), "{why}"); + } + fresh +} + +/// The Export 3D Object state the panel keeps for a revision equals the state worked out from +/// scratch: with no document and no selection, for plain paths, with a 3D object selected first or +/// last, for a path of a compound path whose compound path has the effect, after the effect is +/// hidden, Undo and Redo, in another document and back, and for a group whose 3D effect moves onto +/// its fill. +#[test] +fn export_3d_object_state_kept_for_a_revision_equals_a_fresh_one() { + let mut app = VectorcraftApp::new(Session::new(), Services::default()); + assert!(!exportable(&mut app, "no document")); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + assert!(!exportable(&mut app, "no selection")); + let rect = |app: &mut VectorcraftApp, x: f64| { + app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap() + }; + let (p, q) = (rect(&mut app, 10.0), rect(&mut app, 40.0)); + app.run("select.set", json!({"ids": [p, q]})).unwrap(); + assert!(!exportable(&mut app, "plain paths")); + let solid = rect(&mut app, 70.0); + app.run("effect.apply", json!({"effect": "threeD.extrude", "item": null})).unwrap(); + app.run("select.set", json!({"ids": [solid, p, q]})).unwrap(); + assert!(exportable(&mut app, "a 3D object first")); + app.run("select.set", json!({"ids": [p, q]})).unwrap(); + assert!(!exportable(&mut app, "plain paths again")); + app.run("select.set", json!({"ids": [p, q, solid]})).unwrap(); + assert!(exportable(&mut app, "a 3D object last")); + let (a, b) = (rect(&mut app, 100.0), rect(&mut app, 110.0)); + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + app.run("object.compoundPath.make", json!({})).unwrap(); + let compound = app.session.active().unwrap().selection.objects[0].0; + app.run("effect.apply", json!({"effect": "threeD.extrude", "item": null})).unwrap(); + let member = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(compound)).unwrap().children().unwrap()[0].id.0; + app.run("select.set", json!({"ids": [p, q]})).unwrap(); + assert!(!exportable(&mut app, "plain paths before the compound path's member")); + app.run("select.set", json!({"ids": [p, member]})).unwrap(); + assert!(exportable(&mut app, "a path of a 3D compound path")); + // An edit that leaves the selection as it is. + app.run("effect.setParams", json!({"ids": [compound], "index": 0, "item": null, "visible": false})).unwrap(); + assert!(!exportable(&mut app, "the compound path's 3D effect hidden")); + app.run("edit.undo", json!({})).unwrap(); + assert!(exportable(&mut app, "Undo")); + app.run("edit.redo", json!({})).unwrap(); + assert!(!exportable(&mut app, "Redo")); + app.run("edit.undo", json!({})).unwrap(); + assert!(exportable(&mut app, "Undo again")); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + assert!(!exportable(&mut app, "a new document")); + app.session.set_active(0); + assert!(exportable(&mut app, "back to the first document")); + // A group's own 3D effect exports; the same effect on its fill does not. + app.run("select.set", json!({"ids": [p, q]})).unwrap(); + let group = app.run("object.group", json!({})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [group]})).unwrap(); + app.run("appearance.addFill", json!({})).unwrap(); + app.run("effect.apply", json!({"effect": "threeD.extrude"})).unwrap(); + assert!(exportable(&mut app, "a group with its own 3D effect")); + app.session + .edit("fill", |d, _| { + let n = d.node_mut(vectorcraft_doc::NodeId(group)).unwrap(); + let fx = n.appearance.effects.remove(0); + n.appearance.items[0].effects_mut().push(fx); + Ok(()) + }) + .unwrap(); + assert!(!exportable(&mut app, "a group with a 3D effect on its fill")); +} + +/// A frame of the panel works out the Export 3D Object state once and keeps it for the document's +/// revision: later frames read it, and a new revision works it out again. +#[test] +fn export_3d_object_state_is_worked_out_once_per_revision() { + let key = |app: &VectorcraftApp| app.session.active().map(|st| (st.uid, st.revision)).unwrap(); + let mut app = app(); + painted_text(&mut app, show); + assert_eq!(app.canvas.three_d_exportable, Some((key(&app), false))); + // A wrong answer planted for this revision is what the panel reads: nothing works it out again. + app.canvas.three_d_exportable = Some((key(&app), true)); + assert!(super::can_export_3d_shown(&mut app)); + painted_text(&mut app, show); + assert_eq!(app.canvas.three_d_exportable, Some((key(&app), true))); + app.run("select.none", json!({})).unwrap(); + painted_text(&mut app, show); + assert_eq!(app.canvas.three_d_exportable, Some((key(&app), false))); +} + +/// The thread's CPU time in nanoseconds, where Linux gives it. +fn thread_cpu_ns() -> Option { + std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok() +} + +/// Time the Export 3D Object state with 200,000 selected paths: worked out from scratch on every +/// frame ([`super::can_export_3d`]), by [`super::can_export_3d_shown`] on the first frame of a +/// revision, and by [`super::can_export_3d_shown`] on later frames of the same revision. The first +/// case selects plain paths alone; the second adds a path of a compound path with Extrude & Bevel, +/// selected last. The sides alternate, and the median time per frame of 7 runs is printed. +/// Run with `cargo test --release -p vectorcraft-ui-egui --lib export_3d_object_state_timing -- --ignored --nocapture`. +#[test] +#[ignore = "manual timing probe; performance depends on machine load"] +fn export_3d_object_state_timing() { + const PATHS: usize = 200_000; + const MEASURES: u32 = 20; + const KEPT: u32 = 1_000_000; + let mut app = VectorcraftApp::new(Session::new(), Services::default()); + app.run("file.new", json!({"width": 2000, "height": 2000})).unwrap(); + let rect = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + let rect = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(rect)).cloned().unwrap(); + app.session + .edit("Fill", |d, _| { + let layer = d.layers[0].id; + for _ in 0..PATHS - 1 { + let mut n = rect.clone(); + n.id = d.alloc_id(); + d.insert(Some(layer), usize::MAX, n)?; + } + Ok(()) + }) + .unwrap(); + app.run("select.all", json!({})).unwrap(); + let plain: Vec = app.session.active().unwrap().selection.objects.iter().map(|id| id.0).collect(); + let a = app.run("shape.rectangle", json!({"x": 0, "y": 1000, "width": 30, "height": 30})).unwrap()["id"].clone(); + let b = app.run("shape.rectangle", json!({"x": 5, "y": 1005, "width": 10, "height": 10})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + app.run("object.compoundPath.make", json!({})).unwrap(); + let compound = app.session.active().unwrap().selection.objects[0]; + app.run("effect.apply", json!({"effect": "threeD.extrude", "item": null})).unwrap(); + let member = app.session.active().unwrap().doc.node(compound).unwrap().children().unwrap()[0].id.0; + let mut last = plain.clone(); + last.push(member); + let median = |v: &mut Vec| { + v.sort_by(f64::total_cmp); + v[v.len() / 2] + }; + let clock = if thread_cpu_ns().is_some() { "thread CPU time" } else { "wall-clock time" }; + for (name, ids, expected) in [("plain paths", plain, false), ("plain paths, then a path of a 3D compound path", last, true)] { + app.run("select.set", json!({"ids": &ids})).unwrap(); + let selected: Vec = app.session.active().unwrap().selection.objects.iter().map(|id| id.0).collect(); + assert_eq!(selected.len(), ids.len(), "{name}"); + assert_eq!(selected.last(), ids.last(), "{name}"); + assert_eq!(super::can_export_3d(&app), expected, "{name}"); + let mut time = |frames: u32, f: &mut dyn FnMut(&mut VectorcraftApp) -> bool| { + let (cpu, wall) = (thread_cpu_ns(), std::time::Instant::now()); + for _ in 0..frames { + assert_eq!(f(&mut app), expected); + } + let ns = thread_cpu_ns().zip(cpu).map_or_else(|| wall.elapsed().as_nanos(), |(b, a)| b - a); + ns as f64 / f64::from(frames) / 1000.0 + }; + let (mut full, mut first, mut kept) = (vec![], vec![], vec![]); + for _ in 0..7 { + full.push(time(MEASURES, &mut |app| super::can_export_3d(app))); + first.push(time(MEASURES, &mut |app| { + app.canvas.three_d_exportable = None; + super::can_export_3d_shown(app) + })); + kept.push(time(KEPT, &mut super::can_export_3d_shown)); + } + eprintln!("{name}: {} objects selected, available: {expected}; {clock} per frame, median of 7 runs", selected.len()); + eprintln!("every frame worked out ({MEASURES} frames a run): {:>12.3} us {full:.3?}", median(&mut full)); + eprintln!("first frame of a revision ({MEASURES} a run): {:>12.3} us {first:.3?}", median(&mut first)); + eprintln!("later frames ({KEPT} frames a run): {:>12.4} us {kept:.4?}", median(&mut kept)); + } +} + #[test] fn changed_settings_lists_only_new_values() { let before = json!({"depth": 50.0, "cap": true, "bevel": "none"}); diff --git a/crates/ui-egui/src/panels/three_d.rs b/crates/ui-egui/src/panels/three_d.rs index be7731daf5..61993a8581 100644 --- a/crates/ui-egui/src/panels/three_d.rs +++ b/crates/ui-egui/src/panels/three_d.rs @@ -278,9 +278,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } /// The Export 3D Object button, available while a selected object has a 3D effect that -/// `assets.add3D` exports ([`can_export_3d`]). An error goes to the status bar. +/// `assets.add3D` exports ([`can_export_3d_shown`]). An error goes to the status bar. fn export_button(app: &mut VectorcraftApp, ui: &mut Ui, ctx: &egui::Context) { - let any = can_export_3d(app); + let any = can_export_3d_shown(app); ui.add_space(10.0); if ui.add_enabled(any, egui::Button::new(tl!("Export 3D Object"))).clicked() { finish(app, ctx); @@ -299,6 +299,22 @@ pub(crate) fn can_export_3d(app: &VectorcraftApp) -> bool { st.selection.objects.iter().any(|id| st.doc.node(compound(*id).unwrap_or(*id)).is_some_and(vectorcraft_effects::exports_three_d)) } +/// [`can_export_3d`], worked out once per (document uid, revision) +/// ([`crate::caches::CanvasCache::three_d_exportable`]): the panel reads it every frame, and Select +/// All can select hundreds of thousands of objects. +pub(crate) fn can_export_3d_shown(app: &mut VectorcraftApp) -> bool { + let Some(st) = app.session.active() else { return false }; + let key = (st.uid, st.revision); + if let Some((k, any)) = app.canvas.three_d_exportable + && k == key + { + return any; + } + let any = can_export_3d(app); + app.canvas.three_d_exportable = Some((key, any)); + any +} + /// Export 3D Object: adds the selected objects that have a 3D effect to Asset Export as 3D assets /// (`assets.add3D` on the selection, one undo step, none when each is an asset already), selects /// their assets there and shows the Asset Export panel. The command leaves out the selected diff --git a/crates/ui-egui/src/panels/transform.rs b/crates/ui-egui/src/panels/transform.rs index 1bce03c53d..936fdda1a6 100644 --- a/crates/ui-egui/src/panels/transform.rs +++ b/crates/ui-egui/src/panels/transform.rs @@ -126,7 +126,13 @@ const PATTERN_MODES: [(&str, &str); 3] = [("object", "Transform Object Only"), ( /// Only (the pattern tiles alone) or Transform Both. Until one is chosen (`default`, or any other /// value) neither is passed: patterns follow General › Transform Pattern Tiles. Errors are /// dropped, as the panels' fields have always done. -pub fn run_transform(app: &mut VectorcraftApp, cmd: &str, mut params: serde_json::Value) { +pub fn run_transform(app: &mut VectorcraftApp, cmd: &str, params: serde_json::Value) { + let params = with_pattern_switches(app, params); + app.run(cmd, params).ok(); +} + +/// `params` with the `objects` and `patterns` switches [`run_transform`] adds. +pub fn with_pattern_switches(app: &VectorcraftApp, mut params: serde_json::Value) -> serde_json::Value { let switches = match app.session.prefs.transform_panel_patterns.as_str() { "object" => Some((true, false)), "pattern" => Some((false, true)), @@ -137,7 +143,7 @@ pub fn run_transform(app: &mut VectorcraftApp, cmd: &str, mut params: serde_json params["objects"] = json!(objects); params["patterns"] = json!(patterns); } - app.run(cmd, params).ok(); + params } /// The panel menu's checked choice of [`PATTERN_MODES`]: the one chosen, else (`default`) what @@ -416,10 +422,11 @@ fn pixel_aligned_ids(app: &VectorcraftApp) -> Vec { app.session.active().map(|st| st.selection.objects.iter().filter(|id| st.doc.node(**id).is_some()).map(|id| id.0).collect()).unwrap_or_default() } -/// A live rectangle's, polygon's or ellipse's properties (Transform and Properties panels, and the -/// Contextual Task Bar), their widget ids under `id`. `headed` adds the Rectangle and Polygon -/// Properties headings; an ellipse's heading always shows. Returns false, drawing nothing, for -/// other live shapes. +/// A live rectangle's, polygon's, ellipse's or line's properties (Transform and Properties panels, +/// and for the first three the Contextual Task Bar), their widget ids under `id`. `headed` adds +/// the Rectangle and Polygon Properties headings; an ellipse's and a line's heading always show. +/// Returns false, drawing nothing, for other live shapes, and for a line unless every selected +/// object is one. pub(crate) fn live_shape_rows(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, live: &LiveShape, id: &str, headed: bool) -> bool { match live { LiveShape::Rectangle { .. } => { @@ -438,27 +445,89 @@ pub(crate) fn live_shape_rows(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, l widgets::subheader(ui, tl!("Ellipse Properties:")); pie_rows(app, ui, *pie, &format!("{id}-pie")); } + LiveShape::Line { .. } => return line_rows(app, ui, live, &format!("{id}-line")), _ => return false, } true } +/// Whether every selected object is a live line (and one is selected). +fn only_lines_selected(app: &VectorcraftApp) -> bool { + let Some(st) = app.session.active() else { return false }; + let line = |n: &Node| matches!(&n.kind, NodeKind::Path { live: Some(l), .. } if matches!(**l, LiveShape::Line { .. })); + !st.selection.objects.is_empty() && st.selection.objects.iter().all(|o| st.doc.node(*o).is_some_and(line)) +} + +/// A live line's Line Properties (Transform and Properties panels), under its heading: its length, +/// end to end, and its angle (counterclockwise from 3 o'clock, from its first end to its second). A new length keeps each selected line's first end in place, and a +/// new angle turns each one about its midpoint. Returns false, drawing nothing, unless every +/// selected object is a live line. +pub(crate) fn line_rows(app: &mut VectorcraftApp, ui: &mut Ui, live: &LiveShape, id: &str) -> bool { + if !only_lines_selected(app) { + return false; + } + let (units, fw) = (app.session.general_unit(), super::field_width(ui)); + widgets::subheader(ui, tl!("Line Properties:")); + // The `object.setLiveShape` params the edited fields set, all sent in one call. + let mut set = serde_json::Map::new(); + egui::Grid::new((id, "grid")).num_columns(2).spacing([6.0, 6.0]).show(ui, |ui| { + widgets::dim_label(ui, tl!("Line Length:")); + if let Some(l) = widgets::num_field_named(ui, (id, "length"), Some(tl!("Line Length:")), live.line_length(), units, fw) { + set.insert("lineLength".into(), json!(l)); + } + ui.end_row(); + widgets::dim_label(ui, tl!("Line Angle:")); + if let Some(a) = widgets::plain_field_named(ui, (id, "angle"), Some(tl!("Line Angle:")), live.line_angle().unwrap_or(0.0), "°", 1, fw) { + set.insert("lineAngle".into(), json!(a)); + } + ui.end_row(); + }); + if !set.is_empty() + && let Err(e) = app.run("object.setLiveShape", serde_json::Value::Object(set)) + { + app.status(e); + } + true +} + /// An ellipse's Pie Start and End Angle (degrees, counterclockwise from 3 o'clock; 0 to 360 is the -/// whole ellipse) and Invert Pie, which shows the other part of it (Transform and Properties panels). +/// whole ellipse), the Constrain Pie Angle link beside them, and Invert Pie, which shows the other +/// part of it (Transform and Properties panels). With the link on, a typed angle moves the other +/// one by as much, so each selected ellipse keeps its span. pub(crate) fn pie_rows(app: &mut VectorcraftApp, ui: &mut Ui, pie: (f64, f64), id: &str) { - for (label, key, v) in [(tl!("Pie Start Angle:"), "pieStart", pie.0), (tl!("Pie End Angle:"), "pieEnd", pie.1)] { - ui.horizontal(|ui| { - widgets::dim_label(ui, label); - if let Some(a) = widgets::plain_field(ui, (id, key), v, "°", 1, 60.0) { - app.run("object.setLiveShape", json!({ key: a })).ok(); + ui.horizontal(|ui| { + ui.vertical(|ui| { + for (label, key, v) in [(tl!("Pie Start Angle:"), "pieStart", pie.0), (tl!("Pie End Angle:"), "pieEnd", pie.1)] { + ui.horizontal(|ui| { + widgets::dim_label(ui, label); + if let Some(a) = widgets::plain_field(ui, (id, key), v, "°", 1, 60.0) { + let params = if app.ui.constrain_pie_angle { json!({ key: a, "constrainPie": true }) } else { json!({ key: a }) }; + app.run("object.setLiveShape", params).ok(); + } + }); } }); - } + pie_link(app, ui); + }); if widgets::flat_button(ui, tl!("Invert Pie"), 90.0).clicked() { app.run("object.setLiveShape", json!({"invertPie": true})).ok(); } } +/// The Constrain Pie Angle link between Pie Start and End Angle: one toggle for the Transform and +/// Properties panels, kept while the app runs and off at launch. It is drawn after the fields, so +/// Tab reaches them first; with the keyboard on it, Space or Enter toggles it. +fn pie_link(app: &mut VectorcraftApp, ui: &mut Ui) { + let (_, at) = ui.allocate_exact_size(egui::Vec2::splat(CONSTRAIN_LINK_SIZE), egui::Sense::click()); + let on = app.ui.constrain_pie_angle; + let tip = tl!("Constrain Pie Angle"); + let keyed = at.has_focus() + && ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Space) | i.consume_key(egui::Modifiers::NONE, egui::Key::Enter)); + if widgets::paint_icon_button(ui, at, if on { "link" } else { "link-2-off" }, tip, on).clicked() || keyed { + app.ui.constrain_pie_angle = !on; + } +} + /// A live polygon's Polygon Properties (Transform and Properties panels): its side count, angle /// (counterclockwise), corner type and radius, radius (centre to vertex) and side length, and Make /// Sides Equal, which an uneven scale enables. @@ -515,7 +584,13 @@ pub(crate) fn polygon_rows(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, live /// popover under it, as the Stroke link does with the Stroke panel. pub fn link(app: &mut VectorcraftApp, ui: &mut Ui) { let resp = ui.link(link_text(ui)).on_hover_text(tl!("Transform options")); - widgets::popover(&resp, resp.clicked(), |ui| { + popover(app, &resp); +} + +/// The Transform panel in a popover under `resp`, which a click on it toggles: the Control bar's +/// Transform [`link`], and its X:, Y:, W: and H: labels. +pub fn popover(app: &mut VectorcraftApp, resp: &egui::Response) { + widgets::popover(resp, resp.clicked(), |ui| { ui.set_width(300.0); show(app, ui); }); diff --git a/crates/ui-egui/src/panels/transform/tests.rs b/crates/ui-egui/src/panels/transform/tests.rs index 3dff8e6a4b..fe284bbe22 100644 --- a/crates/ui-egui/src/panels/transform/tests.rs +++ b/crates/ui-egui/src/panels/transform/tests.rs @@ -82,6 +82,35 @@ fn rotation_field_shows_the_angle_the_box_keeps() { assert!(shown.iter().any(|t| t == "0°") && !shown.iter().any(|t| t == "100 pt"), "{shown:?}"); } +/// Object › Transform › Rotate Bounding Box… asks for an angle and turns the box, not the art, in +/// one undo step: the panel then shows the box's angle. +#[test] +fn rotate_bounding_box_menu_item_turns_the_box_by_the_dialog_angle() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 100, "height": 50})).unwrap(); + let entry = crate::menus::menu_entries(&app) + .into_iter() + .find(|e| e.path == ["Object", "Transform"] && e.label == "Rotate Bounding Box…") + .expect("menu item"); + let (id, p) = crate::menus::click_target(&entry.label, entry.command.as_deref().unwrap(), &entry.params); + crate::menus::invoke(&mut app, &id, p); + let d = app.ui.dialog.as_mut().expect("a dialog opens"); + assert_eq!(d.str("__command"), "object.rotateBoundingBox"); + d.fields.insert("angle".into(), json!(90)); + let bounds = |app: &VectorcraftApp| { + let st = app.session.doc().unwrap(); + st.doc.bounds_of(&st.selection.objects, false) + }; + let art = bounds(&app); + let undo = app.session.doc().unwrap().history.undo.len(); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1); + assert_eq!(bounds(&app), art, "the art stays where it is"); + let shown = texts(&mut app, show); + assert!(shown.iter().any(|t| t == "90°"), "{shown:?}"); +} + /// #812: a selected live polygon shows its Polygon Properties in the Transform panel and the /// Properties panel's Transform section, and Make Sides Equal evens it out after a stretch. #[test] @@ -125,6 +154,113 @@ fn an_ellipse_shows_its_pie_properties() { assert!(shown.iter().any(|s| s == "30°") && shown.iter().any(|s| s == "120°"), "{shown:?}"); } +/// Ellipse Properties' Constrain Pie Angle link, in the Transform panel and the Properties panel's +/// Transform section: off at first, a click or Space with the keyboard on it toggles it, and while +/// it is on a typed Pie Start or End Angle moves the other angle by as much, keeping the span, in +/// one undo step. Off, each angle changes on its own. +#[test] +fn the_constrain_pie_angle_link_keeps_the_span() { + use egui_kittest::kittest::Queryable; + const LINK: &str = "Constrain Pie Angle"; + let pie = |app: &VectorcraftApp| match &first_selected(app).unwrap().kind { + NodeKind::Path { live: Some(l), .. } => match **l { + LiveShape::Ellipse { pie, .. } => pie, + ref k => panic!("{k:?}"), + }, + k => panic!("{k:?}"), + }; + let undo = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len(); + for draw in [show as fn(&mut VectorcraftApp, &mut Ui), crate::panels::properties::transform_section] { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("shape.ellipse", json!({"x": 50, "y": 50, "width": 120, "height": 80})).unwrap(); + app.run("object.setLiveShape", json!({"pieStart": 30, "pieEnd": 120})).unwrap(); + assert!(!app.ui.constrain_pie_angle, "off at first"); + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(320.0, 900.0)).with_accessibility_check(false).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !std::mem::replace(&mut fonts, true) { + crate::theme::install_fonts(ui.ctx()); + return; + } + draw(app, ui); + }, + app, + ); + h.run_steps(3); + h.get_by_role_and_label(egui::accesskit::Role::Button, LINK).click(); + h.run_steps(2); + assert!(h.state().ui.constrain_pie_angle, "a click turns it on"); + h.get_by_role_and_label(egui::accesskit::Role::Button, LINK).focus(); + h.run_steps(1); + h.key_press(egui::Key::Space); + h.run_steps(2); + assert!(!h.state().ui.constrain_pie_angle, "Space turns it off"); + h.get_by_role_and_label(egui::accesskit::Role::Button, LINK).click(); + h.run_steps(2); + assert!(h.state().ui.constrain_pie_angle); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let n = undo(h.state()); + type_into(&ctx, h.state_mut(), draw, "30°", "60"); + assert_eq!(pie(h.state()), (60.0, 150.0)); + assert_eq!(undo(h.state()), n + 1, "one undo step"); + type_into(&ctx, h.state_mut(), draw, "150°", "200"); + assert_eq!(pie(h.state()), (110.0, 200.0)); + h.get_by_role_and_label(egui::accesskit::Role::Button, LINK).click(); + h.run_steps(2); + assert!(!h.state().ui.constrain_pie_angle); + type_into(&ctx, h.state_mut(), draw, "110°", "100"); + assert_eq!(pie(h.state()), (100.0, 200.0), "off, the end stays"); + } +} + +/// A live line shows its Line Properties in the Transform panel and the Properties panel's +/// Transform section: a typed length keeps its first end in place and a typed angle turns it +/// about its midpoint, each one undo step. A line with other objects selected, and a line after +/// Expand Shape, show none. +#[test] +fn a_line_shows_and_takes_its_line_properties() { + let ends = |app: &VectorcraftApp| match &first_selected(app).unwrap().kind { + NodeKind::Path { live: Some(l), .. } => match **l { + LiveShape::Line { a, b } => (a, b), + ref k => panic!("{k:?}"), + }, + k => panic!("{k:?}"), + }; + let near = |p: Point, x: f64, y: f64| (p.x - x).abs() < 1e-6 && (p.y - y).abs() < 1e-6; + for draw in [show as fn(&mut VectorcraftApp, &mut Ui), crate::panels::properties::transform_section] { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + // 100 pt long, going down the page to the right: 53.13° clockwise, 306.87° counterclockwise. + let id = app.run("shape.line", json!({"x1": 50, "y1": 50, "x2": 110, "y2": 130})).unwrap()["id"].as_u64().unwrap(); + let shown = texts(&mut app, draw); + for t in ["Line Properties:", "Line Length:", "100 pt", "Line Angle:", "306.9°"] { + assert!(shown.iter().any(|s| s == t), "{t} in {shown:?}"); + } + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + type_into(&ctx, &mut app, draw, "100 pt", "50"); + let (a, b) = ends(&app); + assert!(near(a, 50.0, 50.0) && near(b, 80.0, 90.0), "{a:?} {b:?}"); + type_into(&ctx, &mut app, draw, "306.9°", "90"); + let (a, b) = ends(&app); + assert!(near(a, 65.0, 95.0) && near(b, 65.0, 45.0), "{a:?} {b:?}"); + assert!(texts(&mut app, draw).iter().any(|s| s == "90°")); + app.run("edit.undo", json!({})).unwrap(); + let (a, b) = ends(&app); + assert!(near(a, 50.0, 50.0) && near(b, 80.0, 90.0), "one undo step: {a:?} {b:?}"); + // With a rectangle selected too, the fields would set the line alone: they don't show. + let rect = app.run("shape.rectangle", json!({"x": 200, "y": 200, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [id, rect]})).unwrap(); + assert!(!texts(&mut app, draw).iter().any(|s| s == "Line Properties:" || s == "Line Length:")); + app.run("select.set", json!({"ids": [id]})).unwrap(); + assert!(texts(&mut app, draw).iter().any(|s| s == "Line Properties:")); + app.run("object.expandShape", json!({})).unwrap(); + assert!(!texts(&mut app, draw).iter().any(|s| s == "Line Properties:" || s == "Line Length:")); + } +} + #[test] fn the_artboard_tool_shows_the_active_artboard() { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); @@ -233,8 +369,9 @@ fn type_into(ctx: &egui::Context, app: &mut VectorcraftApp, draw: fn(&mut Vector } /// The panel menu's Transform Object Only, Transform Pattern Only and Transform Both, one -/// checked: a new X typed in the panel (or the Properties panel's Transform section) moves the -/// pattern-filled rectangle and leaves its tiles, moves its tiles alone, or moves both. Until +/// checked: a new X typed in the panel (or the Properties panel's Transform section, or the +/// Control bar) moves the pattern-filled rectangle and leaves its tiles, moves its tiles alone, or +/// moves both. Until /// one is chosen the panels do as General › Transform Pattern Tiles says, as they did before /// the menu acted, and the menu checks Transform Both while it is on, Transform Object Only /// while it is off; a choice overrides it, and resetting the preferences returns to it. @@ -248,7 +385,7 @@ fn the_menu_chooses_whether_the_object_its_pattern_or_both_transform() { let labels = ["Transform Object Only", "Transform Pattern Only", "Transform Both"]; let modes = ["object", "pattern", "both"]; let checked = |shown: &[String]| -> Vec { (0..3).filter(|i| shown.contains(&format!("✓ {}", labels[*i]))).collect() }; - for draw in [show as fn(&mut VectorcraftApp, &mut Ui), crate::panels::properties::transform_section] { + for draw in [show as fn(&mut VectorcraftApp, &mut Ui), crate::panels::properties::transform_section, crate::chrome::control_bar] { for general in [false, true] { for pick in [None, Some(0), Some(1), Some(2)] { let case = format!("General › Transform Pattern Tiles {general}, menu choice {pick:?}"); @@ -333,12 +470,12 @@ fn the_menu_choice_also_applies_to_rotation_and_shear() { } } -/// Use Registration Point for Symbol: with one symbol instance selected, the panel and the -/// Properties panel's Transform section show and set X and Y at its symbol's registration point -/// (here the top-left one) instead of the reference point (the centre). +/// Use Registration Point for Symbol: with one symbol instance selected, the panel, the +/// Properties panel's Transform section and the Control bar show and set X and Y at its symbol's +/// registration point (here the top-left one) instead of the reference point (the center). #[test] fn use_registration_point_for_symbol_measures_an_instance_from_its_registration_point() { - for draw in [show as fn(&mut VectorcraftApp, &mut Ui), crate::panels::properties::transform_section] { + for draw in [show as fn(&mut VectorcraftApp, &mut Ui), crate::panels::properties::transform_section, crate::chrome::control_bar] { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); app.run("shape.rectangle", json!({"x": 100, "y": 50, "width": 80, "height": 40})).unwrap(); @@ -366,6 +503,47 @@ fn use_registration_point_for_symbol_measures_an_instance_from_its_registration_ } } +/// The Control bar's X, Y, W and H use the reference point the Transform panel's locator chose: +/// X and Y show that point of the selection's box and a new X or Y moves it there, a new W or H +/// keeps it in place, and choosing another point changes what the fields show without editing the +/// art. Each field edit is one undo step. +#[test] +fn the_control_bar_fields_use_the_shared_reference_point() { + use crate::panels::tests_appearance::frame_events; + let draw = crate::chrome::control_bar as fn(&mut VectorcraftApp, &mut Ui); + // The reference point (top-left, center, bottom-right): X/Y shown for the rectangle at + // (10, 20), 100 × 50; the box after X becomes `x`, and after W becomes 200 and H 100. + let cases = [ + (0usize, ("10 pt", "20 pt"), "30", Rect::new(30.0, 20.0, 130.0, 70.0), Rect::new(30.0, 20.0, 230.0, 120.0)), + (4, ("60 pt", "45 pt"), "80", Rect::new(30.0, 20.0, 130.0, 70.0), Rect::new(-20.0, -5.0, 180.0, 95.0)), + (8, ("110 pt", "70 pt"), "130", Rect::new(30.0, 20.0, 130.0, 70.0), Rect::new(-70.0, -30.0, 130.0, 70.0)), + ]; + for (refi, (x, y), new_x, moved, sized) in cases { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 20, "width": 100, "height": 50})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let revision = |app: &VectorcraftApp| app.session.active().unwrap().revision; + let shown = |app: &mut VectorcraftApp| frame_events(&ctx, app, vec![], draw).into_iter().map(|(t, _)| t).collect::>(); + shown(&mut app); + let before = revision(&app); + ctx.data_mut(|d| d.insert_temp(egui::Id::unique("refpt"), refi)); + let texts = shown(&mut app); + assert!(texts.iter().any(|t| t == x) && texts.iter().any(|t| t == y), "reference {refi}: X {x}, Y {y} in {texts:?}"); + assert_eq!(revision(&app), before, "reference {refi}: choosing the point leaves the art"); + type_into(&ctx, &mut app, draw, x, new_x); + assert_eq!(app.selection_box().unwrap().rect, moved, "reference {refi}: X"); + assert_eq!(revision(&app), before + 1, "reference {refi}: one undo step"); + type_into(&ctx, &mut app, draw, "100 pt", "200"); + type_into(&ctx, &mut app, draw, "50 pt", "100"); + assert_eq!(app.selection_box().unwrap().rect, sized, "reference {refi}: W and H"); + app.run("edit.undo", json!({})).unwrap(); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.selection_box().unwrap().rect, moved, "reference {refi}: undo"); + } +} + /// Use Registration Point for Symbol on a reflected, a rotated and a sheared symbol instance: /// the panel and the Properties panel's Transform section show X and Y at the registration /// point where the instance's transform put it (not at the box's point of the same index), a diff --git a/crates/ui-egui/src/panels/transparency.rs b/crates/ui-egui/src/panels/transparency.rs index 4279ac11e4..e0cd492a2e 100644 --- a/crates/ui-egui/src/panels/transparency.rs +++ b/crates/ui-egui/src/panels/transparency.rs @@ -4,6 +4,8 @@ //! neutral → off) and Opacity & Mask Define Knockout Shape; the menu's Page Isolated Blending and //! Page Knockout Group. +use std::sync::Arc; + use egui::{Sense, Stroke, StrokeKind, Ui, vec2}; use serde_json::json; use vectorcraft_color::{BlendMode, Paint}; @@ -20,20 +22,21 @@ pub(super) const MASK_THUMB: &str = "tr-mask-thumb"; /// The panel's values ([`vectorcraft_engine::Session::transparency_info`]) and its first target /// (the selection, or the object whose mask is being edited), recomputed only when the document -/// or the selection changes, or other gradient mesh points are picked. -fn state(app: &VectorcraftApp, ctx: &egui::Context) -> (TransparencyInfo, Option) { +/// or the selection changes, or other gradient mesh points are picked. The target is the `Arc` the +/// document holds. +fn state(app: &VectorcraftApp, ctx: &egui::Context) -> (TransparencyInfo, Option>) { type Key = (u64, u64, usize, Option, Option, Option)>>); let Some(st) = app.session.active() else { return Default::default() }; let sel = &st.selection.objects; let key: Key = (st.uid, st.revision, sel.len(), sel.first().copied(), sel.last().copied(), app.session.mesh_points_picked()); let id = egui::Id::unique("tr-state"); - if let Some((k, v)) = ctx.data(|d| d.get_temp::<(Key, (TransparencyInfo, Option))>(id)) + if let Some((k, v)) = ctx.data(|d| d.get_temp::<(Key, (TransparencyInfo, Option>))>(id)) && k == key { return v; } let info = app.session.transparency_info(); - let first = info.ids.first().and_then(|id| st.doc.node(*id)).cloned(); + let first = info.ids.first().and_then(|id| super::layers::node_arc(&st.doc, *id)); let v = (info, first); ctx.data_mut(|d| d.insert_temp(id, (key, v.clone()))); v @@ -82,18 +85,16 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if editing.is_some() && oresp.on_hover_text(tl!("Stop editing the opacity mask")).clicked() { app.run("transparency.stopEditingOpacityMask", json!({})).ok(); } - if let Some(n) = &n { - let mut bare = n.clone(); - bare.extras_mut().mask = None; - if !node_thumb(app, ui, "tr-obj", &bare, r.shrink(3.0), None) { - let (f, s) = current_paints(app); - let inner = r.shrink2(vec2(6.0, 10.0)); - widgets::paint_chip(ui, inner, &f); - if let Some(c) = s.color() - && !matches!(s, Paint::None) - { - ui.painter().rect_stroke(inner, 0.0, Stroke::new(1.0, super::c32(&c)), StrokeKind::Middle); - } + if let Some(n) = &n + && !node_thumb(app, ui, "tr-obj", n, r.shrink(3.0), None, false) + { + let (f, s) = current_paints(app); + let inner = r.shrink2(vec2(6.0, 10.0)); + widgets::paint_chip(ui, inner, &f); + if let Some(c) = s.color() + && !matches!(s, Paint::None) + { + ui.painter().rect_stroke(inner, 0.0, Stroke::new(1.0, super::c32(&c)), StrokeKind::Middle); } } match (mask, n.as_ref().map(|n| n.id)) { @@ -113,7 +114,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let mresp = ui.interact(mr, egui::Id::unique(MASK_THUMB), Sense::click()); let bg = if m.clip != m.invert { [0, 0, 0, 255] } else { [255, 255, 255, 255] }; ui.painter().rect_filled(mr, 0.0, egui::Color32::from_rgb(bg[0], bg[1], bg[2])); - node_thumb(app, ui, "tr-mask", &m.art, mr.shrink(2.0), Some(bg)); + node_thumb(app, ui, "tr-mask", &m.art, mr.shrink(2.0), Some(bg), true); // Viewing the mask alone (Alt-click) highlights its thumbnail. let viewing = app.session.active().is_some_and(|d| d.shown_mask().is_some()); let border = match (viewing, editing.is_some()) { @@ -262,8 +263,9 @@ fn mask_items(mask: Option<&OpacityMask>, can_make: bool) -> [(&'static str, &'s /// A rendered thumbnail of `n` (which may live outside the tree, like mask art). One texture per /// slot, re-rendered only when the document revision, object or size changes, and not during a -/// drag (every pointer move is a new revision): the last one stays until it ends. -fn node_thumb(app: &VectorcraftApp, ui: &Ui, slot: &str, n: &vectorcraft_doc::Node, r: egui::Rect, bg: Option<[u8; 4]>) -> bool { +/// drag (every pointer move is a new revision): the last one stays until it ends. With `own_mask` +/// false, `n` is drawn without its opacity mask. +fn node_thumb(app: &VectorcraftApp, ui: &Ui, slot: &str, n: &vectorcraft_doc::Node, r: egui::Rect, bg: Option<[u8; 4]>, own_mask: bool) -> bool { use std::cell::RefCell; thread_local! { static RENDERER: RefCell = RefCell::new(vectorcraft_render::Renderer::new()); @@ -275,12 +277,20 @@ fn node_thumb(app: &VectorcraftApp, ui: &Ui, slot: &str, n: &vectorcraft_doc::No let cached: Option<(egui::Id, u64, egui::TextureHandle)> = ui.ctx().data(|d| d.get_temp(slot_id)); let tex = match cached { Some((k, rev, tex)) if k == key && (rev == st.revision || busy) => Some(tex), - _ => RENDERER.with(|rr| rr.borrow_mut().render_node_thumbnail_with(&st.doc, n, px, bg, &super::layers::thumb_options())).map(|img| { - let color = crate::canvas::color_image(&img); - let tex = ui.ctx().load_texture(slot, color, egui::TextureOptions::LINEAR); - ui.ctx().data_mut(|d| d.insert_temp(slot_id, (key, st.revision, tex.clone()))); - tex - }), + _ => { + let bare = (!own_mask && n.extras().mask.is_some()).then(|| { + let mut bare = n.clone(); + bare.extras_mut().mask = None; + bare + }); + let n = bare.as_ref().unwrap_or(n); + RENDERER.with(|rr| rr.borrow_mut().render_node_thumbnail_with(&st.doc, n, px, bg, &super::layers::thumb_options())).map(|img| { + let color = crate::canvas::color_image(&img); + let tex = ui.ctx().load_texture(slot, color, egui::TextureOptions::LINEAR); + ui.ctx().data_mut(|d| d.insert_temp(slot_id, (key, st.revision, tex.clone()))); + tex + }) + } }; let Some(tex) = tex else { return false }; let side = r.width().min(r.height()); @@ -448,4 +458,57 @@ mod tests { let texts = frame(&mut app); assert!(texts.iter().any(|t| t == "✓ Page Knockout Group") && texts.iter().any(|t| t == "✓ Page Isolated Blending"), "{texts:?}"); } + + /// The pixels of the thumbnail [`node_thumb`] draws of `n`, in a context of its own (so no + /// earlier texture is reused). + fn thumb_pixels(app: &VectorcraftApp, n: &Node, own_mask: bool) -> Vec { + let ctx = egui::Context::default(); + let r = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(44.0, 44.0)); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + assert!(node_thumb(app, ui, "tr-test", n, r, None, own_mask), "the thumbnail draws"); + }); + let cached: Option<(egui::Id, u64, egui::TextureHandle)> = ctx.data(|d| d.get_temp(egui::Id::unique("tr-test"))); + let id = cached.expect("the thumbnail's texture").2.id(); + let pixels = out.textures_delta.set.iter().find(|e| e.0.eq(&id)).and_then(|e| e.1.last()).map(|d| { + let egui::ImageData::Color(img) = &d.image; + img.pixels.clone() + }); + out.textures_delta.clear(); + pixels.expect("the thumbnail uploads") + } + + /// The panel's state holds the target as the document holds it, a new one after an edit and + /// after Undo; the object thumbnail of a masked object draws as the object without its mask. + #[test] + fn state_holds_the_documents_node_and_the_object_thumbnail_leaves_out_the_mask() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + run(&mut app, "file.new", json!({"width": 100, "height": 100})); + let a = run(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50}))["id"].clone(); + let b = run(&mut app, "shape.ellipse", json!({"x": 10, "y": 10, "width": 20, "height": 20}))["id"].clone(); + run(&mut app, "select.set", json!({"ids": [a, b]})); + run(&mut app, "transparency.makeOpacityMask", json!({})); + let held = |app: &VectorcraftApp, id: NodeId| super::super::layers::node_arc(&app.session.active().unwrap().doc, id).expect("held"); + let ctx = egui::Context::default(); + let n = state(&app, &ctx).1.expect("the masked object"); + assert!(n.extras().mask.is_some(), "the object has its mask"); + assert!(Arc::ptr_eq(&n, &held(&app, n.id)), "the node the document holds"); + assert!(Arc::ptr_eq(&state(&app, &ctx).1.expect("cached"), &n), "the cached state gives the same node"); + // The object thumbnail: as a copy with the mask removed draws, not as the masked object. + let mut bare = (*n).clone(); + bare.extras_mut().mask = None; + let without = thumb_pixels(&app, &n, false); + assert!(without == thumb_pixels(&app, &bare, true), "the object without its mask"); + assert!(without != thumb_pixels(&app, &n, true), "the mask changes the drawing"); + // An edit and its Undo: the state follows the document. + run(&mut app, "transparency.set", json!({"opacity": 40})); + let (info, edited) = state(&app, &ctx); + let edited = edited.expect("the edited object"); + assert_eq!((info.opacity, edited.opacity), (Some(40.0), 0.4)); + assert!(Arc::ptr_eq(&edited, &held(&app, n.id)) && !Arc::ptr_eq(&edited, &n), "the edited node"); + run(&mut app, "edit.undo", json!({})); + let (info, undone) = state(&app, &ctx); + let undone = undone.expect("the object after Undo"); + assert_eq!((info.opacity, undone.opacity), (Some(100.0), 1.0)); + assert!(Arc::ptr_eq(&undone, &held(&app, n.id)), "the node Undo put back"); + } } diff --git a/crates/ui-egui/src/panels/variables.rs b/crates/ui-egui/src/panels/variables.rs index 03183c6652..1b6561f550 100644 --- a/crates/ui-egui/src/panels/variables.rs +++ b/crates/ui-egui/src/panels/variables.rs @@ -967,12 +967,12 @@ mod tests { let xml = r#""#; app.run("variable.loadLibrary", json!({"xml": xml})).unwrap(); assert_eq!(app.ui.status, status, "the load gives no warning"); - let warning = "variables that aren't text were left out: other (1)"; + let warning = "variables that aren't text were left out: `other` (1)"; let langs: Vec = Lang::all().filter(|l| l.code() != "en").collect(); assert!(langs.len() >= 23, "{} languages", langs.len()); for l in langs { let shown = message(l, warning); - assert!(!shown.contains("left out") && shown.contains("other") && shown.contains('1'), "{}: {shown}", l.code()); + assert!(!shown.contains("left out") && shown.contains("`other` (1)"), "{}: {shown}", l.code()); } } @@ -992,6 +992,8 @@ mod tests { assert_eq!(app.ui.status, "a new document won't read these variables back with their kind: `#Tag`"); let warning = app.ui.status.clone(); app.run("variable.define", json!({"name": "%Rate", "kind": "text"})).unwrap(); + // A new document reads a `%` header's values as paths of graph data files. + app.run("dataset.new", json!({"name": "Rates", "values": {"%Rate": "5"}})).unwrap(); app.run("dataset.export", json!({"path": path})).unwrap(); assert_eq!(app.ui.status, "a new document refuses this file because of these variables: `%Rate`"); let refuses = app.ui.status.clone(); diff --git a/crates/ui-egui/src/picks.rs b/crates/ui-egui/src/picks.rs index ea1b51e049..5fec40bb3e 100644 --- a/crates/ui-egui/src/picks.rs +++ b/crates/ui-egui/src/picks.rs @@ -32,10 +32,14 @@ pub enum PickRequest { Open(FilePick), /// An open dialog for files to place. OpenMany, + /// An open dialog for several files of the pick's types. + OpenFiles(FilePick), /// A save dialog. Save(FilePick), /// A folder picker. Folder, + /// A folder picker that starts in the folder given. + FolderAt(String), } /// The paths a dialog shown off the UI thread picked (none: cancelled). A save dialog that reports @@ -82,6 +86,7 @@ const DOCUMENT_FREE: &[&str] = &[ "ui.shortcutImportDialog", crate::panels::actions::SAVE_SET, crate::panels::actions::LOAD_SET, + crate::panels::actions::REPLACE_SET, ]; impl Entry { @@ -192,10 +197,10 @@ impl Picks { /// The kind of dialog open off the UI thread (`ui.inspect`'s `fileDialog`). pub(crate) fn waiting_kind(&self) -> Option<&'static str> { self.waiting.as_ref().map(|w| match w.request { - PickRequest::Open(_) => "open", + PickRequest::Open(_) | PickRequest::OpenFiles(_) => "open", PickRequest::OpenMany => "place", PickRequest::Save(_) => "save", - PickRequest::Folder => "folder", + PickRequest::Folder | PickRequest::FolderAt(_) => "folder", }) } } @@ -350,19 +355,32 @@ pub(crate) fn folder(app: &mut VectorcraftApp) -> Option { ask(app, PickRequest::Folder)?.into_iter().next() } +/// A folder from the folder picker, which starts in `start` when the host can start it there. +pub(crate) fn folder_at(app: &mut VectorcraftApp, start: &str) -> Option { + ask(app, PickRequest::FolderAt(start.to_string()))?.into_iter().next() +} + /// Paths from the open dialog for files to place (none: cancelled). pub(crate) fn open_many(app: &mut VectorcraftApp) -> Vec { ask(app, PickRequest::OpenMany).unwrap_or_default() } +/// Paths from an open dialog for several files of `pick`'s types (none: cancelled, or shown off the +/// UI thread for now). +pub(crate) fn open_files(app: &mut VectorcraftApp, pick: &FilePick) -> Vec { + ask(app, PickRequest::OpenFiles(pick.clone())).unwrap_or_default() +} + /// Whether the host shows `request`'s kind of dialog at all. pub(crate) fn can(app: &VectorcraftApp, request: &PickRequest) -> bool { let s = &app.services; match request { PickRequest::Open(_) => s.pick_open.is_some(), PickRequest::OpenMany => s.pick_open_multi.is_some() || s.pick_open.is_some(), + PickRequest::OpenFiles(_) => s.pick_open_files.is_some() || s.pick_open.is_some(), PickRequest::Save(_) => s.pick_save.is_some(), PickRequest::Folder => s.pick_folder.is_some(), + PickRequest::FolderAt(_) => s.pick_folder_at.is_some() || s.pick_folder.is_some(), } } @@ -402,11 +420,21 @@ fn ask(app: &mut VectorcraftApp, request: PickRequest) -> Option { PickRequest::Open(pick) => one(s.pick_open.as_mut().and_then(|f| f(pick))), PickRequest::Save(pick) => one(s.pick_save.as_mut().and_then(|f| f(pick))), PickRequest::Folder => one(s.pick_folder.as_mut().and_then(|f| f())), + PickRequest::FolderAt(start) => match (s.pick_folder_at.as_mut(), s.pick_folder.as_mut()) { + (Some(at), _) => one(at(start)), + (None, Some(f)) => one(f()), + (None, None) => None, + }, PickRequest::OpenMany => match (s.pick_open_multi.as_mut(), s.pick_open.as_mut()) { (Some(many), _) => Some(many()), (None, Some(f)) => one(f(&FilePick::default())), (None, None) => None, }, + PickRequest::OpenFiles(pick) => match (s.pick_open_files.as_mut(), s.pick_open.as_mut()) { + (Some(many), _) => Some(many(pick)), + (None, Some(f)) => one(f(pick)), + (None, None) => None, + }, } } diff --git a/crates/ui-egui/src/place.rs b/crates/ui-egui/src/place.rs index 9cce282ee6..3ff8159407 100644 --- a/crates/ui-egui/src/place.rs +++ b/crates/ui-egui/src/place.rs @@ -433,7 +433,8 @@ fn line(i: Result, units: vectorcraft_doc::Unit) -> String { match (i["pixelWidth"].as_u64(), i["pixelHeight"].as_u64()) { (Some(w), Some(h)) => { let ppi = i["ppi"][0].as_f64().unwrap_or(72.0); - format!("{w} × {h} px, {} ppi, {} ({size})", fmt_ppi(ppi), i["colorMode"].as_str().unwrap_or("RGB")) + let ppi = crate::i18n::fill_once(tl!("{n} ppi"), &[("n", &fmt_ppi(ppi))]); + format!("{w} × {h} px, {ppi}, {} ({size})", i["colorMode"].as_str().unwrap_or("RGB")) } _ => format!("{} ({size})", i["format"].as_str().unwrap_or_default().to_uppercase()), } @@ -690,7 +691,7 @@ pub fn paint_cursor(app: &mut VectorcraftApp, ctx: &egui::Context, painter: &egu // ---------- drops ---------- impl VectorcraftApp { - /// Where file `name` dropped with the pointer at `pos` (screen points) goes: as in Illustrator, + /// Where file `name` dropped with the pointer at `pos` (screen points) goes: /// onto the canvas of the open document (Shift embeds it), else opened. Where the platform /// doesn't say (`None`: desktop drags carry no position), a document opens as a tab of its /// own and a picture or text is placed in the middle of the view. A library, a presets file, a @@ -929,3 +930,20 @@ pub(crate) fn link_buttons(app: &mut VectorcraftApp, ui: &mut egui::Ui, id: u64, crate::panels::links::unembed(app, id, name); } } + +#[cfg(test)] +mod tests { + use super::*; + + /// The Place dialog's line about an image writes its resolution with the `{n} ppi` row. + #[test] + fn the_file_line_writes_the_ppi_unit_in_the_interface_language() { + let info = json!({ "pixelWidth": 300, "pixelHeight": 150, "ppi": [300.0, 300.0], "colorMode": "RGB", "width": 72.0, "height": 36.0 }); + let en = line(Ok(info.clone()), vectorcraft_doc::Unit::Points); + crate::i18n::set_current(crate::i18n::Lang::from_code("fr").unwrap()); + let fr = line(Ok(info), vectorcraft_doc::Unit::Points); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert!(en.starts_with("300 × 150 px, 300 ppi, RGB ("), "{en}"); + assert!(fr.starts_with("300 × 150 px, 300 ppp, RGB ("), "{fr}"); + } +} diff --git a/crates/ui-egui/src/placing.rs b/crates/ui-egui/src/placing.rs index ca380f7ca8..c43ad596b4 100644 --- a/crates/ui-egui/src/placing.rs +++ b/crates/ui-egui/src/placing.rs @@ -21,10 +21,11 @@ use vectorcraft_engine::file_access::ScopeHandle; use crate::VectorcraftApp; -/// What was read: one file to place, the files to load the place cursor with (and whether they ask -/// for their import options when placed), or a bitmap to paste. +/// What was read: one file to place (and where new art went when it was placed), the files to load +/// the place cursor with (and whether they ask for their import options when placed), or a bitmap +/// to paste. enum Read { - Place(Box), + Place(Box, Insertion), Queue(QueueRead, bool), Paste(Box), } @@ -56,7 +57,8 @@ struct Paste { } /// Where new art goes in the active document: the current layer, the isolated group or object, and -/// the drawing mode with the object Draw Inside draws into. +/// the drawing mode with the object Draw Inside draws into. A paste and a placed file read off the +/// UI thread keep the one from when they were given. #[derive(Clone, PartialEq)] struct Insertion { layer: Option, @@ -81,9 +83,34 @@ impl Insertion { Some(Self { layer, isolation, draw_mode, draw_inside }) } + /// Whether new art can still go where `self` says in `app`'s active document: the isolated group + /// or object when it names one, else the object Draw Inside draws into when it names one and + /// `draws_inside` (a paste draws inside it, a placed file does not), else its layer, which must + /// still be a layer, is still there, shown and unlocked. A paste or a placed file whose layer or + /// group was deleted, hidden or locked meanwhile goes where new art goes now. + fn usable(&self, app: &VectorcraftApp, draws_inside: bool) -> bool { + app.session.doc().is_ok_and(|st| { + let inside = self.draw_inside.filter(|_| draws_inside && self.draw_mode == vectorcraft_engine::DrawMode::Inside); + match (self.isolation, inside, self.layer) { + (Some(target), ..) | (None, Some(target), _) => st.doc.is_editable(target), + (None, None, Some(l)) => st.doc.node(l).is_some_and(|n| n.is_layer()) && st.doc.is_editable(l), + (None, None, None) => true, + } + }) + } + + /// `self` when new art can still go there ([`Self::usable`]), else `now`: where new art went + /// before the paste or the place selected anything again. + fn or_now(self, now: Option<&Self>, app: &VectorcraftApp, draws_inside: bool) -> Self { + match now { + Some(now) if !self.usable(app, draws_inside) => now.clone(), + _ => self, + } + } + /// Put back each part of `self` (where new art went before [`Self::set`] set `started`) that - /// differs from `started`, what the user changed meanwhile; a part the paste itself changed - /// stays as the paste left it. + /// differs from `started`, what the user changed meanwhile; a part the paste or the place + /// itself changed stays as it left it. fn restore_changed(self, started: &Self, app: &mut VectorcraftApp) { if let Ok(st) = app.session.doc_mut() { if self.layer != started.layer { @@ -224,7 +251,9 @@ pub fn start(app: &mut VectorcraftApp, p: &Value, dropped: bool) -> Result) { } app.session.set_active(i); let r = match r { - Ok(Read::Place(read)) => app.session.place_read(*read).map(|_| ()).map_err(|e| e.to_string()), + Ok(Read::Place(read, insertion)) => { + // The file goes where new art went when it was placed (the current layer, the isolated + // group), as a paste does, and what the user changed meanwhile is kept. Where new art + // goes now is taken before Replace selects the object it swaps again. + let current = Insertion::of(app); + let insertion = insertion.or_now(current.as_ref(), app, false); + insertion.clone().set(app); + let r = app.session.place_read(*read).map(|_| ()).map_err(|e| e.to_string()); + if let Some(current) = current { + current.restore_changed(&insertion, app); + } + r + } Ok(Read::Queue(read, asks)) => { app.session.place_queue_read(read).map(|r| crate::place::show_thumbnails(app, &r, asks)).map_err(|e| e.to_string()) } @@ -540,7 +581,8 @@ fn finish_paste(app: &mut VectorcraftApp, paste: Paste) { // The paste goes where new art went when it started (the current layer, the isolated // group, the object Draw Inside draws into), and what the user changed meanwhile is // kept. - paste.insertion.clone().set(app); + let insertion = paste.insertion.or_now(current.as_ref(), app, pastes_inside(&paste.id)); + insertion.clone().set(app); let requested_selection = app.session.doc().map(|st| st.selection.objects.clone()).unwrap_or_default(); app.placing.adopted = true; // `run` shows an error in the status bar. @@ -552,7 +594,7 @@ fn finish_paste(app: &mut VectorcraftApp, paste: Paste) { if let Ok(st) = app.session.doc() { app.placing.swatch_paste = Some(PendingSwatch { clipboard: app.session.clipboard.clone(), - insertion: paste.insertion.clone(), + insertion: insertion.clone(), selection: requested_selection, doc: st.uid, reverts: st.reverts, @@ -562,7 +604,7 @@ fn finish_paste(app: &mut VectorcraftApp, paste: Paste) { } } if let Some(current) = current { - current.restore_changed(&paste.insertion, app); + current.restore_changed(&insertion, app); } app.session.doc().ok().map(|st| st.selection.objects.clone()) } @@ -613,6 +655,12 @@ pub(crate) fn settle_swatch_paste(app: &mut VectorcraftApp) { } } +/// Does the paste command `id` paste inside the object Draw Inside draws into? Paste in Front and +/// Paste in Back keep their own places. +fn pastes_inside(id: &str) -> bool { + !matches!(id, "edit.pasteInFront" | "edit.pasteInBack") +} + /// Run the command confirmed by the deferred paste's Swatch Conflict dialog. pub(crate) fn confirm_swatch_paste(app: &mut VectorcraftApp, id: &str, params: Value, token: Option) -> Result { if !app.placing.swatch_paste.as_ref().is_some_and(|waiting| Some(waiting.chain) == token) { @@ -643,7 +691,7 @@ pub(crate) fn confirm_swatch_paste(app: &mut VectorcraftApp, id: &str, params: V if selected != now.iter().map(|id| id.0).collect::>() { let _ = app.session.execute("select.set", &json!({"ids": selected})); } - let insertion = waiting.insertion.clone(); + let insertion = waiting.insertion.clone().or_now(changed.as_ref(), app, pastes_inside(id)); insertion.clone().set(app); app.placing.adopted = true; let result = app.run(id, params); diff --git a/crates/ui-egui/src/placing/tests.rs b/crates/ui-egui/src/placing/tests.rs index 9043bac0ea..af411f3430 100644 --- a/crates/ui-egui/src/placing/tests.rs +++ b/crates/ui-egui/src/placing/tests.rs @@ -661,6 +661,134 @@ fn a_deferred_swatch_paste_uses_its_original_layer() { assert_eq!(st.current_layer(), Some(second)); } +/// A bitmap pasted from another app while a group is isolated goes into that group when the +/// isolation ends and the current layer, which does not hold the group, is locked while the bitmap +/// is decoded. +#[test] +fn a_bitmap_pasted_into_an_isolated_group_stays_there_when_another_layer_is_locked() { + let (mut app, _) = pasting_app(true, Some(Flavour { mime: PNG, data: picture(Png, 60, 40) }), None, true); + let first = app.session.doc().unwrap().doc.layers[0].id; + app.run("layer.new", json!({})).unwrap(); + let squares: Vec = + (0..2).map(|i| app.run("shape.rectangle", json!({"x": 10 + 30 * i, "y": 10, "width": 20, "height": 20})).unwrap()["id"].clone()).collect(); + app.run("select.set", json!({"ids": squares})).unwrap(); + let group = NodeId(app.run("object.group", json!({})).unwrap()["id"].as_u64().unwrap()); + app.run("select.none", json!({})).unwrap(); + app.run("layer.setCurrent", json!({"id": first.0})).unwrap(); + app.run("object.isolate", json!({"id": group.0})).unwrap(); + app.session.doc_mut().unwrap().active_layer = Some(first); + crate::menus::invoke(&mut app, "edit.paste", json!({})); + app.run("object.exitIsolation", json!({})).unwrap(); + app.run("layer.setProps", json!({"ids": [first.0], "locked": true})).unwrap(); + placed(&mut app); + let st = app.session.doc().unwrap(); + assert_eq!(st.selection.objects.first().and_then(|i| st.doc.parent_of(*i)), Some(group), "pasted into the group isolated at the paste"); + assert_eq!(st.isolation, None, "the isolation ended meanwhile stays ended"); +} + +/// A bitmap pasted from another app whose layer is locked while it is decoded goes into the layer +/// current then, also when the objects selected at the paste, which it selects again, are in +/// another layer. +#[test] +fn a_bitmap_whose_layer_is_locked_meanwhile_is_not_pasted_next_to_the_selection() { + let (mut app, _) = pasting_app(true, Some(Flavour { mime: PNG, data: picture(Png, 60, 40) }), None, true); + let first = app.session.doc().unwrap().doc.layers[0].id; + app.run("layer.new", json!({})).unwrap(); + let selected = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].clone(); + let second = app.session.doc().unwrap().current_layer().unwrap(); + app.run("layer.new", json!({})).unwrap(); + let third = app.session.doc().unwrap().current_layer().unwrap(); + app.run("select.set", json!({"ids": [selected]})).unwrap(); + app.run("layer.setCurrent", json!({"id": first.0})).unwrap(); + assert_eq!(app.session.doc().unwrap().selection.objects.len(), 1); + crate::menus::invoke(&mut app, "edit.paste", json!({})); + app.run("layer.setProps", json!({"ids": [first.0], "locked": true})).unwrap(); + app.run("layer.setCurrent", json!({"id": third.0})).unwrap(); + app.run("select.none", json!({})).unwrap(); + placed(&mut app); + let st = app.session.doc().unwrap(); + let pasted = st.selection.objects.first().and_then(|i| st.doc.layer_containing(*i)); + assert_eq!(pasted, Some(third), "pasted into the current layer, not {second:?}"); +} + +/// In Draw Inside, a bitmap decoded off the UI thread is pasted inside the object Draw Inside draws +/// into, in another layer, when the layer current at the paste is locked meanwhile. +#[test] +fn a_bitmap_pasted_in_draw_inside_stays_inside_when_its_layer_is_locked() { + let (mut app, _) = pasting_app(true, Some(Flavour { mime: PNG, data: picture(Png, 60, 40) }), None, true); + let first = app.session.doc().unwrap().doc.layers[0].id; + app.run("layer.new", json!({})).unwrap(); + let path = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 200, "height": 200})).unwrap()["id"].clone(); + app.run("layer.new", json!({})).unwrap(); + let third = app.session.doc().unwrap().current_layer().unwrap(); + app.run("select.set", json!({"ids": [path]})).unwrap(); + app.run("view.drawMode", json!({"mode": "inside"})).unwrap(); + app.run("select.none", json!({})).unwrap(); + app.run("layer.setCurrent", json!({"id": first.0})).unwrap(); + crate::menus::invoke(&mut app, "edit.paste", json!({})); + app.run("view.drawMode", json!({"mode": "normal"})).unwrap(); + app.run("layer.setProps", json!({"ids": [first.0], "locked": true})).unwrap(); + app.run("layer.setCurrent", json!({"id": third.0})).unwrap(); + placed(&mut app); + let st = app.session.doc().unwrap(); + let group = st.selection.objects.first().and_then(|i| st.doc.parent_of(*i)); + assert!( + group.is_some_and(|g| st.doc.node(g).is_some_and(|n| n.children().is_some_and(|c| c.iter().any(|n| n.id.0 == path.as_u64().unwrap())))), + "pasted inside the path" + ); +} + +/// Paste in Front does not paste inside the object Draw Inside draws into: a bitmap decoded off the +/// UI thread goes into the layer current at the paste when that object is locked meanwhile. +#[test] +fn a_bitmap_pasted_in_front_in_draw_inside_keeps_its_layer() { + let (mut app, _) = pasting_app(true, Some(Flavour { mime: PNG, data: picture(Png, 60, 40) }), None, true); + let first = app.session.doc().unwrap().doc.layers[0].id; + app.run("layer.new", json!({})).unwrap(); + let second = app.session.doc().unwrap().current_layer().unwrap(); + let path = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 200, "height": 200})).unwrap()["id"].clone(); + app.run("layer.new", json!({})).unwrap(); + let third = app.session.doc().unwrap().current_layer().unwrap(); + app.run("select.set", json!({"ids": [path]})).unwrap(); + app.run("view.drawMode", json!({"mode": "inside"})).unwrap(); + app.run("select.none", json!({})).unwrap(); + app.run("layer.setCurrent", json!({"id": first.0})).unwrap(); + crate::menus::invoke(&mut app, "edit.pasteInFront", json!({})); + app.run("layer.setProps", json!({"ids": [second.0], "locked": true})).unwrap(); + app.run("layer.setCurrent", json!({"id": third.0})).unwrap(); + placed(&mut app); + let st = app.session.doc().unwrap(); + assert_eq!(st.selection.objects.first().and_then(|i| st.doc.layer_containing(*i)), Some(first), "pasted into the layer current at the paste"); +} + +/// A paste waiting for its Swatch Conflict dialog whose layer is locked before the dialog's OK +/// goes into the layer current at the OK, not into the topmost layer. +#[test] +fn a_deferred_swatch_paste_whose_layer_is_locked_meanwhile_uses_the_current_layer() { + let (mut app, _) = pasting_app(true, None, None, true); + app.run("swatch.new", json!({"name": "Brand", "color": "#ff0000", "global": true})).unwrap(); + let source = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].clone(); + app.run("paint.setFill", json!({"ids": [source], "swatch": "Brand"})).unwrap(); + app.run("edit.copy", json!({})).unwrap(); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("swatch.new", json!({"name": "Brand", "color": "#0000ff", "global": true})).unwrap(); + let first = app.session.doc().unwrap().doc.layers[0].id; + app.run("layer.new", json!({})).unwrap(); + let second = app.session.doc().unwrap().current_layer().unwrap(); + app.run("layer.new", json!({})).unwrap(); + app.run("layer.setCurrent", json!({"id": first.0})).unwrap(); + app.run("select.none", json!({})).unwrap(); + crate::menus::invoke(&mut app, "edit.paste", json!({})); + placed(&mut app); + assert_eq!(app.ui.dialog.as_ref().unwrap().kind, crate::dialogs::swatch_conflict::KIND); + app.run("layer.setProps", json!({"ids": [first.0], "locked": true})).unwrap(); + app.run("layer.setCurrent", json!({"id": second.0})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("choice".into(), json!("add")); + crate::dialogs::confirm(&mut app).unwrap(); + let st = app.session.doc().unwrap(); + assert_eq!(st.selection.objects.first().and_then(|i| st.doc.layer_containing(*i)), Some(second)); +} + #[test] fn a_queued_paste_stacks_after_a_deferred_swatch_confirmation() { for id in ["edit.pasteInFront", "edit.pasteInBack"] { @@ -970,6 +1098,166 @@ fn a_bitmap_read_off_the_ui_thread_is_pasted_into_its_layer() { assert_eq!(st.current_layer(), Some(second), "the layer of the object selected meanwhile stays current"); } +/// An app placing off the UI thread with three layers, the bottom one current → the app, a TIFF +/// file to place and the layers from the bottom up. +fn three_layers(test: &str) -> (VectorcraftApp, String, [NodeId; 3]) { + let mut app = app(true); + let path = saved(test, "a.tif", &picture(Tiff, 60, 40)); + let first = app.session.doc().unwrap().doc.layers[0].id; + app.run("layer.new", json!({})).unwrap(); + let second = app.session.doc().unwrap().current_layer().unwrap(); + app.run("layer.new", json!({})).unwrap(); + let third = app.session.doc().unwrap().current_layer().unwrap(); + app.run("layer.setCurrent", json!({"id": first.0})).unwrap(); + (app, path, [first, second, third]) +} + +/// A file read off the UI thread after the Place dialog's OK is placed into the layer that was +/// current at the OK, and a layer made current while it is read stays current. +#[test] +fn a_file_read_off_the_ui_thread_is_placed_into_its_layer() { + let (mut app, a, [first, second, _]) = three_layers("into-its-layer"); + app.run("file.place", json!({"paths": [a]})).unwrap(); + assert_eq!(crate::dialogs::confirm(&mut app).unwrap()["background"], true); + app.run("layer.setCurrent", json!({"id": second.0})).unwrap(); + placed(&mut app); + let st = app.session.doc().unwrap(); + assert_eq!(st.doc.layer_containing(st.selection.objects[0]), Some(first), "placed into the layer current at the OK"); + assert_eq!(st.current_layer(), Some(second), "the layer made current meanwhile stays current"); +} + +/// A file dropped on the canvas goes into the layer current at the drop, not into a group in +/// another layer isolated while the file is read, and the group stays isolated. +#[test] +fn a_dropped_file_is_placed_into_the_layer_current_at_the_drop() { + let (mut app, a, [first, second, _]) = three_layers("drop-into-its-layer"); + app.run("layer.setCurrent", json!({"id": second.0})).unwrap(); + let squares: Vec = + (0..2).map(|i| app.run("shape.rectangle", json!({"x": 10 + 30 * i, "y": 10, "width": 20, "height": 20})).unwrap()["id"].clone()).collect(); + app.run("select.set", json!({"ids": squares})).unwrap(); + let group = NodeId(app.run("object.group", json!({})).unwrap()["id"].as_u64().unwrap()); + app.run("select.none", json!({})).unwrap(); + app.run("layer.setCurrent", json!({"id": first.0})).unwrap(); + let doc = app.session.doc().unwrap().uid; + let drop = DropTarget::Place(DropAt { doc, reverts: 0, at: vectorcraft_geom::Point::new(200.0, 150.0), embed: false }); + crate::place::drop_files(&mut app, vec![(drop, ("a.tif".into(), Some(a), vec![]))]); + app.run("object.isolate", json!({"id": group.0})).unwrap(); + placed(&mut app); + let st = app.session.doc().unwrap(); + assert_eq!(st.doc.parent_of(st.selection.objects[0]), Some(first), "placed into the layer current at the drop"); + assert_eq!(st.isolation, Some(group), "the group stays isolated"); +} + +/// An object selected in another layer while a placed file is read makes that layer current, and +/// it stays current after the file is placed into the layer current at the OK. +#[test] +fn a_file_placed_while_an_object_in_another_layer_is_selected_keeps_its_layer() { + let (mut app, a, [first, second, _]) = three_layers("select-meanwhile"); + app.run("layer.setCurrent", json!({"id": second.0})).unwrap(); + let square = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].clone(); + app.run("layer.setCurrent", json!({"id": first.0})).unwrap(); + app.run("select.none", json!({})).unwrap(); + app.run("file.place", json!({"paths": [a]})).unwrap(); + crate::dialogs::confirm(&mut app).unwrap(); + app.run("select.set", json!({"ids": [square]})).unwrap(); + assert_eq!(app.session.doc().unwrap().current_layer(), Some(second)); + placed(&mut app); + let st = app.session.doc().unwrap(); + assert_eq!(st.doc.layer_containing(st.selection.objects[0]), Some(first), "placed into the layer current at the OK"); + assert_eq!(st.current_layer(), Some(second), "the layer of the object selected meanwhile stays current"); +} + +/// Replace swaps the object selected at the OK in its own layer, and a layer made current while the +/// file is read stays current after Replace selects that object again. +#[test] +fn a_replace_read_off_the_ui_thread_keeps_the_layer_made_current_meanwhile() { + let (mut app, a, [first, second, _]) = three_layers("replace-meanwhile"); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + crate::place::run_for_user(&mut app, &json!({"path": a, "replace": true})).unwrap(); + app.run("select.none", json!({})).unwrap(); + app.run("layer.setCurrent", json!({"id": second.0})).unwrap(); + placed(&mut app); + let st = app.session.doc().unwrap(); + let image = st.selection.objects[0]; + assert!(matches!(st.doc.node(image).map(|n| &n.kind), Some(vectorcraft_doc::NodeKind::Image(_))), "{}", app.ui.status); + assert_eq!(st.doc.layer_containing(image), Some(first), "the image takes the replaced object's place"); + assert_eq!(st.current_layer(), Some(second), "the layer made current meanwhile stays current"); +} + +/// A file whose layer is deleted or locked while it is read goes where new art goes now: into the +/// layer current then, not into the topmost layer. +#[test] +fn a_file_whose_layer_is_deleted_or_locked_meanwhile_goes_into_the_current_layer() { + let mut found = vec![]; + let mut wanted = vec![]; + for change in ["delete", "lock", "hide"] { + let (mut app, a, [first, second, _]) = three_layers(&format!("layer-{change}")); + app.run("file.place", json!({"paths": [a]})).unwrap(); + crate::dialogs::confirm(&mut app).unwrap(); + match change { + "delete" => app.run("layer.delete", json!({"ids": [first.0]})).unwrap(), + "lock" => app.run("layer.setProps", json!({"ids": [first.0], "locked": true})).unwrap(), + _ => app.run("layer.setProps", json!({"ids": [first.0], "visible": false})).unwrap(), + }; + app.run("layer.setCurrent", json!({"id": second.0})).unwrap(); + placed(&mut app); + let st = app.session.doc().unwrap(); + let image = st.selection.objects.first().copied(); + found.push((change, image.and_then(|i| st.doc.layer_containing(i)), st.current_layer())); + wanted.push((change, Some(second), Some(second))); + } + assert_eq!(found, wanted, "placed into the current layer, which stays current"); +} + +/// Place does not draw inside an object: with Draw Inside on for an object in another layer, a file +/// whose layer is locked while it is read goes into the layer current then. +#[test] +fn a_file_placed_with_draw_inside_on_follows_its_layer() { + let (mut app, a, [first, second, _]) = three_layers("draw-inside"); + app.run("layer.setCurrent", json!({"id": second.0})).unwrap(); + let inside = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 200, "height": 200})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [inside]})).unwrap(); + app.run("view.drawMode", json!({"mode": "inside"})).unwrap(); + app.run("layer.setCurrent", json!({"id": first.0})).unwrap(); + app.run("select.none", json!({})).unwrap(); + assert_eq!(app.session.draw_inside.map(|t| t.0), inside.as_u64()); + app.run("file.place", json!({"paths": [a]})).unwrap(); + crate::dialogs::confirm(&mut app).unwrap(); + app.run("layer.setProps", json!({"ids": [first.0], "locked": true})).unwrap(); + app.run("layer.setCurrent", json!({"id": second.0})).unwrap(); + placed(&mut app); + let st = app.session.doc().unwrap(); + assert_eq!(st.selection.objects.first().and_then(|i| st.doc.layer_containing(*i)), Some(second), "placed into the current layer"); +} + +/// A bitmap pasted from another app whose layer is deleted, locked or hidden while it is decoded +/// goes into the layer current then, not into the topmost layer. +#[test] +fn a_bitmap_whose_layer_is_deleted_or_locked_meanwhile_is_pasted_into_the_current_layer() { + let mut found = vec![]; + let mut wanted = vec![]; + for change in ["delete", "lock", "hide"] { + let (mut app, _) = pasting_app(true, Some(Flavour { mime: PNG, data: picture(Png, 60, 40) }), None, true); + let first = app.session.doc().unwrap().doc.layers[0].id; + app.run("layer.new", json!({})).unwrap(); + let second = app.session.doc().unwrap().current_layer().unwrap(); + app.run("layer.new", json!({})).unwrap(); + app.run("layer.setCurrent", json!({"id": first.0})).unwrap(); + crate::menus::invoke(&mut app, "edit.paste", json!({})); + match change { + "delete" => app.run("layer.delete", json!({"ids": [first.0]})).unwrap(), + "lock" => app.run("layer.setProps", json!({"ids": [first.0], "locked": true})).unwrap(), + _ => app.run("layer.setProps", json!({"ids": [first.0], "visible": false})).unwrap(), + }; + app.run("layer.setCurrent", json!({"id": second.0})).unwrap(); + placed(&mut app); + let st = app.session.doc().unwrap(); + found.push((change, st.selection.objects.first().and_then(|i| st.doc.layer_containing(*i)))); + wanted.push((change, Some(second))); + } + assert_eq!(found, wanted, "pasted into the current layer"); +} + /// The Place dialog's OK with one file, with several (the place cursor and its thumbnails), a /// drop on the canvas and [`crate::io::place_bytes`] read their files off the UI thread; /// `file.place` and `file.place.queue` from MCP and scripts read them at once, with the replies diff --git a/crates/ui-egui/src/prefs_dialog.rs b/crates/ui-egui/src/prefs_dialog.rs index e8a6368cbb..acd994d1a0 100644 --- a/crates/ui-egui/src/prefs_dialog.rs +++ b/crates/ui-egui/src/prefs_dialog.rs @@ -1,4 +1,4 @@ -//! Edit → Preferences (⌘K): Illustrator-style category list + fields, rendered from the engine's +//! Edit → Preferences (⌘K): a category list + its fields, rendered from the engine's //! preference table ([`PREF_SPECS`]). The dialog edits a working copy in `Dialog::fields` //! (one field per preference key, so agents can `ui.dialog.set` any of them) and OK applies it //! through `prefs.set`. Also: persistence of engine prefs inside `UiState` and the per-frame @@ -72,6 +72,7 @@ fn settings() -> impl Iterator { "appTitleBar" => APP_TITLE_BAR_SHOWN, "linuxDisplayServer" => DISPLAY_SERVER_CHOICE, "monitorProfileDisplay" => !cfg!(target_arch = "wasm32"), + "lowLatencyDrawing" => !cfg!(target_arch = "wasm32"), _ => true, }; let prefs = @@ -660,6 +661,9 @@ fn category_fields(ui: &mut egui::Ui, app: &mut VectorcraftApp, d: &mut Dialog, ui.label(egui::RichText::new(note).color(t.text_dim).size(11.0)); } } + // The desktop app only: it sets the window's present mode when it starts, so a note + // says the change applies at the next start. + PrefKind::Bool if sp.key == "lowLatencyDrawing" => desktop_startup_bool_row(ui, d, sp.key, sp.label, &t), PrefKind::Bool => bool_row(ui, d, sp.key, sp.label), PrefKind::Num { min, max, unit } => { labeled(ui, sp.label, |ui, label_id| { @@ -883,6 +887,16 @@ fn bool_row(ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str) { } } +/// A checkbox the desktop app reads once, when it starts (Performance › Low-Latency Drawing, which +/// sets the window's present mode), with its restart note. The web build doesn't show it. +fn desktop_startup_bool_row(ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str, t: &Tokens) { + if cfg!(target_arch = "wasm32") { + return; + } + bool_row(ui, d, key, label); + ui.label(egui::RichText::new(tl!("Applies the next time VectorCraft starts.")).color(t.text_dim).size(11.0)); +} + fn labeled(ui: &mut egui::Ui, label: &str, add: impl FnOnce(&mut egui::Ui, egui::Id)) { let t = Tokens::get(ui.ctx()); ui.horizontal(|ui| { diff --git a/crates/ui-egui/src/prefs_dialog/descriptions.rs b/crates/ui-egui/src/prefs_dialog/descriptions.rs index eb8156f8dd..b65161d131 100644 --- a/crates/ui-egui/src/prefs_dialog/descriptions.rs +++ b/crates/ui-egui/src/prefs_dialog/descriptions.rs @@ -39,6 +39,7 @@ pub(crate) const DESCRIPTIONS: &[(&str, &str)] = &[ ("ctrlWheelScrollsSideways", "The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways."), ("scrubNumericFields", "Dragging sideways on a numeric field's label changes the field's value."), ("trackpadRotateView", "A two-finger rotate gesture on a trackpad rotates the canvas view."), + ("interpolateControlPoints", "When you move anchor points, each curve with one moved end keeps its shape relative to its ends."), ("holdToolKeys", "Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again."), ("boundingBoxWhileMovingAndDrawing", "Shows the bounding box while you move the selection or draw a shape."), ("japaneseCropMarks", "Create Trim Marks draws Japanese-style marks instead of Roman ones."), @@ -61,6 +62,63 @@ pub(crate) const DESCRIPTIONS: &[(&str, &str)] = &[ "artboardUpdateWhileDragging", "With Fade Region Outside Artboard on, the area outside the artboards stays dark while you drag with the Artboard tool.", ), + // Type + ( + "typeSizeIncrement", + "The step for type size and leading: Cmd/Ctrl+Shift+. and Cmd/Ctrl+Shift+, change the size by one step, or five with Alt too; in horizontal type, Alt with the Up or Down Arrow changes the leading by one step, or five with Cmd/Ctrl.", + ), + ( + "trackingIncrement", + "The step for tracking and kerning, in thousandths of an em: in horizontal type, Alt with the Left or Right Arrow changes the kerning at the caret or the tracking of the selected text by one step, or five with Cmd/Ctrl.", + ), + ( + "baselineShiftIncrement", + "The step for baseline shift: in horizontal type, Alt and Shift with the Up or Down Arrow move the baseline by one step, or five with Cmd/Ctrl.", + ), + ( + "showEastAsianOptions", + "Shows the options for Japanese and other East Asian type in the Character, Paragraph, OpenType and Glyphs panels, and Type › Composite Fonts.", + ), + ( + "showIndicOptions", + "Shows the options for Arabic, Hebrew and Indic type in the Character and Paragraph panels, such as paragraph direction, kashidas and digits.", + ), + ("typeSelectionByPathOnly", "The selection tools select type only on its baseline, its area's frame or its path, not anywhere inside its box."), + ("fontNamesInEnglish", "Font menus list each font by its English name; off, a font that also has a name in its own language shows that name."), + ( + "autoSizeAreaType", + "New area type starts with Auto Size on, so a rectangular frame of horizontal type grows or shrinks in height to fit its text.", + ), + ("fontPreview", "Font lists and the Type › Font menu show a sample of each font beside its name."), + ( + "fontSamplesOnWhite", + "Font samples are drawn in dark type on white, whatever the interface's brightness; it applies only while in-menu font previews are on.", + ), + ("fontPreviewSize", "How tall each row is in the font lists of font fields, such as the Character panel's, and so how large each sample is."), + ("recentFontsCount", "How many of the fonts used last, from 1 to 15, Type › Recent Fonts and the font lists show, newest first."), + ("missingGlyphProtection", "When you change the font or font style of text, characters the new font has no glyph for keep the font they had."), + ( + "highlightAlternateGlyphs", + "A pink highlight on the canvas marks glyphs that OpenType features replaced, such as ligatures; it does not print or export.", + ), + ( + "showCharacterAlternates", + "With the Type tool, selecting one character shows a row of its alternate glyphs beside it on the canvas to choose from.", + ), + ( + "highlightSubstitutedFonts", + "A pink highlight on the canvas marks text drawn in a substitute font because its font is missing; it does not print or export.", + ), + ("placeholderText", "New type made with a Type tool starts with placeholder text, selected, so typing replaces it."), + ("typedLists", "Typing a list marker such as 1. or * and then a space at the start of a paragraph makes the paragraph a list."), + ("fontsFolder", "Fonts in this folder show in the font menus and can be used without being installed."), + ( + "overrideCharColor", + "Applying a graphic style to type removes the characters' own fill or stroke where the style has one, so the style's paint shows.", + ), + ("alignGlyphBoundsPoint", "Align and Distribute measure point type by the ink of its glyphs instead of its em box."), + ("alignGlyphBoundsArea", "Align and Distribute measure area type by the ink of its glyphs instead of its frame."), + ("typeGlyphBounds", "The bounding box and the Transform panel measure point type by the ink of its glyphs instead of its em box."), // Selection & Anchor Display ("selectionTolerance", "How near, in pixels, the pointer must be to an object, anchor or handle for a click to select it."), ( diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index f7c676d441..47535cab06 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -20,6 +20,29 @@ fn marquee_selection_choices_are_saved_from_preferences() { assert!(text.contains("Drag Direction"), "{text}"); } +/// Plug-ins & Scratch Disks › Plug-in Instruction Budget: shown with its choices, applied by OK, +/// saved with the UI state and read back from it when the app starts again. +#[test] +fn plugin_instruction_budget_shows_applies_and_restores() { + let mut a = app(); + open(&mut a, Some("Plug-ins & Scratch Disks")); + let text = crate::tests_labels::painted_text(&mut a, |a, ui| show(a, ui.ctx())); + assert!(text.contains("Plug-in Instruction Budget") && text.contains("Normal"), "{text}"); + a.ui.dialog.as_mut().unwrap().fields.insert("pluginInstructionBudget".into(), json!("large")); + confirm(&mut a).unwrap(); + assert_eq!(a.session.prefs.plugin_instruction_budget, vectorcraft_engine::PluginBudget::Large); + let saved: Value = serde_json::from_slice(&serde_json::to_vec(&a.ui).unwrap()).unwrap(); + assert_eq!(saved["engine_prefs"]["pluginInstructionBudget"], json!("large")); + let mut b = app(); + b.ui.engine_prefs = saved["engine_prefs"].clone(); + restore(&mut b); + assert_eq!(b.session.prefs.plugin_instruction_budget, vectorcraft_engine::PluginBudget::Large); + // A saved value this version doesn't offer reads as Normal, and the other preferences stay. + b.ui.engine_prefs = json!({"keyboardIncrement": 4, "pluginInstructionBudget": 7}); + restore(&mut b); + assert_eq!((b.session.prefs.plugin_instruction_budget, b.session.prefs.keyboard_increment), (vectorcraft_engine::PluginBudget::Normal, 4.0)); +} + #[test] fn geometric_snapping_is_a_saved_smart_guides_preference() { let mut a = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); @@ -512,6 +535,44 @@ fn graphics_processor_preference_shows_and_persists() { assert_eq!(saved["engine_prefs"]["gpuPreference"], json!("highPerformance")); } +/// Performance › Low-Latency Drawing (#6013): shown off with its restart note, applied by OK, +/// saved with the UI state under the key the desktop app reads before the window opens, and every +/// bundled language translates its label. +#[test] +fn low_latency_drawing_preference_shows_and_persists() { + fn texts(s: &egui::Shape, out: &mut Vec) { + match s { + egui::Shape::Text(t) => out.push(t.galley.text().to_string()), + egui::Shape::Vec(v) => v.iter().for_each(|s| texts(s, out)), + _ => {} + } + } + let mut a = app(); + open(&mut a, Some("Performance")); + assert_eq!(a.ui.dialog.as_ref().unwrap().fields.get("lowLatencyDrawing"), Some(&json!(false))); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(&mut a, ui.ctx())); + out.textures_delta.clear(); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(&mut a, ui.ctx())); + out.textures_delta.clear(); + let mut shown = vec![]; + out.shapes.iter().for_each(|c| texts(&c.shape, &mut shown)); + let at = shown.iter().position(|t| t == "Low-Latency Drawing").unwrap_or_else(|| panic!("{shown:?}")); + // The note is the row's own: it comes before the next row's label. + let next = shown[at..].iter().position(|t| t.starts_with("History States")).map(|n| at + n).unwrap_or_else(|| panic!("{shown:?}")); + assert!(shown[at..next].iter().any(|t| t == "Applies the next time VectorCraft starts."), "{shown:?}"); + a.ui.dialog.as_mut().unwrap().fields.insert("lowLatencyDrawing".into(), json!(true)); + confirm(&mut a).unwrap(); + assert!(a.take_prefs_changed(), "OK asks the host to write the preferences file"); + assert!(a.session.prefs.low_latency_drawing); + let saved: Value = serde_json::from_slice(&serde_json::to_vec(&a.ui).unwrap()).unwrap(); + assert_eq!(saved["engine_prefs"]["lowLatencyDrawing"], json!(true)); + for lang in crate::i18n::Lang::all().filter(|l| l.code() != crate::i18n::Lang::EN.code()) { + assert!(crate::i18n::has(lang, "Low-Latency Drawing"), "{}", lang.code()); + } +} + /// User Interface › System Title Bar: shown with its next-launch note, applied by OK and /// saved with the UI state under the key the desktop app reads before the window opens. #[test] @@ -1632,8 +1693,8 @@ fn ok_refuses_a_typed_folder_outside_the_automation_roots_before_looking_at_it() /// One frame of the open Preferences dialog with `events`, a quarter second after the last. → The /// texts it painted where they show (a text its clip rectangle hides is left out), with their -/// rectangles, and the description of each accessibility node that has one. -fn description_frame(a: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> (Vec<(String, egui::Rect)>, Vec) { +/// rectangles, and the description of the accessibility node with the keyboard focus, if it has one. +fn description_frame(a: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> (Vec<(String, egui::Rect)>, Option) { let time = ctx.input(|i| i.time) + 0.25; let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 900.0))); let raw = egui::RawInput { screen_rect, events, time: Some(time), ..Default::default() }; @@ -1653,9 +1714,11 @@ fn description_frame(a: &mut VectorcraftApp, ctx: &egui::Context, events: Vec {} + n => bad.push(format!("`{}` ({}) has {n} sentences", s.key, s.label)), + } + if descriptions::description(s.key).is_some_and(|d| d.trim().is_empty()) { + bad.push(format!("`{}` has an empty sentence", s.key)); + } + } + assert!(count > 0, "the Type category shows settings"); + assert!(bad.is_empty(), "{}", bad.join("\n")); +} + +/// The pointer over Type's Size/Leading row and over its Show East Asian Options box shows each +/// row's sentence. +#[test] +fn hovering_a_type_row_shows_its_description() { + let mut a = app(); + open(&mut a, Some("Type")); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + description_frame(&mut a, &ctx, vec![]); + let (texts, _) = description_frame(&mut a, &ctx, vec![]); + let row = |texts: &[(String, egui::Rect)], label: &str| { + texts.iter().find(|(t, _)| t == label).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("no `{label}` in {texts:?}")) + }; + let size = descriptions::description("typeSizeIncrement").expect("Size/Leading has a sentence"); + let east_asian = descriptions::description("showEastAsianOptions").expect("Show East Asian Options has a sentence"); + description_frame(&mut a, &ctx, vec![egui::Event::PointerMoved(row(&texts, "Size/Leading:"))]); + let (after, _) = description_frame(&mut a, &ctx, vec![]); + assert!(painted(&after, size) && !painted(&after, east_asian), "the Size/Leading row's sentence shows: {after:?}"); + description_frame(&mut a, &ctx, vec![egui::Event::PointerMoved(row(&texts, "Show East Asian Options"))]); + let (after, _) = description_frame(&mut a, &ctx, vec![]); + assert!(painted(&after, east_asian) && !painted(&after, size), "the East Asian row's sentence shows: {after:?}"); +} + +/// Tab from the search field reaches Type's first control, the Size/Leading field: the line shows +/// its sentence and a screen reader gets it as the control's description. +#[test] +fn keyboard_focus_on_a_type_row_shows_its_description() { + let mut a = app(); + open(&mut a, Some("Type")); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + description_frame(&mut a, &ctx, vec![]); + description_frame(&mut a, &ctx, vec![]); + let size = descriptions::description("typeSizeIncrement").expect("Size/Leading has a sentence"); + let mut shown = None; + for _ in 0..40 { + let (texts, described) = description_frame(&mut a, &ctx, key_press(egui::Key::Tab, egui::Modifiers::NONE)); + if painted(&texts, size) { + shown = Some(described); + break; + } + } + let described = shown.expect("Tab reaches the Size/Leading row and its sentence shows"); + assert_eq!(described.as_deref(), Some(size), "the focused control carries the sentence"); } /// The pointer over Selection & Anchor Display's Tolerance row and over its Highlight anchors on diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index ddba7618d1..7bc52f35b1 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -1,7 +1,7 @@ //! A running script, advanced one slice per frame: `script.run` starts it and [`poll`] takes it to //! its end, while the app goes on drawing the documents as they were before the run. The status bar //! shows it with a Stop button; a run that has added a great deal, or that opened a dialog with -//! `alert`, `confirm` or `prompt`, waits for the person's answer. +//! `alert`, `confirm`, `prompt` or a `File` or `Folder` file dialog, waits for the person's answer. use serde_json::json; @@ -49,6 +49,15 @@ pub fn poll(app: &mut VectorcraftApp) { /// question about its growth. Closes the script's dialog when the run no longer waits at it. /// → true while the run waits. fn ask(app: &mut VectorcraftApp) -> bool { + if let Some(picker) = app.session.script_picker() { + if app.ui.dialog.is_none() { + script_run::open_picker(app, &picker); + } + return true; + } + if app.ui.dialog.as_ref().is_some_and(|d| d.kind == script_run::PICKER_KIND) { + app.ui.dialog = None; + } if let Some(dialog) = app.session.script_dialog() { if app.ui.dialog.is_none() { script_run::open_notice(app, &dialog); diff --git a/crates/ui-egui/src/scripts_menu.rs b/crates/ui-egui/src/scripts_menu.rs index c951aac8cb..1afaf11d34 100644 --- a/crates/ui-egui/src/scripts_menu.rs +++ b/crates/ui-egui/src/scripts_menu.rs @@ -7,6 +7,10 @@ //! active one, and each time the File menu of the window's menu bar opens ([`refresh`]). The menus show the last finished //! listing ([`items`]), so a script added to the folder is listed without a restart. //! +//! Until the first read ends the menu shows [`LOADING`], and [`SLOW`] once that read has taken +//! [`SLOW_SECS`]; a first read that cannot start or ends without a listing shows [`UNREADABLE`], +//! and the next read tries again. +//! //! `ui.runInstalledScript {path}` runs a listed script (`script.run`) without the warning Other //! Script… shows: the file was put in the folder to be run from the menu. The path is one a //! listing gave; a file that is no longer a plain script under the folder is not run. @@ -28,8 +32,14 @@ pub const COMMAND: &str = "ui.runInstalledScript"; pub const TRUNCATED: &str = "Some scripts were not listed"; /// The menu's note when the folder is there and cannot be read. pub const UNREADABLE: &str = "The Scripts folder cannot be read"; +/// The menu's note while the first read is under way. +pub const LOADING: &str = "Loading scripts…"; +/// The menu's note once the first read has taken [`SLOW_SECS`]. +pub const SLOW: &str = "The Scripts folder is still being read"; /// The notes, for the catalogs ([`crate::menus::menu_strings`]). -pub const LABELS: &[&str] = &[TRUNCATED, UNREADABLE]; +pub const LABELS: &[&str] = &[TRUNCATED, UNREADABLE, LOADING, SLOW]; +/// How long the first read runs before the menu shows [`SLOW`]. +pub const SLOW_SECS: f64 = 2.0; #[derive(Default)] struct State { @@ -45,6 +55,43 @@ struct State { started: bool, /// The window was the active one at the last [`poll`]. focused: bool, + /// A listing has been taken in. + loaded: bool, + /// When the first read started ([`crate::clock::now_secs`]), while it is under way. + first_read: Option, + /// The first read has taken [`SLOW_SECS`]. + slow: bool, + /// No listing yet, and the last read could not start or ended without one. + failed: bool, +} + +impl State { + /// The note in place of a listing before the first one. + fn first_read_note(&self) -> Option<&'static str> { + if self.loaded { + return None; + } + if self.reading.is_some() { + return Some(if self.slow { SLOW } else { LOADING }); + } + self.failed.then_some(UNREADABLE) + } + + /// No listing yet, and the read under way ended without one or could not start. + fn first_read_failed(&mut self) { + if !self.loaded { + (self.first_read, self.slow, self.failed) = (None, false, true); + self.revision += 1; + } + } + + /// Show [`SLOW`] once the first read has run [`SLOW_SECS`] by `now`. + fn mark_slow(&mut self, now: f64) { + if !self.loaded && !self.slow && self.reading.is_some() && self.first_read.is_some_and(|t| now - t >= SLOW_SECS) { + self.slow = true; + self.revision += 1; + } + } } /// The listing the menus show. One per process in the app; one per thread in unit tests, which run @@ -92,7 +139,8 @@ pub(crate) fn intern(s: &str) -> Option<&'static str> { Some(v) } -/// Changes whenever the menus' listing changes (the macOS menu bar follows it). +/// Changes whenever the menus' listing or the note before the first listing changes (the macOS +/// menu bar follows it). pub fn revision() -> u64 { state().revision } @@ -108,18 +156,28 @@ pub fn refresh(app: &VectorcraftApp, ctx: Option<&egui::Context>) { return; } let (tx, rx) = std::sync::mpsc::channel(); - let ctx = ctx.cloned(); + let worker_ctx = ctx.cloned(); let spawned = std::thread::Builder::new().name("vectorcraft-scripts".into()).spawn(move || { // The app's own folder, read for the person at the keyboard. let listing = vectorcraft_engine::file_access::unconfined(|| vectorcraft_engine::script::folder::list(&root)); if tx.send(listing).is_ok() - && let Some(ctx) = ctx + && let Some(ctx) = worker_ctx { ctx.request_repaint(); } }); - if spawned.is_ok() { - state.reading = Some(rx); + if spawned.is_err() { + state.first_read_failed(); + return; + } + state.reading = Some(rx); + if !state.loaded && state.first_read.is_none() { + // The menus show the loading note, and a frame comes when it is due to change to SLOW. + state.first_read = Some(crate::clock::now_secs()); + state.revision += 1; + if let Some(ctx) = ctx { + ctx.request_repaint_after(std::time::Duration::from_secs_f64(SLOW_SECS)); + } } } @@ -137,6 +195,7 @@ pub fn poll(app: &VectorcraftApp, ctx: &egui::Context) { refresh(app, Some(ctx)); } take(false); + state().mark_slow(crate::clock::now_secs()); let again = { let mut state = state(); let again = state.pending && state.reading.is_none(); @@ -157,14 +216,22 @@ fn take(wait: bool) { let listing = if wait { reading.recv().map_err(|_| TryRecvError::Disconnected) } else { reading.try_recv() }; match listing { Ok(listing) => { - if *state.listing != listing { + let changed = *state.listing != listing; + if changed { state.listing = Arc::new(listing); + } + // The first listing also takes the place of the loading note. + if changed || !state.loaded { state.revision += 1; } + (state.loaded, state.first_read, state.slow, state.failed) = (true, None, false, false); state.reading = None; } Err(TryRecvError::Empty) => {} - Err(TryRecvError::Disconnected) => state.reading = None, + Err(TryRecvError::Disconnected) => { + state.reading = None; + state.first_read_failed(); + } } } @@ -174,6 +241,27 @@ pub(crate) fn wait() { take(true); } +/// The read under way ends without a listing, as when its thread stops early. +#[cfg(test)] +pub(crate) fn lose_read() { + let mut state = state(); + if state.reading.is_some() { + state.reading = Some(std::sync::mpsc::channel::().1); + } +} + +/// When the first read started, while it is under way. +#[cfg(test)] +pub(crate) fn first_read_started() -> Option { + state().first_read +} + +/// What [`poll`] does about a slow first read, at `now` ([`crate::clock::now_secs`]). +#[cfg(test)] +pub(crate) fn check_slow(now: f64) { + state().mark_slow(now); +} + /// Wait for the read under way to end and leave its listing to be taken in, so the read is under /// way until the next [`poll`]. #[cfg(test)] @@ -188,7 +276,8 @@ pub(crate) fn end_untaken() { } /// File › Scripts' items: the listed scripts and subfolders, a note when some may be missing or -/// the folder cannot be read, then Check Script… and Other Script…. +/// the folder cannot be read, or one before the first listing, then Check Script… and Other +/// Script…. pub fn items() -> Vec { // A row whose name is past [`MAX_NAMES`] is left out (`dropped`). fn level(entries: &[Entry], dropped: &mut bool) -> Vec { @@ -208,7 +297,10 @@ pub fn items() -> Vec { } items } - let listing = state().listing.clone(); + let (listing, note) = { + let state = state(); + (state.listing.clone(), state.first_read_note()) + }; let mut dropped = false; let mut items = level(&listing.entries, &mut dropped); if listing.truncated || dropped { @@ -217,6 +309,7 @@ pub fn items() -> Vec { if listing.unreadable { items.push(Item::Header(UNREADABLE)); } + items.extend(note.map(Item::Header)); if !items.is_empty() { items.push(Item::Sep); } diff --git a/crates/ui-egui/src/scrub.rs b/crates/ui-egui/src/scrub.rs index 5a0a2ff4f9..b1de4e585c 100644 --- a/crates/ui-egui/src/scrub.rs +++ b/crates/ui-egui/src/scrub.rs @@ -1,9 +1,10 @@ -//! Scrubbing numeric fields (#400, beyond Illustrator; Photoshop's scrubby labels): a horizontal +//! Scrubbing numeric fields (#400): a horizontal //! drag on a numeric field's label (`W:`, `Opacity:`, the Character panel's size icon) steps the //! field's value by one unit every [`PX_PER_STEP`] points, ten with Shift and a tenth with //! Ctrl/Cmd, as the arrow keys step a focused field; a click on the label focuses the field. A //! label that is a link (the Control bar's `Stroke:` and `Opacity:`, which open their panels; -//! #4088) scrubs its field the same way, and a click on it still follows the link. The text box +//! #4088) or opens a panel (its `X:`, `Y:`, `W:` and `H:`, which open the Transform panel) scrubs +//! its field the same way, and a click on it still opens the panel. The text box //! itself never scrubs, and a field without a label doesn't. //! //! The panels apply each value the drag passes as they apply a typed one, so the art follows the @@ -117,12 +118,14 @@ struct Label { pass: u64, /// The label is a link, this widget: a click follows it instead of focusing the field. link: Option, + /// The label is a tab stop of its own (a link; not a [`panel_label`]). + tab_stop: bool, } /// Note the label (text or icon) drawn at `rect`: a numeric field drawn right after it on the /// same line takes it as its label, which scrubs the field. pub(crate) fn note_label(ui: &Ui, rect: Rect) { - note(ui, rect, None); + note(ui, Label { rect, pass: 0, link: None, tab_stop: false }); } /// A link that labels the numeric field drawn after it (it opens a panel when clicked): a drag on @@ -135,13 +138,27 @@ pub(crate) fn link_label(ui: &mut Ui, text: egui::RichText) -> Response { ui.link(text) }) .inner; - note(ui, link.rect, Some(link.id)); + note(ui, Label { rect: link.rect, pass: 0, link: Some(link.id), tab_stop: true }); link } -fn note(ui: &Ui, rect: Rect, link: Option) { +/// A field's label that opens a panel when clicked (the Control bar's X:, Y:, W: and H:, which open +/// the Transform panel): a drag on it scrubs the field after it, and a click stays the label's, as +/// with [`link_label`]. Unlike a link it is not a tab stop of its own, so Tab still moves from one +/// field to the next. The pointing hand shows over it. +pub(crate) fn panel_label(ui: &mut Ui, text: egui::RichText) -> Response { + let label = ui.add(egui::Label::new(text).selectable(false).sense(Sense::CLICK)); + if label.hovered() { + ui.ctx().set_cursor_icon(CursorIcon::PointingHand); + } + note(ui, Label { rect: label.rect, pass: 0, link: Some(label.id), tab_stop: false }); + label +} + +/// Keep `label` for the field after it, as drawn this pass. +fn note(ui: &Ui, label: Label) { let pass = ui.ctx().cumulative_pass_nr(); - ui.data_mut(|d| d.insert_temp(label_id(), Label { rect, pass, link })); + ui.data_mut(|d| d.insert_temp(label_id(), Label { pass, ..label })); } /// The label noted just before the field at `field`, on its line. @@ -169,9 +186,11 @@ pub(crate) fn field(ui: &Ui, field: Id, rect: Rect, text: &str, value: Option ui.interact(label.rect, link, Sense::drag()), + Some(link) if label.tab_stop => ui.interact(label.rect, link, Sense::drag()), + Some(link) => ui.interact(label.rect, link, Sense::DRAG), None => ui.interact(label.rect, field.with("scrub-label"), Sense::CLICK | Sense::DRAG), }; drag(ui, &resp, field, text, value, decimals, label.link.is_some()).map(|v| v.max(*bounds.start()).min(*bounds.end())) diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs index 676a9a48c8..ce48ef17c1 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -35,6 +35,11 @@ pub type PickOpen = Box Option>; pub type PickSave = Box Option>; +pub type PickOpenFiles = Box Vec>; + +/// Shows a folder picker that starts in the given folder; returns the folder picked. +pub type PickFolderAt = Box Option>; + pub type ReadFn = Box Result, String>>; /// The first `max` bytes of the file at a path (all of it when it is shorter); the rest of the file @@ -120,6 +125,9 @@ pub struct Services { pub open_url: Option, /// Show an open dialog for several files (File → Place…); returns their paths (none: cancelled). pub pick_open_multi: Option Vec>>, + /// Show an open dialog for several files of the pick's types (a script's `File.openDialog` with + /// `multiSelect`); returns their paths (none: cancelled). Without it, an open dialog for one. + pub pick_open_files: Option, /// Web: start an async pick of files to place (they arrive via `place_inbox`). pub place_async: Option>, /// Files that arrived asynchronously to be placed (web: picked for Place, or dropped on the @@ -160,6 +168,9 @@ pub struct Services { pub open_in_photocraft: Option, /// Show a folder picker; returns its path (desktop: Relink to Folder, Package). pub pick_folder: Option Option>>, + /// Show a folder picker that starts in a folder (a script's `selectDlg`); returns its path. + /// Without it, `pick_folder`, which starts where the host starts it. + pub pick_folder_at: Option, /// Show the system's color sampler, which picks a color anywhere on the screen (macOS, Linux /// through the desktop portal, and browsers with an EyeDropper): Sample Color from Screen /// ([`screen_color`]). Without it that command answers with an error and the Color Picker's diff --git a/crates/ui-egui/src/shortcut_editor.rs b/crates/ui-egui/src/shortcut_editor.rs index 84c1ff4fa0..e6120ad599 100644 --- a/crates/ui-egui/src/shortcut_editor.rs +++ b/crates/ui-egui/src/shortcut_editor.rs @@ -152,12 +152,23 @@ pub fn sync(ui: &UiState) { crate::custom_toolbars::sync(ui); } -/// Registry default shortcut of a command (engine or UI command). +/// Registry default shortcut of a command (engine or UI command) on [`crate::keymap::platform`]. pub fn default_command_shortcut(id: &str) -> Option<&'static str> { + default_command_shortcut_on(id, crate::keymap::platform()) +} + +/// Registry default shortcut of a command on platform `p`. +fn default_command_shortcut_on(id: &str, p: craft_keymap::Platform) -> Option<&'static str> { if let Some(c) = vectorcraft_engine::find_command(id) { return c.shortcut; } - menus::UI_COMMANDS.iter().find(|c| c.0 == id).map(|c| c.2).filter(|s| !s.is_empty()) + menus::UI_COMMANDS.iter().find(|c| c.0 == id).map(|c| ui_command_default(c.0, c.2, p)).filter(|s| !s.is_empty()) +} + +/// The default shortcut `sc` of UI command `id` on platform `p` (empty for none). Select Last +/// Selection Tool has none on macOS, which takes Cmd+` to switch between an app's windows. +pub(crate) fn ui_command_default(id: &str, sc: &'static str, p: craft_keymap::Platform) -> &'static str { + if id == "tool.selectLastSelection" && p.is_mac() { "" } else { sc } } /// Window menu items that show a panel (`window.panel {panel}`) with a default shortcut: (panel @@ -184,15 +195,21 @@ pub const PANEL_SHORTCUTS: &[(&str, &str)] = &[ ("openType", "Cmd+Alt+Shift+T"), ]; -/// Default shortcut of an entry key (`tool:`, `panel:` or a command id). +/// Default shortcut of an entry key (`tool:`, `panel:` or a command id) on +/// [`crate::keymap::platform`]. pub fn default_of(key: &str) -> Option<&'static str> { + default_on(key, crate::keymap::platform()) +} + +/// Default shortcut of an entry key on platform `p`. +pub(crate) fn default_on(key: &str, p: craft_keymap::Platform) -> Option<&'static str> { if let Some(t) = key.strip_prefix("tool:") { return vectorcraft_tools::tool_info(t).and_then(|t| t.shortcut); } - if let Some(p) = key.strip_prefix("panel:") { - return PANEL_SHORTCUTS.iter().find(|(id, _)| *id == p).map(|(_, sc)| *sc); + if let Some(panel) = key.strip_prefix("panel:") { + return PANEL_SHORTCUTS.iter().find(|(id, _)| *id == panel).map(|(_, sc)| *sc); } - default_command_shortcut(key) + default_command_shortcut_on(key, p) } /// Effective shortcut of an entry key, honouring the user's overrides. @@ -1000,14 +1017,10 @@ fn names_a_required_field(params: &str) -> bool { !(f.is_empty() || f.starts_with('…') || f[end..].starts_with('=') || f[..end].split('|').all(|n| n.trim().ends_with('?'))) }; let Some(rest) = params.strip_prefix('{') else { return false }; - let (mut depth, mut quoted, mut start) = (0usize, false, 0); - for (i, ch) in rest.char_indices() { + let mut start = 0; + for (i, ch, depth) in outside_quotes(rest) { match ch { - '"' => quoted = !quoted, - _ if quoted => {} - '{' | '[' | '(' => depth += 1, '}' if depth == 0 => return required(&rest[start..i]), - '}' | ']' | ')' => depth = depth.saturating_sub(1), ',' if depth == 0 => { if required(&rest[start..i]) { return true; @@ -1020,6 +1033,29 @@ fn names_a_required_field(params: &str) -> bool { false } +/// Each character of `text` that is not a double quote or inside a pair of them, with its byte +/// offset and the number of `{`, `[` and `(` groups open before it. A closing `}`, `]` or `)` comes +/// with a count that includes the group it closes, and one with no group open counts none. +pub(crate) fn outside_quotes(text: &str) -> impl Iterator + '_ { + let (mut depth, mut quoted) = (0usize, false); + text.char_indices().filter_map(move |(i, ch)| { + if ch == '"' { + quoted = !quoted; + return None; + } + if quoted { + return None; + } + let before = depth; + match ch { + '{' | '[' | '(' => depth += 1, + '}' | ']' | ')' => depth = depth.saturating_sub(1), + _ => {} + } + Some((i, ch, before)) + }) +} + pub fn entry(key: &str) -> Option { entries().iter().find(|e| e.key == key).cloned() } @@ -3094,6 +3130,8 @@ mod tests { assert_eq!(shown("file.new"), Some(("File".into(), "New…".into(), true))); assert_eq!(shown("text.fitHeadline"), Some(("Type".into(), "Fit Headline".into(), false))); assert_eq!(shown("type.fitHeadline"), Some(("Type".into(), "Fit Headline".into(), true))); + assert_eq!(shown("text.convertListToText"), Some(("Type".into(), "Convert to Text".into(), false))); + assert_eq!(shown("type.convertListToText"), Some(("Type › Bullets and Numbering".into(), "Convert to Text".into(), false))); for id in ["file.exportInBackground", "file.openInBackground"] { assert_eq!(shown(id), Some(("File".into(), "Continue in Background".into(), true)), "{id}"); } @@ -3118,6 +3156,26 @@ mod tests { assert!(d.str("__message").contains("was already used by Type › Fit Headline (type.fitHeadline) "), "{}", d.str("__message")); } + /// No two entries of Keyboard Shortcuts have the same name in any UI language: each catalog + /// translates two different English names two different ways. + #[test] + fn no_two_entries_have_the_same_name_in_any_language() { + let all = entries(); + let mut shared = vec![]; + let previous = crate::i18n::current(); + for lang in crate::i18n::Lang::all() { + crate::i18n::set_current(lang); + let mut by_name: HashMap> = HashMap::new(); + for e in all.iter() { + by_name.entry(shown_name(e)).or_default().push(e.key.as_str()); + } + shared.extend(by_name.into_iter().filter(|(_, keys)| keys.len() > 1).map(|(name, keys)| (lang.code(), name, keys))); + } + crate::i18n::set_current(previous); + shared.sort(); + assert!(shared.is_empty(), "{} names: {shared:#?}", shared.len()); + } + /// Two filter plug-ins with the same name in the same menu show their ids, and a third whose /// name is one of those names with the id stays apart from it. A filter with that name in /// another menu, or with a label that differs by its "…", shows no id. diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index 781bec4e74..56bc5ada08 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -539,7 +539,8 @@ fn escape_ends_one_thing(app: &mut VectorcraftApp, ctx: &egui::Context) { if app.session.active().is_some_and(|d| d.doc.pattern_edit.is_some()) { let _ = app.run("object.pattern.done", json!({})); } else if app.session.active().is_some_and(|d| d.isolation.is_some()) { - let _ = app.run("object.exitIsolation", json!({})); + // From an isolated sublayer, Escape leaves isolation mode rather than going up one layer. + let _ = app.run("object.exitIsolation", json!({ "all": true })); } else if app.session.active().is_some_and(|d| d.global_edit.is_some()) { let _ = app.run("select.globalEdit", json!({})); } else if app.ui.flyout.is_some() { diff --git a/crates/ui-egui/src/shortcuts/tests.rs b/crates/ui-egui/src/shortcuts/tests.rs index 4fad102f73..a74bfd8b4a 100644 --- a/crates/ui-egui/src/shortcuts/tests.rs +++ b/crates/ui-egui/src/shortcuts/tests.rs @@ -2693,6 +2693,36 @@ fn the_blend_tool_shortcut_finishes_the_blend() { assert_eq!(app.session.active().unwrap().doc.layers, layers, "no blend was made"); } +/// P, the Pen's shortcut, pressed between clicks while the Pen draws a path ends that path: the Pen +/// stays chosen, the path stays open, and the next click starts a new path. +#[test] +fn the_pen_shortcut_ends_the_path_being_drawn() { + use vectorcraft_tools::{PointerEvent, PointerKind}; + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 600, "height": 300})).unwrap(); + app.select_tool("pen"); + let click = |app: &mut VectorcraftApp, x: f64| { + let v = app.view_info(); + app.session.pointer(&PointerEvent::new(PointerKind::Down, x, 100.0), v).unwrap(); + app.session.pointer(&PointerEvent::new(PointerKind::Up, x, 100.0), v).unwrap(); + }; + let press = |key| egui::Event::Key { key, physical_key: Some(key), pressed: true, repeat: false, modifiers: Modifiers::NONE }; + let anchors = |app: &VectorcraftApp, id| { + let path = app.session.active().unwrap().doc.node(id).and_then(|n| n.path_data()); + path.map(|pd| pd.subpaths.iter().map(|sp| sp.anchors.len()).collect::>()) + }; + click(&mut app, 100.0); + click(&mut app, 200.0); + let first = app.session.active().unwrap().selection.objects[0]; + frame(&mut app, vec![press(Key::P), egui::Event::Text("p".into())]); + assert_eq!(app.session.tool_id(), "pen"); + click(&mut app, 300.0); + assert_eq!(anchors(&app, first), Some(vec![2]), "the path keeps its two anchors"); + let second = app.session.active().unwrap().selection.objects[0]; + assert_ne!(second, first, "the click starts a new path"); + assert_eq!(anchors(&app, second), Some(vec![1])); +} + /// A Blend tool shortcut that arrives only as text (Shift+~ types `~`) also finishes the blend, /// while another tool's shifted shortcut does not. #[test] @@ -3364,3 +3394,27 @@ fn artboard_navigation_commands_can_be_given_keys() { frame(&mut app, press(Key::PageUp)); assert_eq!(at(&app), 1, "Page Up goes to the previous artboard"); } + +/// Ctrl+` (Windows and Linux) chooses the selection tool chosen last; macOS gives the command no +/// default key. Edit › Keyboard Shortcuts lists it, and a chord the user assigns runs it. +#[test] +fn ctrl_backtick_chooses_the_last_selection_tool() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let mac = crate::keymap::platform().is_mac(); + let list = app.run("shortcuts.list", json!({ "query": "tool.selectLastSelection" })).unwrap(); + let listed = list.as_array().unwrap().iter().find(|e| e["id"] == "tool.selectLastSelection").cloned(); + let listed = listed.unwrap_or_else(|| panic!("listed: {list}")); + assert_eq!(listed["label"], "Select Last Selection Tool"); + assert_eq!(listed["default"], if mac { json!(null) } else { json!("Cmd+~") }); + app.select_tool("directSelection"); + app.select_tool("pen"); + frame(&mut app, press(Key::Backtick, cmd())); + assert_eq!(app.session.tool_id(), if mac { "pen" } else { "directSelection" }); + crate::keymap::set_override(&mut app.ui.shortcut_overrides, "tool.selectLastSelection", "Alt+~"); + app.select_tool("groupSelection"); + app.select_tool("rectangle"); + frame(&mut app, press(Key::Backtick, Modifiers::ALT)); + assert_eq!(app.session.tool_id(), "groupSelection", "the user's chord"); + crate::shortcut_editor::sync(&crate::state::UiState::default()); +} diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index ac241a5ebd..8790fc9280 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -101,7 +101,7 @@ pub fn sync_zoom_stops_display_print_size(v: bool) { ZOOM_STOPS_PRINT_SIZE.store(v, Ordering::Relaxed); } -/// Illustrator's preset zoom stops, in percent. +/// The preset zoom stops, in percent. pub const ZOOM_STOPS: [f64; 26] = [ 3.13, 4.17, 6.25, 8.33, 12.5, 16.67, 25.0, 33.33, 50.0, 66.67, 100.0, 150.0, 200.0, 300.0, 400.0, 600.0, 800.0, 1200.0, 1600.0, 2400.0, 3200.0, 4800.0, 6400.0, 12800.0, 25600.0, 64000.0, @@ -135,7 +135,7 @@ pub fn next_zoom_with_display(z: f64, up: bool, display_print_size: bool) -> f64 zoom_from_display_percent(stop, display_print_size) } -/// Format like Illustrator's tab/zoom field: up to 2 decimals, no trailing zeros. +/// Format for the tab/zoom field: up to 2 decimals, no trailing zeros. pub fn zoom_label(z: f64, display_print_size: bool) -> String { let s = format!("{:.2}", zoom_display_percent(z, display_print_size)); let s = s.trim_end_matches('0').trim_end_matches('.'); @@ -225,12 +225,15 @@ pub const ICON_PANELS: &[(&str, &str, &str)] = &[ (crate::panels::variables::ID, "Variables", "chart-column"), (crate::panels::script_console::ID, "Script Console", "message-circle"), (crate::panels::learn::ID, "Learn", "graduation-cap"), + (crate::panels::discover::ID, "VectorCraft Help…", "search"), (crate::addons::cleanup::ID, "Artwork Cleanup", "sparkles"), (crate::addons::color::ID, "Color Effects", "sun"), (crate::addons::packaging::ID, "Fold Lines", "scissors"), + (crate::addons::packaging::preview::ID, "Fold Preview", "box"), (crate::addons::pathtools::ID, "Anchor Inspector", "dc-anchor-smooth"), (crate::addons::pathtools::shape::ID, "Parametric Shape", "hexagon"), (crate::addons::pen::ID, "Smart Pen", "spline-pointer"), + (crate::addons::units::ID, "Unit Converter", "ruler"), ]; /// Groups of icon panels separated by dividers in the collapsed column. @@ -418,9 +421,16 @@ pub struct UiState { /// Type › Find Font…'s last Find In choice (`find_font::FIND_IN`), kept while the app runs. #[serde(skip)] pub find_font_in: String, + /// Ellipse Properties' Constrain Pie Angle link (Transform and Properties panels): a Pie Start + /// or End Angle typed while it is on keeps each selected ellipse's pie span. Kept while the app + /// runs; off at every launch. + #[serde(skip)] + pub constrain_pie_angle: bool, /// The Learn panel's tab, skill and tutorial, kept while the app runs. #[serde(skip)] pub learn: crate::panels::learn::View, + #[serde(skip)] + pub discover: crate::panels::discover::View, /// The tool whose place a Learn tutorial step's link shows (`learn.locateTool`), while its mark /// is on screen. Not saved. #[serde(skip)] @@ -454,7 +464,7 @@ pub struct UiState { pub toolbar_advanced: bool, #[serde(default = "yes")] pub task_bar: bool, - /// Where the Contextual Task Bar was dragged or pinned. Not saved, as in Illustrator: the bar + /// Where the Contextual Task Bar was dragged or pinned. Not saved: the bar /// starts under the selection at every launch. #[serde(skip)] pub task_bar_place: TaskBarPlace, @@ -542,7 +552,9 @@ pub struct UiState { pub toolbar_pos: Option<[f32; 2]>, /// The docked Tools panel sits between the left-side panels and the canvas instead of at the /// window's left edge (Window › Toolbars › Keep Tools Beside the Canvas, - /// `window.toolsBesideCanvas`). Off by default, and off in state saved without it. + /// `window.toolsBesideCanvas`). Dropping Tools on the canvas's left edge, right of panels docked + /// on the left, turns it on, and on the window's left edge turns it off; with no panels docked on + /// the left, a drop leaves it as it is. Off by default, and off in state saved without it. #[serde(default)] pub tools_beside_canvas: bool, /// The docked Tools panel stands on the right, between the canvas and the panels, instead of on @@ -603,6 +615,10 @@ pub struct UiState { /// Consolidate All Windows. Not saved: the reference app does not save windows with a document. #[serde(skip)] pub tiled: bool, + /// How Tile lays the panes out: in a grid, side by side, stacked, or 2-up to 6-up. Not saved, + /// as `tiled` is not. + #[serde(skip)] + pub tile_layout: crate::canvas::TileLayout, /// Window › Arrange › Float in Window, Float All in Windows and Cascade: the documents in /// floating windows of their own, out of the tab strip, until Consolidate All Windows. Not /// saved, as `tiled` is not. @@ -712,6 +728,10 @@ pub struct UiState { /// Flattener Preview panel: highlight, overprints, preset and options (`ui.flattenerPreview`). #[serde(default)] pub flattener_preview: crate::panels::flattener_preview::Settings, + /// Fold Preview window: fold amount, view, zoom, perspective, inside color, fold lines and + /// base panel (`ui.foldPreview`). + #[serde(default)] + pub fold_preview: crate::addons::packaging::preview::Settings, /// Color Guide panel: Limit to Library, a swatch library id, "document" (the document's /// swatches) or "" (none) (`ui.colorGuideLimit`). #[serde(default)] @@ -751,6 +771,10 @@ pub struct UiState { /// of an RGB field, `ui.colorPanel`, [`crate::panels::color::deserialize_rgb_percent`]). #[serde(default, deserialize_with = "crate::panels::color::deserialize_rgb_percent")] pub color_rgb_percent: bool, + /// Color Wheel panel: the wheel or the box, and the box's channel (`ui.colorWheel`, + /// [`crate::panels::color_wheel::deserialize_settings`]). + #[serde(default, deserialize_with = "crate::panels::color_wheel::deserialize_settings")] + pub color_wheel: crate::panels::color_wheel::Settings, /// Swatches panel: Show Recent Colors in its panel menu, which draws the panel's Recent Colors /// row (#6617; read as [`Self::color_show_recent_colors`] is). Separate from the Color panel's. #[serde(default = "yes", deserialize_with = "crate::panels::color::deserialize_show_recent_colors")] @@ -832,6 +856,11 @@ pub struct UiState { /// them (#1732). #[serde(default)] pub transform_each: Value, + /// The Expand choices OK last expanded with in this run of the app (object, fill, stroke, + /// gradient, steps; null: none yet): the Expand dialog opens on them, and Object › Expand… + /// chosen with Alt (Option) expands with them at once. They are not kept across launches. + #[serde(skip)] + pub expand_options: Value, /// The spacing used the last time Rearrange All Artboards was confirmed. #[serde(default)] pub rearrange_artboards_spacing: Value, @@ -854,7 +883,8 @@ pub struct UiState { /// Layers panel › Panel Options… (row size, thumbnails, Show Layers Only, Locate Selected Objects). #[serde(default)] pub layers_panel: crate::panels::layers::PanelOptions, - /// Navigator panel › Panel Options… (the view box color, Draw Dashed Lines as Solid Lines). + /// Navigator panel › Panel Options… (the view box color, Draw Dashed Lines as Solid Lines) and + /// the panel menu's View Artboard Contents Only. #[serde(default)] pub navigator_panel: crate::panels::navigator::PanelOptions, /// The Layers panel's Filter (`ui.layersFilter`). It is not saved and lasts the session, as the @@ -1153,7 +1183,9 @@ impl Default for UiState { transient_focus: false, color_settings_scroll: false, find_font_in: String::new(), + constrain_pie_angle: false, learn: Default::default(), + discover: Default::default(), learn_locate: None, learn_practice: Default::default(), learn_progress: Default::default(), @@ -1211,6 +1243,7 @@ impl Default for UiState { palette_query: String::new(), screen_mode: 0, tiled: false, + tile_layout: crate::canvas::TileLayout::Grid, floating: Vec::new(), tab_document: None, draw_mode: 0, @@ -1241,6 +1274,7 @@ impl Default for UiState { color_guide: Default::default(), library_panels: vec![], flattener_preview: Default::default(), + fold_preview: Default::default(), color_guide_limit: String::new(), color_guide_base: None, color_guide_spot: None, @@ -1250,6 +1284,7 @@ impl Default for UiState { color_hide_options: false, color_show_recent_colors: true, color_rgb_percent: false, + color_wheel: Default::default(), swatches_show_recent_colors: true, svg_options: Value::Null, place_link: true, @@ -1271,6 +1306,7 @@ impl Default for UiState { simplify: Value::Null, move_options: Value::Null, transform_each: Value::Null, + expand_options: Value::Null, rearrange_artboards_spacing: Value::Null, dxf_import: Value::Null, psd_import: Value::Null, diff --git a/crates/ui-egui/src/sysclip.rs b/crates/ui-egui/src/sysclip.rs index 7285d2acf2..1ef9a20e6a 100644 --- a/crates/ui-egui/src/sysclip.rs +++ b/crates/ui-egui/src/sysclip.rs @@ -103,6 +103,13 @@ pub(crate) struct Publishing { /// The latest one's formats could not be written: what the system clipboard held when the /// write failed, and the text of those formats. unwritten: Option<(Held, String)>, + /// The status bar's message when the latest one ran, with [`crate::state::UiState::status_sets`] + /// then. Its formats' notes replace the message only while the status bar still shows it and + /// nothing has set the status since. + status: (String, u64), + /// The status bar's message the latest Copy or Cut with notes left, with + /// [`crate::state::UiState::status_sets`] then. + notes_status: Option<(String, u64)>, } impl Publishing { @@ -116,6 +123,45 @@ impl Publishing { pub(crate) fn latest(&self) -> u64 { self.latest.load(Ordering::SeqCst) } + + /// `ui`'s status bar message is the one the latest Copy or Cut left, which its formats' notes + /// may replace. + pub(crate) fn ran_with_status(&mut self, ui: &crate::state::UiState) { + ui.status.clone_into(&mut self.status.0); + self.status.1 = ui.status_sets; + } + + /// Does `ui`'s status bar still show the message the latest Copy or Cut left, with nothing + /// setting the status since? + fn shows_status(&self, ui: &crate::state::UiState) -> bool { + ui.status == self.status.0 && ui.status_sets == self.status.1 + } +} + +/// The status bar's line after a Copy (or with `cut`, a Cut) whose formats have `n` notes, the +/// first of them `first`. +pub(crate) fn copied_with_notes(cut: bool, n: usize, first: &str) -> String { + let (one, other) = if cut { + ("Cut with {n} note: {first}", "Cut with {n} notes: {first}") + } else { + ("Copied with {n} note: {first}", "Copied with {n} notes: {first}") + }; + crate::i18n::msg_n(n as u64, one, other, &[("first", first)]) +} + +/// Show a Copy's (or with `cut`, a Cut's) formats' `notes` in the status bar: the first of them +/// and how many there are, with the rest for the message's hover. Without notes, the message an +/// earlier Copy's or Cut's notes left is cleared while nothing has set the status since, and any +/// other message stays. +pub(crate) fn show_copy_notes(app: &mut VectorcraftApp, cut: bool, notes: Vec) { + let left = app.clipboard_publishing.notes_status.take(); + let Some(first) = notes.first() else { + crate::io::clear_notes_left(app, left); + return; + }; + let status = copied_with_notes(cut, notes.len(), first); + crate::io::show_with_notes(app, status, notes); + app.clipboard_publishing.notes_status = Some((app.ui.status.clone(), app.ui.status_sets)); } /// Does a flavour of type `mime` load with `clipboard.importImage` ([`import_command`])? @@ -172,14 +218,18 @@ impl VectorcraftApp { /// ([`Self::drop_formats_after_egui_copy`]), drops the formats not written yet. While the /// latest Copy or Cut's formats wait to be written, Paste takes the internal clipboard, and /// while a text field or type has the keyboard the app waits for them - /// ([`Self::write_formats_before_text_input`]). Once they are written, the status bar shows - /// the first of the PNG's and PDF's warnings. - pub(crate) fn publish_clipboard(&mut self) { + /// ([`Self::write_formats_before_text_input`]). Once they are written, while the status bar + /// still shows the message the Copy or Cut (`cut`) left ([`Publishing::ran_with_status`]), it + /// shows the first of the PNG's and PDF's notes and how many there are; hovering the message + /// lists them ([`crate::io::show_with_notes`]). + pub(crate) fn publish_clipboard(&mut self, cut: bool) { // Ruler guides copied alone stay in VectorCraft, but the Copy still replaces what the // system clipboard held: it is emptied, so the next Paste takes the guides rather than // what another app copied before, and what another app copies after still wins (#3226). if !self.session.clipboard.has_art() { self.clear_system_clipboard(); + // Guides have no formats, so this Copy or Cut has no notes. + show_copy_notes(self, cut, vec![]); return; } if self.services.system_clipboard.is_none() { @@ -197,6 +247,7 @@ impl VectorcraftApp { let n = latest.fetch_add(1, Ordering::SeqCst).wrapping_add(1); self.clipboard_publishing.pending = true; self.clipboard_publishing.unwritten = None; + self.clipboard_publishing.ran_with_status(&self.ui); // What the clipboard holds at the Copy or Cut: a copy made elsewhere before the write is newer. let before = self.services.system_clipboard.as_deref_mut().map(Held::now); let (tx, made) = channel(); @@ -245,11 +296,11 @@ impl VectorcraftApp { }); match written { Err(e) => app.ui.status = format!("Couldn't copy to the system clipboard: {e}"), - // Show the first of the PNG's and PDF's warnings (an image that couldn't be decoded, - // type in the fallback font). + // The PNG's and PDF's notes (an image that couldn't be decoded, type in the + // fallback font), unless another message has replaced the Copy or Cut's since. Ok(warnings) => { - if let Some(first) = warnings.into_iter().next() { - app.ui.status = first; + if app.clipboard_publishing.shows_status(&app.ui) { + show_copy_notes(app, cut, warnings); } } } diff --git a/crates/ui-egui/src/tests/automation.rs b/crates/ui-egui/src/tests/automation.rs index 541e78ff39..7a904e4646 100644 --- a/crates/ui-egui/src/tests/automation.rs +++ b/crates/ui-egui/src/tests/automation.rs @@ -1270,22 +1270,26 @@ fn ui_inspect_keeps_text_that_only_looks_like_a_library_id() { let _ = std::fs::remove_dir_all(base); } -/// `ui.inspect`'s `scriptReport` names a file the person's script wrote outside the read root, and -/// the included file a failed run stopped in (also in its error line), by its file name; the person -/// sees the paths. +/// `ui.inspect`'s `scriptReport` names a file the person's script wrote outside the read root (in +/// the folder the person allowed it), and the included file a failed run stopped in (also in its +/// error line), by its file name; the person sees the paths. #[test] fn ui_inspect_script_report_leaves_out_files_outside_the_read_root() { let (mut app, tx, base) = confined("inspect-script-report"); let (kept, hidden) = (s(base.join("in/kept.svg")), s(base.join("outside/hidden.svg"))); app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); let source = format!( - "vc.run('document.export', {{path: {kept}, format: 'svg'}}); vc.run('document.export', {{path: {hidden}, format: 'svg'}});", + "Folder.selectDialog('Folder'); vc.run('document.export', {{path: {kept}, format: 'svg'}}); vc.run('document.export', {{path: {hidden}, format: 'svg'}});", kept = json!(kept), hidden = json!(hidden) ); let finish = |app: &mut VectorcraftApp, params: Value| { app.session.execute("script.run", ¶ms).unwrap(); for _ in 0..10_000 { + if app.session.script_picker().is_some() { + let paths = vec![s(base.clone())]; + assert!(app.session.script_pick(vectorcraft_engine::script::files::PickAnswer::Allow { paths, always: false })); + } if app.session.script_pump().is_some() { break; } diff --git a/crates/ui-egui/src/tests/picks.rs b/crates/ui-egui/src/tests/picks.rs index 9d4ae15493..5d96a14fa6 100644 --- a/crates/ui-egui/src/tests/picks.rs +++ b/crates/ui-egui/src/tests/picks.rs @@ -53,6 +53,7 @@ pub(crate) fn off_the_ui_thread(services: &mut Services) -> (Shown, Written) { services.pick_open = Some(Box::new(in_line)); services.pick_save = Some(Box::new(in_line)); services.pick_open_multi = Some(Box::new(|| panic!("no dialog on the UI thread"))); + services.pick_open_files = Some(Box::new(|_: &FilePick| panic!("no dialog on the UI thread"))); services.pick_folder = Some(Box::new(|| panic!("no dialog on the UI thread"))); services.read = Some(Box::new(|_: &str| Ok(SVG.to_vec()))); services.write = Some(Box::new(move |path: &str, _: &[u8]| { @@ -1168,11 +1169,11 @@ fn without_tests(code: &str) -> String { } /// The calls in `code` (from [`code_only`]) of the host's in-line dialogs: [`Services`]' -/// `pick_open`, `pick_save`, `pick_folder` and `pick_open_multi` used other than to ask whether -/// the host has them (`.is_some()`, `.is_none()`). +/// `pick_open`, `pick_save`, `pick_folder`, `pick_folder_at`, `pick_open_multi` and +/// `pick_open_files` used other than to ask whether the host has them (`.is_some()`, `.is_none()`). fn in_line_dialogs(code: &str) -> Vec { let mut found = vec![]; - for name in ["pick_open", "pick_save", "pick_folder", "pick_open_multi"] { + for name in ["pick_open", "pick_save", "pick_folder", "pick_folder_at", "pick_open_multi", "pick_open_files"] { let field = format!(".{name}"); let mut rest = code; while let Some(at) = rest.find(&field) { diff --git a/crates/ui-egui/src/tests/recolor.rs b/crates/ui-egui/src/tests/recolor.rs index f4d2d6e85a..0d5bacd77c 100644 --- a/crates/ui-egui/src/tests/recolor.rs +++ b/crates/ui-egui/src/tests/recolor.rs @@ -1585,3 +1585,29 @@ fn row_context_menu_pick_from_swatches_and_limit_to_library() { assert_eq!(colors(h.state_mut()), 2, "Recolor Cancel restores the original artwork"); } } + +/// With the Color Groups list shown, the Color Picker opened from a row and closed with Cancel +/// leaves Recolor Artwork the size it was and where it was, in every frame. +#[test] +fn the_color_picker_leaves_the_dialog_in_place() { + use egui::accesskit::Role; + + let mut app = app(); + art(&mut app, &["#ff0000", "#0000ff"]); + let mut h = assign_harness(app, json!({})); + assert_eq!(field(h.state(), "groupStorage"), json!(true), "the list is shown"); + let window = egui::Id::unique(("dialog", "recolor")); + let rect = |h: &egui_kittest::Harness<'_, VectorcraftApp>| h.ctx.memory(|m| m.area_rect(window)); + let before = rect(&h).expect("dialog drawn"); + row_context_menu(&mut h, 1); + h.get_by_label(" Pick from Swatches").click(); + h.run_steps(3); + assert_eq!(h.state().ui.dialog.as_ref().map(|d| d.kind.as_str()), Some("colorPicker")); + assert_eq!(rect(&h), Some(before), "the dialog keeps its size while the picker is open"); + h.get_by_role_and_label(Role::Button, "Cancel").click(); + for step in 0..4 { + h.run_steps(1); + assert_eq!(rect(&h), Some(before), "frame {step} after Cancel"); + } + assert_eq!(h.state().ui.dialog.as_ref().map(|d| d.kind.as_str()), Some("recolor")); +} diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index 08ac8e1917..fee27caa13 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -267,9 +267,13 @@ fn a_stop_names_the_files_the_run_left_written() { let dir = folder("written"); let path = dir.join("out.svg"); let p = path.to_string_lossy().into_owned(); - let source = format!("vc.run('document.export', {{path: {p:?}, format: 'svg'}}); while (true) {{}}"); + let source = format!("Folder.selectDialog('Folder'); vc.run('document.export', {{path: {p:?}, format: 'svg'}}); while (true) {{}}"); menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap(); script_runs::poll(&mut app); + assert!(app.session.script_picker().is_some(), "the run waits at its folder dialog"); + let paths = vec![dir.to_string_lossy().into_owned()]; + assert!(app.session.script_pick(vectorcraft_engine::script::files::PickAnswer::Allow { paths, always: false })); + script_runs::poll(&mut app); assert!(path.exists()); app.ui.dialog = Some(crate::state::Dialog::new(dialogs::script_run::CLOSE_KIND, json!({}))); confirm(&mut app).unwrap(); @@ -277,6 +281,365 @@ fn a_stop_names_the_files_the_run_left_written() { let _ = std::fs::remove_dir_all(&dir); } +/// While a run waits at its file dialog, the app's frame logic does not ask for a frame on every +/// frame. +#[test] +fn a_run_waiting_at_its_file_dialog_lets_the_app_idle() { + let mut app = app(); + app.session.prefs.show_external_script_warning = false; + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": "Folder.selectDialog('Folder');" })).unwrap().unwrap(); + script_runs::poll(&mut app); + assert!(app.session.script_picker().is_some(), "the run waits at its folder dialog"); + let ctx = egui::Context::default(); + let mut wait = std::time::Duration::ZERO; + for frame in 0..4 { + let time = f64::from(frame); + app.now_override = Some(time); + let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0))); + let raw = egui::RawInput { screen_rect, time: Some(time), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| app.logic(ui.ctx())); + out.textures_delta.clear(); + wait = out.viewport_output.get(&egui::ViewportId::ROOT).map_or(std::time::Duration::MAX, |v| v.repaint_delay); + } + assert!(app.session.script_picker().is_some(), "the run still waits"); + assert!(wait > std::time::Duration::from_millis(100), "{wait:?}: {:?}", ctx.repaint_causes()); + assert!(app.session.script_request_stop()); + finish(&mut app); +} + +/// A script's open dialog with `multiSelect` shows the host's dialog for several files, with the +/// file types of the script's filter, and the script gets every file picked. +#[test] +fn a_scripts_open_dialog_picks_several_files_of_its_types() { + let asked = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); + let dir = folder("several"); + let paths: Vec = ["a.txt", "b.txt"].iter().map(|n| dir.join(n).to_string_lossy().into_owned()).collect(); + for p in &paths { + std::fs::write(p, "x").unwrap(); + } + let (seen, given) = (asked.clone(), paths.clone()); + let services = crate::Services { + pick_open: Some(Box::new(|_: &crate::FilePick| panic!("the dialog for one file"))), + pick_open_files: Some(Box::new(move |pick: &crate::FilePick| { + seen.borrow_mut().push(pick.filters.clone()); + given.clone() + })), + ..Default::default() + }; + let mut app = VectorcraftApp::new(Session::new(), services); + app.run("file.new", json!({})).unwrap(); + app.session.prefs.show_external_script_warning = false; + let source = "var f = File.openDialog('Pick', 'Text:*.txt;All files:*.*', true); vc.log([f.length, f[0].name, f[1].name]);"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap(); + script_runs::poll(&mut app); + let mut d = app.ui.dialog.take().expect("the script's file dialog"); + assert_eq!(d.kind, dialogs::script_run::PICKER_KIND); + dialogs::script_run::choose(&mut app, &mut d); + assert_eq!(*asked.borrow(), vec![vec![("Text".to_string(), vec!["txt".to_string()]), ("All files".to_string(), vec!["*".to_string()])]]); + assert_eq!(app.script_picked, paths); + d.fields.insert("answer".into(), json!("once")); + app.ui.dialog = Some(d); + confirm(&mut app).unwrap(); + finish(&mut app); + assert_eq!(app.session.script_report().unwrap()["log"], json!([[2, "a.txt", "b.txt"]])); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A folder's `selectDlg` asks the host for a folder picker that starts in that folder, and +/// `Folder.selectDialog` for one that starts where the host starts it. +#[test] +fn a_scripts_folder_dialog_starts_in_the_folder_it_was_asked_from() { + let dir = folder("selectstart"); + let requests = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); + let seen = requests.clone(); + let picked = dir.to_string_lossy().into_owned(); + let services = crate::Services { + start_pick: Some(Box::new(move |request: crate::picks::PickRequest| { + seen.borrow_mut().push(request); + None + })), + pick_folder: Some(Box::new(move || Some(picked.clone()))), + ..Default::default() + }; + let mut app = VectorcraftApp::new(Session::new(), services); + app.run("file.new", json!({})).unwrap(); + app.session.prefs.show_external_script_warning = false; + let source = format!( + "var a = new Folder({:?}).selectDlg('Pick'); var b = Folder.selectDialog('Pick'); vc.log([a !== null, b !== null]);", + dir.to_string_lossy() + ); + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap(); + for _ in 0..2 { + script_runs::poll(&mut app); + let mut d = app.ui.dialog.take().expect("the script's file dialog"); + assert_eq!(d.kind, dialogs::script_run::PICKER_KIND); + dialogs::script_run::choose(&mut app, &mut d); + d.fields.insert("answer".into(), json!("once")); + app.ui.dialog = Some(d); + confirm(&mut app).unwrap(); + } + finish(&mut app); + let start = app.session.script_report().map(|r| r["log"].clone()); + assert_eq!(start, Some(json!([[true, true]]))); + let r = requests.borrow(); + let starts_in_dir = |s: &str| std::fs::canonicalize(s).ok() == std::fs::canonicalize(&dir).ok(); + assert!(matches!(&r[..], [crate::picks::PickRequest::FolderAt(s), crate::picks::PickRequest::Folder] if starts_in_dir(s)), "{r:?}"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Where the host shows file dialogs in line (Windows), a folder's `selectDlg` also opens the +/// folder picker in that folder, and `Folder.selectDialog` the one that starts where the host +/// starts it. +#[test] +fn a_scripts_folder_dialog_shown_in_line_starts_in_the_folder_it_was_asked_from() { + let dir = folder("selectstartinline"); + let shown = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); + let (at, plain) = (shown.clone(), shown.clone()); + let (picked_at, picked) = (dir.to_string_lossy().into_owned(), dir.to_string_lossy().into_owned()); + let services = crate::Services { + pick_folder_at: Some(Box::new(move |start: &str| { + at.borrow_mut().push(Some(start.to_string())); + Some(picked_at.clone()) + })), + pick_folder: Some(Box::new(move || { + plain.borrow_mut().push(None); + Some(picked.clone()) + })), + ..Default::default() + }; + let mut app = VectorcraftApp::new(Session::new(), services); + app.run("file.new", json!({})).unwrap(); + app.session.prefs.show_external_script_warning = false; + let source = format!( + "var a = new Folder({:?}).selectDlg('Pick'); var b = Folder.selectDialog('Pick'); vc.log([a !== null, b !== null]);", + dir.to_string_lossy() + ); + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap(); + for _ in 0..2 { + script_runs::poll(&mut app); + let mut d = app.ui.dialog.take().expect("the script's file dialog"); + assert_eq!(d.kind, dialogs::script_run::PICKER_KIND); + dialogs::script_run::choose(&mut app, &mut d); + d.fields.insert("answer".into(), json!("once")); + app.ui.dialog = Some(d); + confirm(&mut app).unwrap(); + } + finish(&mut app); + assert_eq!(app.session.script_report().map(|r| r["log"].clone()), Some(json!([[true, true]]))); + let r = shown.borrow(); + let starts_in_dir = |s: &str| std::fs::canonicalize(s).ok() == std::fs::canonicalize(&dir).ok(); + assert!(matches!(&r[..], [Some(s), None] if starts_in_dir(s)), "{r:?}"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A control request, handled as the app handles one: while `answering_control` is set. +fn control(app: &mut VectorcraftApp, method: &str, params: Value) -> Value { + let (req, _) = crate::control::ControlRequest::new(method, params); + app.ui.answering_control = true; + let outcome = crate::control::handle(app, &egui::Context::default(), &req); + app.ui.answering_control = false; + let crate::control::Outcome::Done(r) = outcome else { panic!("expected an immediate reply") }; + r +} + +const BY_PERSON: &str = "Only the person at the keyboard can allow a script's file access"; + +/// The paths a script's file dialog allows come from Choose… alone: `ui.dialog.set` cannot set +/// them, and fields set on the dialog do not let Always Allow keep a grant the run cannot keep. +#[test] +fn a_scripts_file_dialog_takes_no_paths_from_automation() { + let dir = folder("automated"); + let secret = dir.join("secret.txt"); + std::fs::write(&secret, "secret").unwrap(); + let mut app = app(); + app.session.prefs.show_external_script_warning = false; + let source = "var f = File.openDialog('Pick'); vc.log(f === null ? null : f.fsName);"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap(); + script_runs::poll(&mut app); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(dialogs::script_run::PICKER_KIND)); + let p = secret.to_string_lossy().into_owned(); + let r = control(&mut app, "ui.dialog.set", json!({"field": "paths", "value": [p]})); + assert!(r["error"].as_str().is_some_and(|e| e.contains("no field `paths`")), "{r}"); + let always = json!({"fields": [{"field": "canAlways", "value": true}, {"field": "answer", "value": "always"}], "action": "confirm"}); + let r = control(&mut app, "ui.dialog.set", always.clone()); + assert_eq!(r["error"], BY_PERSON, "{r}"); + let d = app.ui.dialog.as_mut().expect("the dialog stays open"); + d.fields.insert("answer".into(), json!("once")); + assert_eq!(confirm(&mut app).unwrap_err(), "choose a file or folder first, or deny"); + app.script_picked = vec![p]; + let r = control(&mut app, "ui.dialog.set", always); + assert_eq!(r["error"], BY_PERSON, "{r}"); + let d = app.ui.dialog.as_mut().expect("the dialog stays open"); + d.fields.insert("canAlways".into(), json!(true)); + d.fields.insert("answer".into(), json!("always")); + assert_eq!(confirm(&mut app).unwrap_err(), "this script's file access can be allowed only once"); + let r = control(&mut app, "ui.dialog.set", json!({"fields": [{"field": "answer", "value": "deny"}], "action": "confirm"})); + assert!(r.get("error").is_none_or(Value::is_null), "{r}"); + finish(&mut app); + assert_eq!(app.session.script_report().unwrap()["log"], json!([null])); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Allow Once and Always Allow This Script are taken only from the person at the keyboard: a control +/// request and synthetic input are refused and the dialog stays open, after a person picked a file +/// with Choose… too, while Deny from automation is taken. +#[test] +fn a_scripts_file_access_is_allowed_only_by_the_person() { + let dir = folder("byperson"); + let picked = dir.join("picked.txt"); + std::fs::write(&picked, "picked").unwrap(); + let mut app = app(); + app.session.prefs.show_external_script_warning = false; + let source = "var f = File.openDialog('Pick'); vc.log(f === null ? null : f.name);"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap(); + script_runs::poll(&mut app); + app.script_picked = vec![picked.to_string_lossy().into_owned()]; + let r = control(&mut app, "ui.dialog.set", json!({"fields": [{"field": "answer", "value": "once"}], "action": "confirm"})); + assert_eq!(r["error"], BY_PERSON, "{r}"); + assert!(app.session.script_picker().is_some(), "the run still waits"); + let r = control(&mut app, "ui.dialog.set", json!({"fields": [{"field": "answer", "value": "deny"}], "action": "confirm"})); + assert!(r.get("error").is_none_or(Value::is_null), "Deny is taken from automation: {r}"); + finish(&mut app); + assert_eq!(app.session.script_report().unwrap()["log"], json!([null])); + + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap(); + script_runs::poll(&mut app); + app.script_picked = vec![picked.to_string_lossy().into_owned()]; + app.ui.dialog.as_mut().expect("the file dialog").fields.insert("answer".into(), json!("once")); + app.synthetic_frame = true; + assert_eq!(confirm(&mut app).unwrap_err(), BY_PERSON); + app.synthetic_frame = false; + assert!(app.session.script_picker().is_some(), "the run still waits"); + confirm(&mut app).unwrap(); + finish(&mut app); + assert_eq!(app.session.script_report().unwrap()["log"], json!(["picked.txt"])); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The texts the dialog layer draws, once a few frames have let it settle. +fn dialog_texts(app: &mut VectorcraftApp) -> Vec { + fn texts(s: &egui::Shape, out: &mut Vec) { + match s { + egui::Shape::Text(t) => out.push(t.galley.text().to_string()), + egui::Shape::Vec(v) => v.iter().for_each(|s| texts(s, out)), + _ => {} + } + } + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut v = vec![]; + for _ in 0..3 { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| dialogs::show(app, ui.ctx())); + out.textures_delta.clear(); + v.clear(); + out.shapes.iter().for_each(|c| texts(&c.shape, &mut v)); + } + v +} + +/// The dialog says what the run asks for and shows the script's prompt, also after `ui.dialog.set` +/// changed the dialog's `kind` and `prompt` fields. +#[test] +fn a_scripts_file_dialog_says_what_the_run_asks_for() { + let mut app = app(); + app.session.prefs.show_external_script_warning = false; + let source = "vc.log(Folder.selectDialog('Pick the export folder'));"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap(); + script_runs::poll(&mut app); + let r = + control(&mut app, "ui.dialog.set", json!({"fields": [{"field": "kind", "value": "open"}, {"field": "prompt", "value": "Nothing to see"}]})); + assert!(r.get("error").is_none_or(Value::is_null), "{r}"); + let texts = dialog_texts(&mut app); + let folder = "The script asks to read and write a folder you choose, with everything in it."; + assert!(texts.iter().any(|t| t == folder), "{texts:?}"); + assert!(texts.iter().any(|t| t == "Pick the export folder"), "{texts:?}"); + assert!(!texts.iter().any(|t| t == "Nothing to see" || t == "The script asks to read a file you choose."), "{texts:?}"); + dialogs::cancel(&mut app); + finish(&mut app); +} + +/// Enter in the file dialog gives Deny, its default answer, also after the person picked a folder. +#[test] +fn enter_in_a_scripts_file_dialog_denies() { + let mut app = app(); + app.session.prefs.show_external_script_warning = false; + let source = "vc.log(Folder.selectDialog('Pick'));"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap(); + script_runs::poll(&mut app); + let dir = folder("enterdeny"); + app.script_picked = vec![dir.to_string_lossy().into_owned()]; + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let enter = egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + for events in [vec![], vec![], vec![enter]] { + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| dialogs::show(&mut app, ui.ctx())); + out.textures_delta.clear(); + } + assert!(app.ui.dialog.as_ref().is_none_or(|d| d.kind != dialogs::script_run::PICKER_KIND), "the dialog closes"); + finish(&mut app); + assert_eq!(app.session.script_report().unwrap()["log"], json!([null])); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Enter on the file dialog's focused Choose… button goes to that button, which opens the folder +/// picker once, and does not deny. +#[test] +fn enter_on_a_focused_choose_button_does_not_deny() { + let asked = std::rc::Rc::new(std::cell::Cell::new(0usize)); + let counted = asked.clone(); + let pick_folder: Box Option> = Box::new(move || { + counted.set(counted.get() + 1); + None + }); + let mut app = VectorcraftApp::new(Session::new(), crate::Services { pick_folder: Some(pick_folder), ..Default::default() }); + app.run("file.new", json!({})).unwrap(); + app.session.prefs.show_external_script_warning = false; + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": "vc.log(Folder.selectDialog('Pick'));" })).unwrap().unwrap(); + script_runs::poll(&mut app); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let key = |key| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + let frame = |app: &mut VectorcraftApp, events| { + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| dialogs::show(app, ui.ctx())); + out.textures_delta.clear(); + }; + for events in [vec![], vec![], vec![key(egui::Key::Tab)], vec![]] { + frame(&mut app, events); + } + assert!(ctx.memory(|m| m.focused().is_some()), "Tab gives a button the keyboard focus"); + assert_eq!(asked.get(), 0); + frame(&mut app, vec![key(egui::Key::Enter)]); + frame(&mut app, vec![]); + assert_eq!(asked.get(), 1, "Enter chose the focused Choose… button"); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(dialogs::script_run::PICKER_KIND), "the dialog stays open"); + assert!(app.session.script_picker().is_some(), "the run still waits"); + dialogs::cancel(&mut app); + finish(&mut app); +} + +/// Choose… keeps at most the 2,048 files a script is given, and the dialog says the files picked +/// after them were left out. +#[test] +fn a_scripts_file_dialog_keeps_at_most_2048_picked_files() { + let given: Vec = (0..2050).map(|n| format!("/picked/{n}.txt")).collect(); + let all = given.clone(); + let services = crate::Services { pick_open_files: Some(Box::new(move |_: &crate::FilePick| all.clone())), ..Default::default() }; + let mut app = VectorcraftApp::new(Session::new(), services); + app.run("file.new", json!({})).unwrap(); + app.session.prefs.show_external_script_warning = false; + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": "File.openDialog('Pick', '', true);" })).unwrap().unwrap(); + script_runs::poll(&mut app); + let mut d = app.ui.dialog.take().expect("the script's file dialog"); + dialogs::script_run::choose(&mut app, &mut d); + app.ui.dialog = Some(d); + assert_eq!(app.script_picked, given[..2048]); + let texts = dialog_texts(&mut app); + let note = "A script is given at most 2,048 files: the files picked after them were left out"; + assert!(texts.iter().any(|t| t == note), "{texts:?}"); + dialogs::cancel(&mut app); + finish(&mut app); +} + #[test] fn a_new_app_shows_the_warning_by_default() { assert!(Session::new().prefs.show_external_script_warning); diff --git a/crates/ui-egui/src/tests/scripts_menu.rs b/crates/ui-egui/src/tests/scripts_menu.rs index 7cfa5fe2b5..93f0117eb8 100644 --- a/crates/ui-egui/src/tests/scripts_menu.rs +++ b/crates/ui-egui/src/tests/scripts_menu.rs @@ -80,19 +80,22 @@ fn finish(app: &mut VectorcraftApp) { const DRAW: &str = "vc.run('shape.rectangle', {x:0,y:0,width:10,height:10}); vc.run('shape.rectangle', {x:20,y:0,width:10,height:10});"; +/// The items File › Scripts always ends with. +const FIXED: &str = "Check Script…, Other Script…"; + #[test] fn the_folders_scripts_are_listed_above_check_script_and_other_script() { let dir = folder("listed"); let app = app(&dir); - assert_eq!(shape(&scripts()), "Check Script…, Other Script…", "before the first listing"); + assert_eq!(shape(&scripts()), FIXED, "before the first read"); read(&app); - assert_eq!(shape(&scripts()), "Check Script…, Other Script…", "an empty folder"); + assert_eq!(shape(&scripts()), FIXED, "an empty folder"); let draw = write(&dir, "Draw Two.jsx", DRAW); write(&dir, "Export/All Artboards.js", ""); write(&dir, "notes.txt", ""); read(&app); let items = scripts(); - assert_eq!(shape(&items), "Draw Two, Export/[All Artboards], -, Check Script…, Other Script…"); + assert_eq!(shape(&items), format!("Draw Two, Export/[All Artboards], -, {FIXED}")); assert!(matches!(&items[0], Item::Cmd(_, scripts_menu::COMMAND, p) if *p == json!({ "path": draw })), "{:?}", items[0]); // A script added to the folder is listed by the next read, with no restart. write(&dir, "Added.js", ""); @@ -201,7 +204,7 @@ fn a_script_that_left_the_folder_is_not_run_and_the_folder_is_read_again() { assert_eq!(e, "the script is no longer in the Scripts folder"); assert!(!app.session.script_running()); scripts_menu::wait(); - assert_eq!(shape(&scripts()), "kept, -, Check Script…, Other Script…"); + assert_eq!(shape(&scripts()), format!("kept, -, {FIXED}")); // A file outside the folder is not one of its scripts, and a call needs a path. let outside = dir.join("outside.js"); std::fs::write(&outside, DRAW).unwrap(); @@ -246,12 +249,12 @@ fn the_menu_notes_a_listing_that_stopped_and_a_folder_it_cannot_read() { read(&app); let items = scripts(); assert_eq!(items.len(), vectorcraft_engine::script::folder::MAX_SCRIPTS + 4); - assert_eq!(shape(&items[items.len() - 4..]), format!("({}), -, Check Script…, Other Script…", scripts_menu::TRUNCATED)); + assert_eq!(shape(&items[items.len() - 4..]), format!("({}), -, {FIXED}", scripts_menu::TRUNCATED)); // A file where the folder should be. std::fs::remove_dir_all(dir.join("Scripts")).unwrap(); std::fs::write(dir.join("Scripts"), "").unwrap(); read(&app); - assert_eq!(shape(&scripts()), format!("({}), -, Check Script…, Other Script…", scripts_menu::UNREADABLE)); + assert_eq!(shape(&scripts()), format!("({}), -, {FIXED}", scripts_menu::UNREADABLE)); let _ = std::fs::remove_dir_all(dir); } @@ -284,7 +287,7 @@ fn names_past_the_session_limit_are_left_out_with_the_note() { let app = app(&dir); write(&dir, "Kept.js", ""); read(&app); - assert_eq!(shape(&scripts()), "Kept, -, Check Script…, Other Script…"); + assert_eq!(shape(&scripts()), format!("Kept, -, {FIXED}")); // Names other listings showed fill what one session keeps. for n in 0..scripts_menu::MAX_NAMES { if scripts_menu::intern(&format!("renamed {n}")).is_none() { @@ -294,7 +297,7 @@ fn names_past_the_session_limit_are_left_out_with_the_note() { write(&dir, "New.js", ""); write(&dir, "Folder/Inside.js", ""); read(&app); - assert_eq!(shape(&scripts()), format!("Kept, ({}), -, Check Script…, Other Script…", scripts_menu::TRUNCATED)); + assert_eq!(shape(&scripts()), format!("Kept, ({}), -, {FIXED}", scripts_menu::TRUNCATED)); let _ = std::fs::remove_dir_all(dir); } @@ -305,7 +308,8 @@ fn the_macos_menu_bar_lists_the_same_scripts_and_follows_a_new_listing() { let path = write(&dir, "Export/All Artboards.js", ""); let before = scripts_menu::revision(); read(&app); - assert_eq!(scripts_menu::revision(), before + 1); + // The loading note showed, then the listing took its place. + assert_eq!(scripts_menu::revision(), before + 2); let bar = native_menu::from_tree(&app, &menus::menu_tree()); let file = bar.menus.iter().find(|m| m.title == "File").unwrap(); let scripts = file.children.iter().find_map(|n| match n { @@ -321,10 +325,10 @@ fn the_macos_menu_bar_lists_the_same_scripts_and_follows_a_new_listing() { assert!(script.enabled && script.shortcut.is_none()); // A read that finds the same scripts changes nothing the menu bar would rebuild for. read(&app); - assert_eq!(scripts_menu::revision(), before + 1); + assert_eq!(scripts_menu::revision(), before + 2); write(&dir, "More.jsx", ""); read(&app); - assert_eq!(scripts_menu::revision(), before + 2); + assert_eq!(scripts_menu::revision(), before + 3); let _ = std::fs::remove_dir_all(dir); } @@ -424,9 +428,130 @@ fn a_read_asked_for_during_another_runs_when_that_one_ends() { fn an_app_without_a_scripts_folder_keeps_the_two_fixed_items() { let mut app = VectorcraftApp::new(Session::new(), crate::Services::default()); read(&app); - assert_eq!(shape(&scripts()), "Check Script…, Other Script…"); + assert_eq!(shape(&scripts()), FIXED, "no loading note: there is no folder to read"); let e = menus::run_ui_command(&mut app, scripts_menu::COMMAND, &json!({ "path": "draw.js" })).unwrap().unwrap_err(); assert_eq!(e, "the script is no longer in the Scripts folder"); assert_eq!(menus::UI_COMMANDS.iter().filter(|c| c.0 == scripts_menu::COMMAND).count(), 1); let _: Value = app.run("script.listInstalled", json!({})).unwrap(); } + +/// File › Scripts in the macOS menu bar as text, as [`shape`] gives the in-window menu. +fn native_shape(app: &VectorcraftApp) -> String { + fn one(nodes: &[Node]) -> String { + let node = |n: &Node| match n { + Node::Item(it) if it.command.is_none() => format!("({})", it.label), + Node::Item(it) => it.label.clone(), + Node::Header(label) => format!("({label})"), + Node::Submenu { label, children } => format!("{label}/[{}]", one(children)), + Node::Separator => "-".to_string(), + Node::Standard(s) => format!("{s:?}"), + }; + nodes.iter().map(node).collect::>().join(", ") + } + let bar = native_menu::from_tree(app, &menus::menu_tree()); + let file = bar.menus.iter().find(|m| m.title == "File").unwrap(); + let scripts = file.children.iter().find_map(|n| match n { + Node::Submenu { label, children } if label == "Scripts" => Some(children), + _ => None, + }); + one(scripts.unwrap()) +} + +#[test] +fn the_first_read_shows_a_loading_note_until_its_listing_comes() { + let dir = folder("loading"); + let app = app(&dir); + write(&dir, "first.js", ""); + let before = scripts_menu::revision(); + scripts_menu::refresh(&app, None); + scripts_menu::end_untaken(); + let loading = format!("({}), -, {FIXED}", scripts_menu::LOADING); + assert_eq!(shape(&scripts()), loading); + assert_eq!(native_shape(&app), loading, "the macOS menu bar shows the same note"); + assert_eq!(scripts_menu::revision(), before + 1, "the macOS menu bar rebuilds for the note"); + scripts_menu::wait(); + assert_eq!(shape(&scripts()), format!("first, -, {FIXED}")); + assert_eq!(native_shape(&app), format!("first, -, {FIXED}")); + assert_eq!(scripts_menu::revision(), before + 2); + // A later read keeps the listing, with no note, while it is under way. + write(&dir, "second.js", ""); + scripts_menu::refresh(&app, None); + scripts_menu::end_untaken(); + assert_eq!(shape(&scripts()), format!("first, -, {FIXED}")); + assert_eq!(scripts_menu::revision(), before + 2); + scripts_menu::wait(); + assert_eq!(shape(&scripts()), format!("first, second, -, {FIXED}")); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn an_empty_or_unreadable_first_listing_takes_the_place_of_the_loading_note() { + let dir = folder("loading-empty"); + let app = app(&dir); + let before = scripts_menu::revision(); + read(&app); + assert_eq!(shape(&scripts()), FIXED); + assert_eq!(scripts_menu::revision(), before + 2, "the note went, though the listing is the empty one it started from"); + let _ = std::fs::remove_dir_all(dir); + // A thread of its own has a menu that has not listed yet. + let dir = folder("loading-unreadable"); + std::fs::remove_dir_all(dir.join("Scripts")).unwrap(); + std::fs::write(dir.join("Scripts"), "").unwrap(); + let there = dir.clone(); + std::thread::spawn(move || { + let app = self::app(&there); + read(&app); + assert_eq!(shape(&scripts()), format!("({}), -, {FIXED}", scripts_menu::UNREADABLE)); + }) + .join() + .unwrap(); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn a_slow_first_read_says_so_until_its_listing_comes() { + let dir = folder("slow"); + let app = app(&dir); + write(&dir, "first.js", ""); + scripts_menu::refresh(&app, None); + scripts_menu::end_untaken(); + let started = scripts_menu::first_read_started().unwrap(); + let before = scripts_menu::revision(); + scripts_menu::check_slow(started + scripts_menu::SLOW_SECS / 2.0); + assert_eq!(shape(&scripts()), format!("({}), -, {FIXED}", scripts_menu::LOADING)); + assert_eq!(scripts_menu::revision(), before); + scripts_menu::check_slow(started + scripts_menu::SLOW_SECS); + assert_eq!(shape(&scripts()), format!("({}), -, {FIXED}", scripts_menu::SLOW)); + assert_eq!(native_shape(&app), format!("({}), -, {FIXED}", scripts_menu::SLOW)); + assert_eq!(scripts_menu::revision(), before + 1); + // Asking again while it reads starts no second read. + scripts_menu::refresh(&app, None); + scripts_menu::check_slow(started + 10.0 * scripts_menu::SLOW_SECS); + assert_eq!(scripts_menu::revision(), before + 1); + scripts_menu::wait(); + assert_eq!(shape(&scripts()), format!("first, -, {FIXED}")); + assert_eq!(scripts_menu::first_read_started(), None); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn a_first_read_that_ends_without_a_listing_says_the_folder_cannot_be_read_and_the_next_read_tries_again() { + let dir = folder("lost"); + let app = app(&dir); + write(&dir, "first.js", ""); + scripts_menu::refresh(&app, None); + scripts_menu::end_untaken(); + scripts_menu::lose_read(); + let before = scripts_menu::revision(); + scripts_menu::wait(); + assert_eq!(shape(&scripts()), format!("({}), -, {FIXED}", scripts_menu::UNREADABLE), "no loading note left behind"); + assert_eq!(native_shape(&app), format!("({}), -, {FIXED}", scripts_menu::UNREADABLE)); + assert_eq!(scripts_menu::revision(), before + 1); + assert_eq!(scripts_menu::first_read_started(), None); + scripts_menu::refresh(&app, None); + scripts_menu::end_untaken(); + assert_eq!(shape(&scripts()), format!("({}), -, {FIXED}", scripts_menu::LOADING)); + scripts_menu::wait(); + assert_eq!(shape(&scripts()), format!("first, -, {FIXED}")); + let _ = std::fs::remove_dir_all(dir); +} diff --git a/crates/ui-egui/src/tests/sysclip.rs b/crates/ui-egui/src/tests/sysclip.rs index 089fcdafaa..c44bd24c03 100644 --- a/crates/ui-egui/src/tests/sysclip.rs +++ b/crates/ui-egui/src/tests/sysclip.rs @@ -412,12 +412,8 @@ fn a_copy_while_the_worker_saves_writes_the_formats_at_once() { assert_eq!(board.borrow().writes, 1); } -/// Copy of an image the renderer can't decode: the PNG leaves it out, and once the formats are -/// written the status bar shows the PNG's note, made at once or on the worker. -#[test] -fn copy_says_in_the_status_bar_when_an_image_could_not_be_decoded() { - const WARNING: &str = "an image couldn't be decoded and is missing from the picture"; - // A PNG whose header reads but whose pixel data is cut short. +/// A PNG whose header reads but whose pixel data is cut short, which the renderer can't decode. +pub(super) fn cut_short_png() -> Vec { let mut png = Vec::new(); { let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(64, 32, image::Rgba([200, 30, 30, 255]))).into(); @@ -454,18 +450,113 @@ fn copy_says_in_the_status_bar_when_an_image_could_not_be_decoded() { .map(|__b| png.extend_from_slice(&__b)) } .unwrap(); + png +} + +/// The PNG's note on an image the renderer can't decode. +pub(super) const UNDECODED: &str = "an image couldn't be decoded and is missing from the picture"; + +/// Copy of an image the renderer can't decode: the PNG leaves it out, and once the formats are +/// written the status bar says the Copy (or Cut) has 1 note and shows it, made at once or on the +/// worker. The note is kept for the message's hover, and a Copy without notes leaves the message. +#[test] +fn copy_says_in_the_status_bar_when_an_image_could_not_be_decoded() { + let png = cut_short_png(); for worker in [false, true] { let (mut app, board) = if worker { app_with_worker() } else { app() }; app.status("Ready"); copy_rect(&mut app); background::wait_all(&mut app); - assert_eq!(app.ui.status, "Ready", "worker {worker}: no note"); - vectorcraft_testkit::fixtures::place_cut_png(&mut app.session, &png, json!({})); - app.status("Ready"); + assert_eq!((app.ui.status.as_str(), &app.ui.status_notes), ("Ready", &None), "worker {worker}: no note"); + for (id, said) in [("edit.copy", "Copied"), ("artboard.copy", "Copied"), ("edit.cut", "Cut")] { + vectorcraft_testkit::fixtures::place_cut_png(&mut app.session, &png, json!({})); + app.status("Ready"); + let p = if id == "artboard.copy" { json!({"index": 0}) } else { json!({}) }; + run(&mut app, id, p); + background::wait_all(&mut app); + assert_eq!(written(&board), [TEXT, SVG, PNG], "worker {worker}: {id}"); + let status = format!("{said} with 1 note: {UNDECODED}"); + assert_eq!(app.ui.status, status, "worker {worker}: {id}"); + assert_eq!(app.ui.status_notes, Some((status, vec![UNDECODED.to_string()])), "worker {worker}: {id}"); + } + } +} + +/// The status bar names how many notes a Copy's or Cut's formats have and the first of them, and +/// keeps them all, in order, for the message's hover. Without notes it keeps its message. +#[test] +fn copy_notes_are_counted_and_kept_in_order() { + let (mut app, _) = app(); + let notes: Vec = ["first", "second", "third"].map(String::from).to_vec(); + for (cut, said) in [(false, "Copied"), (true, "Cut")] { + crate::sysclip::show_copy_notes(&mut app, cut, notes.clone()); + let status = format!("{said} with 3 notes: first"); + assert_eq!(app.ui.status, status); + assert_eq!(app.ui.status_notes, Some((status, notes.clone()))); + } + app.status("Ready"); + app.ui.status_notes = None; + crate::sysclip::show_copy_notes(&mut app, false, vec![]); + assert_eq!((app.ui.status.as_str(), &app.ui.status_notes), ("Ready", &None)); +} + +/// A message shown while a Copy's formats are made on the worker stays: the formats are written +/// once they are ready, and their note does not replace the newer message. +#[test] +fn a_copy_note_does_not_replace_a_newer_message() { + let (mut app, board, hold) = app_with_busy_worker(""); + vectorcraft_testkit::fixtures::place_cut_png(&mut app.session, &cut_short_png(), json!({})); + app.status("Ready"); + run(&mut app, "edit.copy", json!({})); + app.status("Saved /out/a.vectorcraft"); + drop(hold); + background::wait_all(&mut app); + assert_eq!(written(&board), [TEXT, SVG, PNG]); + assert_eq!((app.ui.status.as_str(), &app.ui.status_notes), ("Saved /out/a.vectorcraft", &None)); +} + +/// A message set while a Copy's formats are made on the worker stays even when its text is the +/// Copy's: an empty status bar set again, or File › New clearing it. +#[test] +fn a_copy_note_does_not_replace_a_message_with_the_same_text() { + for then in ["status", "file.new"] { + let (mut app, board, hold) = app_with_busy_worker(""); + vectorcraft_testkit::fixtures::place_cut_png(&mut app.session, &cut_short_png(), json!({})); + app.status(""); run(&mut app, "edit.copy", json!({})); + if then == "status" { + app.status(""); + } else { + run(&mut app, "file.new", json!({})); + } + drop(hold); background::wait_all(&mut app); - assert_eq!(written(&board), [TEXT, SVG, PNG], "worker {worker}"); - assert_eq!(app.ui.status, WARNING, "worker {worker}"); + assert_eq!(written(&board), [TEXT, SVG, PNG], "{then}"); + assert_eq!((app.ui.status.as_str(), &app.ui.status_notes), ("", &None), "{then}"); + } +} + +/// A Copy without notes clears the message an earlier Copy's notes left, with its hover notes, +/// made at once or on the worker. It leaves any other message, one with the same text set since +/// included. +#[test] +fn a_copy_without_notes_clears_an_earlier_copys_notes() { + let earlier = format!("Copied with 1 note: {UNDECODED}"); + for worker in [false, true] { + for (then, kept) in [(None, ""), (Some("Ready"), "Ready"), (Some(earlier.as_str()), earlier.as_str())] { + let (mut app, _) = if worker { app_with_worker() } else { app() }; + vectorcraft_testkit::fixtures::place_cut_png(&mut app.session, &cut_short_png(), json!({})); + run(&mut app, "edit.copy", json!({})); + background::wait_all(&mut app); + assert_eq!(app.ui.status, earlier, "worker {worker}, {then:?}"); + if let Some(then) = then { + app.status(then); + app.ui.status_notes = None; + } + copy_rect(&mut app); + background::wait_all(&mut app); + assert_eq!((app.ui.status.as_str(), &app.ui.status_notes), (kept, &None), "worker {worker}, {then:?}"); + } } } diff --git a/crates/ui-egui/src/tests/sysclip_guides.rs b/crates/ui-egui/src/tests/sysclip_guides.rs index 50c4535c37..f078ec5972 100644 --- a/crates/ui-egui/src/tests/sysclip_guides.rs +++ b/crates/ui-egui/src/tests/sysclip_guides.rs @@ -10,7 +10,7 @@ use vectorcraft_doc::NodeKind; use vectorcraft_engine::Session; use vectorcraft_engine::cmd::clipboard::{PNG, TEXT}; -use crate::tests_sysclip::{app, app_with_busy_worker, copy_elsewhere, copy_rect, count, frame, pasted, run, written}; +use crate::tests_sysclip::{UNDECODED, app, app_with_busy_worker, copy_elsewhere, copy_rect, count, cut_short_png, frame, pasted, run, written}; use crate::{Services, VectorcraftApp, background}; fn guides(app: &VectorcraftApp) -> usize { @@ -42,6 +42,18 @@ fn a_guides_only_copy_pastes_the_guides_not_what_another_app_copied_before() { assert_eq!((guides(&app), count(&app)), (3, 0)); } +/// A guides-only Copy has no notes: it clears the message an earlier Copy's notes left. +#[test] +fn a_guides_only_copy_clears_an_earlier_copys_notes() { + let (mut app, _) = app(); + vectorcraft_testkit::fixtures::place_cut_png(&mut app.session, &cut_short_png(), json!({})); + run(&mut app, "edit.copy", json!({})); + background::wait_all(&mut app); + assert_eq!(app.ui.status, format!("Copied with 1 note: {UNDECODED}")); + copy_guide(&mut app, 120.0); + assert_eq!((app.ui.status.as_str(), &app.ui.status_notes), ("", &None)); +} + #[test] fn what_another_app_copies_after_a_guides_only_copy_is_pasted() { let (mut app, board) = app(); diff --git a/crates/ui-egui/src/tests/taskbar.rs b/crates/ui-egui/src/tests/taskbar.rs index 8230969c97..bc4734db5a 100644 --- a/crates/ui-egui/src/tests/taskbar.rs +++ b/crates/ui-egui/src/tests/taskbar.rs @@ -215,6 +215,185 @@ fn an_image_with_vector_art_offers_make_clipping_mask() { assert!(has(&texts, "Unite") && !has(&texts, "Make Clipping Mask"), "{texts:?}"); } +/// Places a 2 by 2 pixel image from `dir` and returns its id. +fn place_image(app: &mut VectorcraftApp, dir: &crate::tests_folder::Folder) -> u64 { + let raw = [0u8, 128, 255, 255].repeat(4); + let image = craft_image_codecs::Image::from_raw(2, 2, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, raw).unwrap(); + let png = craft_image_codecs::encode(&image, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap(); + let path = dir.file("tile.png", &png); + app.services.read = Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))); + app.run("file.place", json!({"path": path, "link": false})).unwrap(); + let img = app.session.active().unwrap().selection.objects[0].0; + assert!(matches!(kind(app, img), NodeKind::Image(_))); + img +} + +/// Whether the bar offers Make Clipping Mask, worked out by counting the selected images: some of +/// the selected ids, but not all, are images. +fn mixed_by_count(st: &vectorcraft_engine::DocState) -> bool { + let n = st.selection.len(); + let images = st.selection.objects.iter().filter_map(|id| st.doc.node(*id)).filter(|o| matches!(o.kind, NodeKind::Image(_))).count(); + images > 0 && images < n +} + +/// Sets the selected objects and anchors directly, as no command can select an id with no object, +/// and moves the document's revision as every selection change does. +fn set_selection(app: &mut VectorcraftApp, ids: &[u64], anchors: &[u64]) { + let st = app.session.active_mut().unwrap(); + st.selection.objects = ids.iter().map(|i| NodeId(*i)).collect(); + st.selection.anchors = anchors.iter().map(|i| (NodeId(*i), [(0, 0)].into_iter().collect())).collect(); + st.revision += 1; +} + +/// The task bar's check for images selected with other objects gives the count's answer for every +/// selection: empty, one object, paths only, images only, images with paths or type, an id +/// selected twice, anchors picked out, and ids with no object. +#[test] +fn images_with_other_art_matches_the_image_count() { + let mut app = app(); + let dir = crate::tests_folder::Folder::new("ui-taskbar-mixed"); + let img = place_image(&mut app, &dir); + let img2 = place_image(&mut app, &dir); + let a = id(app.run("shape.rectangle", json!({"x": 10, "y": 200, "width": 40, "height": 40})).unwrap()); + let b = id(app.run("shape.rectangle", json!({"x": 30, "y": 210, "width": 40, "height": 40})).unwrap()); + let t = id(app.run("text.create", json!({"x": 60, "y": 80, "text": "Hello"})).unwrap()); + let stale = 1_000_000; + assert!(app.session.active().unwrap().doc.node(NodeId(stale)).is_none()); + let ctx = egui::Context::default(); + let cases: [(&[u64], &[u64], bool); 17] = [ + (&[], &[], false), + (&[a], &[], false), + (&[img], &[], false), + (&[a, b], &[], false), + (&[img, img2], &[], false), + (&[img, a], &[], true), + (&[a, img], &[], true), + (&[a, b, img], &[], true), + (&[img, t], &[], true), + (&[img, img], &[], false), + (&[img, img, a], &[], true), + (&[img, a], &[a], true), + (&[a, b], &[a, b], false), + (&[img, stale], &[], true), + (&[img, img2, stale], &[], true), + (&[a, stale], &[], false), + (&[stale, stale], &[], false), + ]; + for (ids, anchors, mixed) in cases { + set_selection(&mut app, ids, anchors); + let st = app.session.active().unwrap(); + assert_eq!(mixed_by_count(st), mixed, "{ids:?} with anchors on {anchors:?}: the count"); + assert_eq!(canvas::images_with_other_art(st, &ctx), mixed, "{ids:?} with anchors on {anchors:?}"); + } +} + +/// The check is worked out once for each revision of the document: an unchanged revision gives the +/// kept answer, and a selection change, which moves the revision, works it out again. +#[test] +fn images_with_other_art_is_kept_for_the_revision() { + let mut app = app(); + let dir = crate::tests_folder::Folder::new("ui-taskbar-mixed-kept"); + let img = place_image(&mut app, &dir); + let a = id(app.run("shape.rectangle", json!({"x": 10, "y": 200, "width": 40, "height": 40})).unwrap()); + let b = id(app.run("shape.rectangle", json!({"x": 30, "y": 210, "width": 40, "height": 40})).unwrap()); + select(&mut app, &[img, a]); + let ctx = egui::Context::default(); + assert!(canvas::images_with_other_art(app.session.active().unwrap(), &ctx)); + // Changing the objects behind the revision's back shows the kept answer is used. + app.session.active_mut().unwrap().selection.objects = vec![NodeId(a), NodeId(b)]; + assert!(canvas::images_with_other_art(app.session.active().unwrap(), &ctx), "the revision's answer is kept"); + select(&mut app, &[a, b]); + assert!(!canvas::images_with_other_art(app.session.active().unwrap(), &ctx), "a new revision works it out again"); + select(&mut app, &[b, img]); + assert!(canvas::images_with_other_art(app.session.active().unwrap(), &ctx)); + // Another context keeps its own answer. + assert!(canvas::images_with_other_art(app.session.active().unwrap(), &egui::Context::default())); +} + +/// The CPU time this thread has used, where the system reports it (Linux), else none. +fn cpu_time() -> Option { + std::fs::read_to_string("/proc/thread-self/schedstat") + .ok() + .and_then(|s| s.split_whitespace().next()?.parse::().ok()) + .map(std::time::Duration::from_nanos) +} + +/// Runs `f` and returns the CPU time it used (zero where the system does not report it) and the +/// time it took. +fn timed(f: impl FnOnce()) -> (std::time::Duration, std::time::Duration) { + let (cpu, wall) = (cpu_time(), std::time::Instant::now()); + f(); + let wall = wall.elapsed(); + (cpu_time().zip(cpu).map_or_else(Default::default, |(b, a)| b.saturating_sub(a)), wall) +} + +/// Times the image check on a selection of 131,072 rectangles: 120 frames with an unchanged +/// revision, counting each frame as before against the kept answer, and the first frame after a +/// change. Each cell is the median of 7 runs, CPU time then elapsed time. Run with +/// `cargo test -p vectorcraft-ui-egui --lib images_with_other_art_timing -- --ignored --nocapture`. +#[test] +#[ignore = "a timing run on a large selection"] +fn images_with_other_art_timing() { + let dir = crate::tests_folder::Folder::new("ui-taskbar-mixed-timing"); + let doubled = |app: &mut VectorcraftApp, times: usize| { + for _ in 0..times { + app.run("select.all", json!({})).unwrap(); + app.run("edit.duplicate", json!({})).unwrap(); + } + app.run("select.all", json!({})).unwrap(); + }; + let rects = |app: &mut VectorcraftApp| { + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + doubled(app, 17); + }; + let mut variants: Vec<(&str, VectorcraftApp)> = vec![]; + let mut none = app(); + rects(&mut none); + variants.push(("131,072 rectangles", none)); + let mut one = app(); + rects(&mut one); + place_image(&mut one, &dir); + one.run("select.all", json!({})).unwrap(); + variants.push(("131,072 rectangles and 1 image", one)); + let mut images = app(); + place_image(&mut images, &dir); + doubled(&mut images, 9); + variants.push(("512 images", images)); + let median = |mut v: Vec<(std::time::Duration, std::time::Duration)>| { + let mut wall: Vec<_> = v.iter().map(|t| t.1).collect(); + v.sort(); + wall.sort(); + format!("{:.2?} / {:.2?}", v[v.len() / 2].0, wall[wall.len() / 2]) + }; + println!("| Selection | Count, 120 frames | Kept, 120 frames | Count, 1 frame | First frame after a change |"); + println!("| --- | --- | --- | --- | --- |"); + for (name, mut app) in variants { + let mut runs = [vec![], vec![], vec![], vec![]]; + for _ in 0..7 { + let ctx = egui::Context::default(); + let st = app.session.active().unwrap(); + let expected = mixed_by_count(st); + assert_eq!(canvas::images_with_other_art(st, &ctx), expected, "{name}"); + runs[0].push(timed(|| { + for _ in 0..120 { + assert_eq!(std::hint::black_box(mixed_by_count(st)), expected); + } + })); + runs[1].push(timed(|| { + for _ in 0..120 { + assert_eq!(std::hint::black_box(canvas::images_with_other_art(st, &ctx)), expected); + } + })); + runs[2].push(timed(|| assert_eq!(std::hint::black_box(mixed_by_count(st)), expected))); + app.session.active_mut().unwrap().revision += 1; + let st = app.session.active().unwrap(); + runs[3].push(timed(|| assert_eq!(std::hint::black_box(canvas::images_with_other_art(st, &ctx)), expected))); + } + let [a, b, c, d] = runs.map(median); + println!("| {name} ({} selected) | {a} | {b} | {c} | {d} |", app.session.active().unwrap().selection.len()); + } +} + #[test] fn type_converts_between_point_and_area_type() { let mut app = app(); diff --git a/crates/ui-egui/src/tests/trace_runs.rs b/crates/ui-egui/src/tests/trace_runs.rs index 478631ad18..fee8b11115 100644 --- a/crates/ui-egui/src/tests/trace_runs.rs +++ b/crates/ui-egui/src/tests/trace_runs.rs @@ -142,6 +142,69 @@ fn without_threads_make_traces_at_once() { assert_eq!(undos(&app), before + 1); } +/// A trace's notes: the status bar names how many there are and the first of them, and keeps them +/// all, in the reply's order, for the message's hover. Make and Make and Expand, at once, off the +/// UI thread and from the Image Trace panel; a trace without notes leaves the status bar empty. +/// A trace that made no paths shows its first note as it is, and keeps them all for the hover. +#[test] +fn a_trace_shows_how_many_notes_it_has() { + let mut app = app(); + let img = image::RgbaImage::from_fn(1501, 20, |x, _| image::Rgba(if x < 700 { [0, 0, 0, 255] } else { [255, 255, 255, 255] })); + let mut png = vec![]; + img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let data = vectorcraft_format::base64_encode(&png); + let slow = "The image is 1501 × 20 pixels, more than 1500 on a side: it is traced, but more slowly. A lower-fidelity preset or a smaller copy of the image traces faster."; + let some = ("#000000", "keepColors: none of the colors the trace found matches #00ffff, so nothing of it is traced."); + let none = ("#ff00ff", "Nothing was traced: none of the colors the trace found matches keepColors (#ff00ff, #00ffff)."); + for (command, threaded, from_panel) in + [("imageTrace.make", false, false), ("imageTrace.make", true, false), ("imageTrace.makeAndExpand", true, true)] + { + for (keep, first) in [some, none] { + app.run("file.place", json!({"name": "wide.png", "dataBase64": data, "link": false})).unwrap(); + app.trace_runs.off_the_ui_thread = threaded; + app.ui.status.clear(); + let p = json!({"params": {"mode": "color", "palette": "limited", "colors": 2, "keepColors": [keep, "#00ffff"]}}); + trace_runs::start(&mut app, command, p, from_panel).unwrap(); + wait(&mut app); + let notes = [first, slow].map(String::from).to_vec(); + let status = if keep == some.0 { format!("Traced with 2 notes: {first}") } else { first.to_string() }; + assert_eq!(app.ui.status, status, "{command}, threaded {threaded}"); + assert_eq!(app.ui.status_notes, Some((status, notes)), "{command}, threaded {threaded}"); + } + } + // The 40 × 40 px image of [`app`] traces without notes: the status bar stays empty. + let mut app = self::app(); + for command in ["imageTrace.make", "imageTrace.makeAndExpand"] { + app.ui.status.clear(); + let v = app.run(command, json!({"preset": "Default"})).unwrap(); + assert_eq!(v["warnings"], json!([]), "{command}"); + assert_eq!((app.ui.status.as_str(), &app.ui.status_notes), ("", &None), "{command}"); + app.run("edit.undo", json!({})).unwrap(); + } +} + +/// A trace without notes clears the message an earlier trace's notes left, with its hover notes, +/// and leaves any other message, one with the same text set since included. +#[test] +fn a_trace_without_notes_clears_an_earlier_traces_notes() { + let mut app = app(); + let earlier = "Traced with 2 notes: a note"; + for (then, kept) in [(None, ""), (Some("Ready"), "Ready"), (Some(earlier), earlier)] { + app.status(earlier); + app.trace_runs.notes_status = Some((earlier.to_string(), app.ui.status_sets)); + if let Some(then) = then { + app.status(then); + } + app.ui.status_notes = Some((app.ui.status.clone(), vec!["a note".to_string(), "another".to_string()])); + let v = app.run("imageTrace.make", json!({"preset": "Default"})).unwrap(); + assert_eq!(v["warnings"], json!([]), "{then:?}"); + assert_eq!(app.ui.status, kept, "{then:?}"); + assert_eq!(app.ui.status_notes.is_none(), kept.is_empty(), "{then:?}"); + assert_eq!(app.trace_runs.notes_status, None, "{then:?}"); + app.run("edit.undo", json!({})).unwrap(); + } +} + /// Nothing to trace fails at once, before anything runs. #[test] fn nothing_to_trace_fails_at_once() { diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 56de30acff..ec2ef99db0 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -38,7 +38,7 @@ pub const BASIC: &[(&str, &[&[&str]])] = &[ "Shapes", &[ &["rectangle", "roundedRectangle", "star", "lineSegment", "arc", "spiral", "rectangularGrid", "polarGrid", "flare"], - &["ellipse"], + &["ellipse", "circle"], &["polygon"], &["shaper"], ], @@ -127,21 +127,20 @@ pub(crate) fn docked_width(ui: &crate::state::UiState) -> f32 { } } -/// With `UiState::tools_beside_canvas` on, the canvas-edge redocking target, registered even -/// while Tools floats, and the docked panel, which follows the canvas's left edge as dock columns -/// resize, collapse or hide. With it off, `app.rs` draws Tools before the docking layout. +/// The canvas-edge redocking targets, registered even while Tools floats, whichever way +/// `UiState::tools_beside_canvas` is (a drop on the left one turns it on), and, with it on, the +/// docked panel, which follows the canvas's left edge as dock columns resize, collapse or hide. +/// With it off, `app.rs` draws Tools before the docking layout. /// -/// The canvas's right edge, left of the panels, is a redocking target too, and Tools docked there -/// (`UiState::toolbar_right`) is drawn at it whichever way the setting is. +/// Tools docked on the canvas's right edge, left of the panels (`UiState::toolbar_right`), is +/// drawn there whichever way the setting is. pub(crate) fn show_beside_canvas(app: &mut VectorcraftApp, ui: &mut Ui) { if !app.ui.toolbar || app.ui.screen_mode >= 3 { return; } let canvas = ui.available_rect_before_wrap(); crate::tools_float::set_right_dock_zone(ui.ctx(), canvas, WIDTH); - if app.ui.tools_beside_canvas { - crate::tools_float::set_dock_zones(ui.ctx(), canvas, WIDTH); - } + crate::tools_float::set_dock_zones(ui.ctx(), canvas, WIDTH); if app.ui.toolbar_pos.is_none() && (app.ui.tools_beside_canvas || app.ui.toolbar_right) { show(app, ui); } @@ -1212,7 +1211,7 @@ fn puppet_warp_options(app: &mut VectorcraftApp, ui: &mut Ui, reserve: f32) { ui.label(text); let unit = app.session.general_unit(); if let Some(v) = widgets::num_field(ui, ("cb-tool", "expand"), opts["expand"].as_f64(), unit, 64.0) { - app.run("tool.setOption", json!({ "key": "expand", "value": v })).ok(); + app.run("tool.setOption", json!({ "key": "expand", "value": v.clamp(0.0, 1000.0) })).ok(); } } let show = opts["showMesh"].as_bool().unwrap_or(true); diff --git a/crates/ui-egui/src/toolbar/tests.rs b/crates/ui-egui/src/toolbar/tests.rs index 37613c72e8..708e5e9807 100644 --- a/crates/ui-egui/src/toolbar/tests.rs +++ b/crates/ui-egui/src/toolbar/tests.rs @@ -853,7 +853,7 @@ fn window_float_tools_floats_and_puts_back_a_group() { assert!(app.ui.floating_flyouts.is_empty() && check(&app) == Some(false)); assert_eq!(app.run("window.floatTools", json!({"tool": "pen", "floating": false})).unwrap(), json!(false)); // A tool alone in its slot, an unknown tool, a bad flag. - assert!(app.run("window.floatTools", json!({"tool": "ellipse"})).is_err()); + assert!(app.run("window.floatTools", json!({"tool": "polygon"})).is_err()); assert!(app.run("window.floatTools", json!({"tool": "nope"})).is_err()); assert!(app.run("window.floatTools", json!({})).is_err()); assert!(app.run("window.floatTools", json!({"tool": "pen", "floating": "yes"})).is_err()); diff --git a/crates/ui-egui/src/tools_float.rs b/crates/ui-egui/src/tools_float.rs index b5fb04d384..1511958ff1 100644 --- a/crates/ui-egui/src/tools_float.rs +++ b/crates/ui-egui/src/tools_float.rs @@ -1,10 +1,15 @@ //! The Tools panel floats by its title bar and docks again on the window's left edge //! ([`crate::toolbar`]). It stays outside the docking layout: dragging its title bar out of the //! docked panel floats it under the pointer, a floating panel's title bar moves it, and a release -//! over the strip along the window's left edge (lit up) docks it there. With Keep Tools Beside the -//! Canvas on (`UiState::tools_beside_canvas`), a release over the canvas's left edge docks it too, -//! and either release docks it beside the canvas. A release over the canvas's right edge (left of -//! the panels) or the window's right edge docks it on the right, between the canvas and the panels. +//! over the strip along the window's left edge (lit up) docks it there. A release over the strip +//! along the canvas's left edge, right of any panels docked on the left, docks it beside the +//! canvas. The release sets Keep Tools Beside the Canvas (`UiState::tools_beside_canvas`) to the +//! place it docked at. With no panels docked on the left, both strips put Tools in the same +//! place (left of any toolbars made with New Toolbar docked there), and a drop on either docks it +//! where the setting puts it and leaves the setting as it is; so does a drop in the column both +//! strips share when the panels are collapsed narrower than the window's strip. A release over +//! the canvas's right edge (left of the panels) or the window's right edge docks it on the right, +//! between the canvas and the panels. //! Escape or losing the window's focus puts it back where the drag began. //! //! `window.panel.float {panel: "tools"}` / `window.panel.dock {panel: "tools"}` do the same for @@ -32,6 +37,9 @@ struct Move { original: Option<[f32; 2]>, /// The side it was docked on before the drag. right: bool, + /// The frame that floated it from the window's left edge, whose canvas-edge strip was laid out + /// right of the docked panel and is not a target. + floated_from_edge: Option, } fn move_id() -> Id { @@ -53,8 +61,8 @@ pub(crate) fn mark_escape_cancelled(ctx: &egui::Context) { ctx.data_mut(|d| d.insert_temp(escape_cancel_id(), frame)); } -/// The strip along the canvas's left edge where the Tools panel docks while Keep Tools Beside the -/// Canvas is on, as last laid out. +/// The strip along the canvas's left edge where the Tools panel docks beside the canvas, as last +/// laid out. pub(crate) fn tools_zone_id() -> Id { Id::unique("tools-float-zone") } @@ -82,10 +90,14 @@ pub(crate) fn set_dock_zones(ctx: &egui::Context, canvas: Rect, width: f32) { }); } -/// Forget the canvas-edge target, so a strip laid out while Keep Tools Beside the Canvas was on -/// does not dock Tools after it is turned off. -pub(crate) fn clear_canvas_dock_zone(ctx: &egui::Context) { - ctx.data_mut(|d| d.remove::(tools_zone_id())); +fn dock_area_id() -> Id { + Id::unique("tools-float-dock-area-left") +} + +/// The left edge of the space the canvas and the panels share, as last laid out: right of the +/// lane of New Toolbar toolbars docked on the left, and of Tools docked at the window's edge. +pub(crate) fn set_dock_area_left(ctx: &egui::Context, left: f32) { + ctx.data_mut(|d| d.insert_temp(dock_area_id(), left)); } /// The legacy 48-point window-edge target spans the full layout below the bars, including @@ -113,9 +125,10 @@ pub(crate) fn cancel_move_on_escape(app: &mut VectorcraftApp, ctx: &egui::Contex } } -fn start(app: &VectorcraftApp, ctx: &egui::Context, grab: Vec2) { +fn start(app: &VectorcraftApp, ctx: &egui::Context, grab: Vec2, floated_from_edge: Option) { let Some(from) = ctx.input(|i| i.pointer.press_origin().or(i.pointer.interact_pos())) else { return }; - ctx.data_mut(|d| d.insert_temp(move_id(), Move { grab, from, original: app.ui.toolbar_pos, right: app.ui.toolbar_right })); + let m = Move { grab, from, original: app.ui.toolbar_pos, right: app.ui.toolbar_right, floated_from_edge }; + ctx.data_mut(|d| d.insert_temp(move_id(), m)); } /// The Tools panel's title bar was pressed (`title`, the panel's bounds `bounds`): docked, dragging @@ -126,11 +139,12 @@ pub(crate) fn drag_tools(app: &mut VectorcraftApp, ctx: &egui::Context, title: & } let Some(at) = ctx.input(|i| i.pointer.interact_pos()) else { return }; match floating { - Some(pos) if title.drag_started() => start(app, ctx, at - pos), + Some(pos) if title.drag_started() => start(app, ctx, at - pos, None), None if title.dragged() && !bounds.contains(at) => { // Held where the press grabbed the title bar. let grab = ctx.input(|i| i.pointer.press_origin()).map_or(vec2(10.0, 7.0), |p| p - bounds.min); - start(app, ctx, grab); + let at_edge = !app.ui.tools_beside_canvas && !app.ui.toolbar_right; + start(app, ctx, grab, at_edge.then(|| ctx.cumulative_frame_nr_for(ctx.viewport_id()))); let p = at - grab; app.ui.toolbar_pos = Some([p.x, p.y]); } @@ -138,23 +152,50 @@ pub(crate) fn drag_tools(app: &mut VectorcraftApp, ctx: &egui::Context, title: & } } -/// The docking strip under `at`, if any, and whether it docks the panel on the right: the window's -/// left edge, with `beside_canvas` the canvas's left edge as well, and on the right the canvas's -/// right edge or anywhere along the window's right edge (which lights up the strip left of the -/// panels, where it docks). -fn drop_zone(ctx: &egui::Context, at: Pos2, beside_canvas: bool) -> Option<(Rect, bool)> { - let (left, right) = ctx.data(|d| { - let canvas = d.get_temp::(tools_zone_id()).filter(|_| beside_canvas); - let left = [canvas, d.get_temp::(window_zone_id())].into_iter().flatten().find(|r| r.contains(at)); - (left, d.get_temp::(tools_zone_right_id())) +/// Where a release docks the Tools panel. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Dock { + /// On the left: beside the canvas (`Some(true)`), at the window's edge (`Some(false)`), or + /// where Keep Tools Beside the Canvas puts it (`None`, where the two strips share a column). + Left(Option), + /// On the right, between the canvas and the panels. + Right, +} + +/// The docking strip under `at`, if any, and where it docks the panel: the window's left edge, +/// the canvas's left edge, and on the right the canvas's right edge or anywhere along the +/// window's right edge (which lights up the strip left of the panels, where it docks). With no +/// panels docked on the left, both left strips put Tools in the same place, and a drop on either +/// docks it where `beside_canvas` puts it; with panels collapsed narrower than the window's strip, +/// so does a drop in the column the two strips share. The canvas's strip lights up where both are +/// under `at` and `beside_canvas` is on; with no panels docked on the left, the window's strip lights +/// up, where Tools docks. Without `canvas_laid_out`, the canvas's strip is skipped. +fn drop_zone(ctx: &egui::Context, at: Pos2, beside_canvas: bool, canvas_laid_out: bool) -> Option<(Rect, Dock)> { + let (canvas, window, right, area_left) = ctx.data(|d| { + let canvas = d.get_temp::(tools_zone_id()).filter(|_| canvas_laid_out); + (canvas, d.get_temp::(window_zone_id()), d.get_temp::(tools_zone_right_id()), d.get_temp::(dock_area_id())) }); - if let Some(r) = left { - return Some((r, false)); + let panels_left = matches!((canvas, area_left), (Some(c), Some(left)) if c.left() > left + 0.5); + let shared = !panels_left || matches!((canvas, window), (Some(c), Some(w)) if c.x_range().contains(at.x) && w.x_range().contains(at.x)); + let follow = |beside: bool| Dock::Left((!shared).then_some(beside)); + // With no panels docked on the left, Tools docks at the window's edge either way. + let shown = |hit: Rect| if panels_left { hit } else { window.unwrap_or(hit) }; + match (canvas.filter(|r| r.contains(at)), window.filter(|r| r.contains(at))) { + (Some(c), Some(w)) => return Some((shown(if beside_canvas { c } else { w }), follow(beside_canvas))), + (Some(c), None) => return Some((shown(c), follow(true))), + (None, Some(w)) => return Some((w, follow(false))), + (None, None) => {} } let r = right?; // Read outside the data lock above: egui's context locks are not re-entrant. let at_edge = at.x >= ctx.content_rect().right() - crate::toolbar::WIDTH && r.y_range().contains(at.y); - (r.contains(at) || at_edge).then_some((r, true)) + (r.contains(at) || at_edge).then_some((r, Dock::Right)) +} + +/// The strip that lights up with the pointer at `at` during a move. +#[cfg(test)] +pub(crate) fn drop_highlight(ctx: &egui::Context, at: Pos2, beside_canvas: bool) -> Option { + drop_zone(ctx, at, beside_canvas, true).map(|(zone, _)| zone) } fn highlight(ctx: &egui::Context, zone: Rect) { @@ -179,7 +220,11 @@ pub fn track(app: &mut VectorcraftApp, ctx: &egui::Context) { return; } let at = ctx.input(|i| i.pointer.interact_pos()); - let zone = at.filter(|at| at.distance(m.from) > TRAVEL).and_then(|at| drop_zone(ctx, at, app.ui.tools_beside_canvas)); + // The frame after Tools floated from the window's edge reads the canvas-edge strip that frame + // laid out right of the docked panel. + let frame = ctx.cumulative_frame_nr_for(ctx.viewport_id()); + let canvas_laid_out = m.floated_from_edge.is_none_or(|f| frame > f + 1); + let zone = at.filter(|at| at.distance(m.from) > TRAVEL).and_then(|at| drop_zone(ctx, at, app.ui.tools_beside_canvas, canvas_laid_out)); if ctx.input(|i| i.pointer.primary_down()) { if let Some(p) = at.map(|at| at - m.grab) && p.x.is_finite() @@ -194,9 +239,19 @@ pub fn track(app: &mut VectorcraftApp, ctx: &egui::Context) { return; } ctx.data_mut(|d| d.remove::(move_id())); - if let Some((_, right)) = zone { - app.ui.toolbar_pos = None; - app.ui.toolbar_right = right; + match zone { + Some((_, Dock::Left(beside))) => { + app.ui.toolbar_pos = None; + app.ui.toolbar_right = false; + if let Some(beside) = beside { + app.ui.tools_beside_canvas = beside; + } + } + Some((_, Dock::Right)) => { + app.ui.toolbar_pos = None; + app.ui.toolbar_right = true; + } + None => {} } } diff --git a/crates/ui-egui/src/trace_runs.rs b/crates/ui-egui/src/trace_runs.rs index d9800e6668..9234f914b4 100644 --- a/crates/ui-egui/src/trace_runs.rs +++ b/crates/ui-egui/src/trace_runs.rs @@ -76,6 +76,14 @@ pub struct TraceRuns { next_id: u64, /// Set by unit tests whose app traces off the UI thread. pub(crate) off_the_ui_thread: bool, + /// The status bar's message the latest Image Trace with notes left, with + /// [`crate::state::UiState::status_sets`] then. + pub(crate) notes_status: Option<(String, u64)>, +} + +/// The status bar's line after an Image Trace with `n` notes, the first of them `first`. +pub(crate) fn traced_with_notes(n: usize, first: &str) -> String { + crate::i18n::msg_n(n as u64, "Traced with {n} note: {first}", "Traced with {n} notes: {first}", &[("first", first)]) } /// Does `app` trace off the UI thread? Where documents open off it ([`crate::opening::available`]), diff --git a/crates/ui-egui/src/ui_fonts.rs b/crates/ui-egui/src/ui_fonts.rs index ac3f260e95..73c1a30891 100644 --- a/crates/ui-egui/src/ui_fonts.rs +++ b/crates/ui-egui/src/ui_fonts.rs @@ -6,71 +6,154 @@ //! don't have, an installed font covering it is looked for (in the background on native) and added //! to egui's families as their last fallback, on the baseline of each family's first face, from //! the next frame on. Text the UI fonts cover costs no font loading or memory. On the web, which -//! has no system fonts, such characters stay missing-glyph boxes (Japanese too, unless built with -//! craft-fonts). +//! has no system fonts, the shell is told which characters no loaded font covers +//! ([`on_missing_glyphs`]) and fetches a face for them (Korean, Devanagari) when it has one; until +//! a face arrives they stay missing-glyph boxes (Japanese too, unless built with craft-fonts). +//! Characters no font covered are looked for again whenever the font database changes. use std::collections::HashSet; -use std::sync::Arc; +use std::sync::{Arc, OnceLock}; use egui::epaint::Shape; use egui::epaint::text::{FontInsert, FontPriority, InsertFontFamily}; use egui::{FontData, FontDefinitions, FontFamily, FontId, FontTweak, LayerId}; use vectorcraft_text::{FontDb, FontFace}; +/// Called with the painted characters no loaded or installed font covers. +static MISSING_GLYPHS: OnceLock = OnceLock::new(); + +/// Have `f` called (on the UI thread, after a frame) with the characters the interface painted +/// that no loaded or installed font covers, so it can load a font for them: the web shell fetches +/// its `demand` craft-fonts faces. A character is reported again only after the fonts change and it +/// is still not covered. The first call sets it; later calls are ignored. +pub fn on_missing_glyphs(f: fn(&[char])) { + let _ = MISSING_GLYPHS.set(f); +} + +/// What one search for fallback faces found. +struct Found { + /// The faces covering the characters looked for, each once. + faces: Vec>, + /// The characters no face covers. + uncovered: Vec, + /// [`FontDb::generation`] when the search started. + generation: u64, +} + +/// Look in `db` for the faces covering `chars`, each through `lookup`. +fn search(db: &FontDb, chars: Vec, lookup: impl Fn(&FontDb, char) -> Option>) -> Found { + // Read before the lookups: when a font is added during them, the generation kept is older than + // the database's, and the characters not found are looked for again. + let generation = db.generation(); + let (mut faces, mut uncovered): (Vec>, Vec) = (vec![], vec![]); + for c in chars { + match lookup(db, c) { + Some(f) if !faces.iter().any(|x| x.id() == f.id()) => faces.push(f), + Some(_) => {} + None => uncovered.push(c), + } + } + Found { faces, uncovered, generation } +} + #[derive(Default)] pub(crate) struct UiFonts { /// Characters looked at already: the UI fonts have them, a fallback was added (or is being /// looked for), or no font has them. seen: HashSet, + /// Characters no font covered at the last search: looked for again once the font database's + /// generation is no longer [`UiFonts::searched`]. + uncovered: HashSet, + /// The font database's generation when the last search started. + searched: u64, /// The fonts added to egui, by name. added: HashSet, /// The faces covering the characters being looked for (native: looked for on a thread). #[cfg(not(target_arch = "wasm32"))] - pending: Option>>>, + pending: Option>, + /// The search thread can't be created (tests). + #[cfg(all(test, not(target_arch = "wasm32")))] + spawn_fails: bool, } impl UiFonts { /// After a frame is laid out: add the fallback fonts found since the last frame, and look for /// fonts covering the characters this frame painted that the UI fonts lack. pub(crate) fn frame(&mut self, ctx: &egui::Context) { + self.frame_in(ctx, FontDb::global(), MISSING_GLYPHS.get().copied().unwrap_or(|_| {})); + } + + /// [`UiFonts::frame`] looking through `db`, reporting uncovered characters to `report`. + fn frame_in(&mut self, ctx: &egui::Context, db: &'static FontDb, report: fn(&[char])) { #[cfg(not(target_arch = "wasm32"))] - if let Some(faces) = self.pending.as_ref().and_then(|rx| rx.try_recv().ok()) { + if let Some(found) = self.pending.as_ref().and_then(|rx| rx.try_recv().ok()) { self.pending = None; - self.install(ctx, &faces); + self.found(ctx, found, report); + } + let mut missing = self.missing(ctx); + #[cfg(not(target_arch = "wasm32"))] + let idle = self.pending.is_none(); + #[cfg(target_arch = "wasm32")] + let idle = true; + // A font added since (a web face fetched for them) may cover them now. + let retry: Vec = + if idle && !self.uncovered.is_empty() && db.generation() != self.searched { self.uncovered.drain().collect() } else { vec![] }; + if !retry.is_empty() { + missing.extend_from_slice(&retry); + missing.sort_unstable(); + missing.dedup(); } - let missing = self.missing(ctx); if missing.is_empty() { return; } - let find = move || { - let mut faces: Vec> = vec![]; - for c in missing { - if let Some(f) = FontDb::global().face_covering(c) - && !faces.iter().any(|x| x.id() == f.id()) - { - faces.push(f); - } - } - faces - }; + #[cfg(not(target_arch = "wasm32"))] + let looked_for = missing.clone(); + let find = move || search(db, missing, FontDb::face_covering); // Native: the installed fonts are read off the UI thread. Characters met meanwhile wait for // the next search (they aren't marked seen until then). #[cfg(not(target_arch = "wasm32"))] { let (tx, rx) = std::sync::mpsc::channel(); let repaint = ctx.clone(); - let spawned = std::thread::Builder::new().name("ui-font-fallback".into()).spawn(move || { + let spawned = self.spawn_search(move || { // The receiver is gone only when the app is. let _ = tx.send(find()); repaint.request_repaint(); }); if spawned.is_ok() { self.pending = Some(rx); + } else { + // Not looked for: the characters met this frame are looked for when painted again, + // and the ones no font covered wait for the fonts to change again. + for c in looked_for.iter().filter(|c| !retry.contains(c)) { + self.seen.remove(c); + } + self.uncovered.extend(retry); } } // The web has only the loaded fonts to look through: quick, on this thread. #[cfg(target_arch = "wasm32")] - self.install(ctx, &find()); + self.found(ctx, find(), report); + } + + /// Run `search` on a thread of its own. + #[cfg(not(target_arch = "wasm32"))] + fn spawn_search(&self, search: impl FnOnce() + Send + 'static) -> std::io::Result<()> { + #[cfg(test)] + if self.spawn_fails { + return Err(std::io::Error::other("no thread for the font search")); + } + std::thread::Builder::new().name("ui-font-fallback".into()).spawn(search).map(|_| ()) + } + + /// Add the faces a search found, and keep (and report) the characters it found no face for. + fn found(&mut self, ctx: &egui::Context, found: Found, report: fn(&[char])) { + self.install(ctx, &found.faces); + self.searched = found.generation; + if !found.uncovered.is_empty() { + report(&found.uncovered); + self.uncovered.extend(found.uncovered); + } } /// Characters painted this frame that the UI fonts lack and haven't been looked for, now @@ -135,8 +218,14 @@ impl UiFonts { /// Wait for the font search running, if any, and add what it found (tests). #[cfg(test)] pub(crate) fn finish(&mut self, ctx: &egui::Context) { - if let Some(faces) = self.pending.take().and_then(|rx| rx.recv().ok()) { - self.install(ctx, &faces); + self.finish_with(ctx, |_| {}); + } + + /// [`UiFonts::finish`], reporting uncovered characters to `report` (tests). + #[cfg(test)] + fn finish_with(&mut self, ctx: &egui::Context, report: fn(&[char])) { + if let Some(found) = self.pending.take().and_then(|rx| rx.recv().ok()) { + self.found(ctx, found, report); } } } @@ -399,8 +488,111 @@ mod tests { for c in installed { assert!(has_glyph(&ctx, c), "{c} has a glyph"); } - // Looked for once: a later frame starts no search. + // Looked for once: a later frame starts no search, unless characters no font covered are + // looked for again because the fonts changed (other tests add fonts meanwhile). + let searched = fonts.searched; frame(&ctx, &mut fonts, text); - assert!(fonts.pending.is_none()); + assert!(fonts.pending.is_none() || FontDb::global().generation() != searched, "a search with the fonts unchanged"); + } + + thread_local! { + static REPORTED: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; + } + + fn report(chars: &[char]) { + REPORTED.with(|r| r.borrow_mut().extend_from_slice(chars)); + } + + /// Run a frame painting `text` with fallbacks looked for in `db`, then wait for the search. + fn frame_in(ctx: &egui::Context, fonts: &mut UiFonts, text: &str, db: &'static FontDb) { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + ui.label(text); + fonts.frame_in(ui.ctx(), db, report); + }); + out.textures_delta.clear(); + fonts.finish_with(ctx, report); + } + + /// A character painted while no font covers it is reported once, and draws once a font that + /// covers it is added (as the web fetches one), with no further search while the fonts stay + /// the same. The character is a private-use one, which no craft-fonts face covers either (the + /// database holds them when the build embeds craft-fonts). + #[test] + fn a_font_added_later_draws_characters_painted_before_it() { + use vectorcraft_text::test_fonts::{PRIVATE_USE_CHAR, PRIVATE_USE_FAMILY, private_use_font}; + let db: &'static FontDb = Box::leak(Box::new(FontDb::with_font_dirs(vec![]))); + // Scanned first, as the app's database is at startup: a first scan during the search would + // change the generation and start one more search. + db.families(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut fonts = UiFonts::default(); + let text = format!("Layer {PRIVATE_USE_CHAR}"); + frame_in(&ctx, &mut fonts, &text, db); + assert!(!has_glyph(&ctx, PRIVATE_USE_CHAR), "no font covers the character yet"); + assert_eq!(REPORTED.with(|r| r.borrow().clone()), [PRIVATE_USE_CHAR], "reported once"); + frame_in(&ctx, &mut fonts, &text, db); + assert!(fonts.pending.is_none() && REPORTED.with(|r| r.borrow().len()) == 1, "no new search while the fonts are the same"); + db.add_font(private_use_font().expect("the test face builds")); + assert!(db.face(PRIVATE_USE_FAMILY, "Regular").is_some()); + // The next frame looks again and adds the face; the one after draws with it. + frame_in(&ctx, &mut fonts, &text, db); + frame_in(&ctx, &mut fonts, &text, db); + assert!(has_glyph(&ctx, PRIVATE_USE_CHAR), "the added face draws the character"); + assert!(fonts.uncovered.is_empty()); + assert_eq!(REPORTED.with(|r| r.borrow().len()), 1, "a covered character is not reported again"); + } + + /// A font added while a search runs (another thread loading one) leaves the search's generation + /// older than the database's, so the next frame looks again for the characters it did not find. + #[test] + fn a_font_added_during_a_search_has_its_characters_looked_for_again() { + use vectorcraft_text::test_fonts::{PRIVATE_USE_CHAR, private_use_font}; + let db: &'static FontDb = Box::leak(Box::new(FontDb::with_font_dirs(vec![]))); + let found = search(db, vec![PRIVATE_USE_CHAR], |db, c| { + let face = db.face_covering(c); + db.add_font(private_use_font().expect("the test face builds")); + face + }); + assert_eq!(found.uncovered, [PRIVATE_USE_CHAR], "the lookup ran before the font was added"); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut fonts = UiFonts::default(); + fonts.found(&ctx, found, |_| {}); + // Painted before: the character is looked for again only because the fonts changed. + fonts.seen.insert(PRIVATE_USE_CHAR); + let text = format!("Layer {PRIVATE_USE_CHAR}"); + frame_in(&ctx, &mut fonts, &text, db); + frame_in(&ctx, &mut fonts, &text, db); + assert!(has_glyph(&ctx, PRIVATE_USE_CHAR), "the added face draws the character"); + assert!(fonts.uncovered.is_empty()); + } + + /// A search whose thread can't be created leaves its characters to be looked for later: a + /// character painted for the first time is looked for when it is painted again, and one no font + /// covered stays waiting for the fonts to change. + #[test] + fn a_search_that_cannot_start_keeps_its_characters() { + use vectorcraft_text::test_fonts::{PRIVATE_USE_CHAR, private_use_font}; + let db: &'static FontDb = Box::leak(Box::new(FontDb::with_font_dirs(vec![]))); + db.families(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut fonts = UiFonts { spawn_fails: true, ..UiFonts::default() }; + let text = format!("Layer {PRIVATE_USE_CHAR}"); + frame_in(&ctx, &mut fonts, &text, db); + assert!(fonts.pending.is_none() && !fonts.seen.contains(&PRIVATE_USE_CHAR), "not looked for yet"); + fonts.spawn_fails = false; + frame_in(&ctx, &mut fonts, &text, db); + assert!(fonts.uncovered.contains(&PRIVATE_USE_CHAR), "looked for when painted again"); + db.add_font(private_use_font().expect("the test face builds")); + fonts.spawn_fails = true; + frame_in(&ctx, &mut fonts, &text, db); + assert!(fonts.uncovered.contains(&PRIVATE_USE_CHAR), "still waiting to be looked for again"); + fonts.spawn_fails = false; + frame_in(&ctx, &mut fonts, &text, db); + frame_in(&ctx, &mut fonts, &text, db); + assert!(has_glyph(&ctx, PRIVATE_USE_CHAR), "the added face draws the character"); + assert!(fonts.uncovered.is_empty()); } } diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index fb291b8525..45818730d1 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -37,25 +37,27 @@ pub(crate) use buttons::{ use chips::gradient_chip_colors; pub use chips::{ProxyClicks, chip_button, chip_button_named, fill_stroke_proxy, gradient_chip, paint_chip, proxy_chip, swatch_tile}; pub use color::{ - FieldAxis, Live, RingResponse, SliderValue, WheelAxes, WheelResponse, channel_slider, channel_slider_named, channel_slider_valued, color_field, - color_mesh, color_slider, color_slider_named, color_slider_stepped, color_slider_valued, harmony_wheel, hex_field, hex_field_named, hsb32, - hue_ring, region_texture, ring_square, segment_color, segment_color_on, segmented_wheel, stepped_area, wheel_of, + FieldAxis, Live, RingResponse, SliderValue, WheelAxes, WheelResponse, channel_slider, channel_slider_named, channel_slider_stepped, + channel_slider_valued, color_field, color_mesh, color_slider, color_slider_named, color_slider_stepped, color_slider_valued, harmony_wheel, + hex_field, hex_field_named, hsb32, hue_ring, region_texture, ring_square, segment_color, segment_color_on, segmented_wheel, stepped_area, + wheel_of, }; -pub(crate) use color::{HEX_FIELD_CHARS, hex_text, pointer_phase}; +pub(crate) use color::{HEX_FIELD_CHARS, focus_by_pointer, hex_text, pointer_phase}; pub use drag::{ - PanelDrag, RowClick, SwatchRows, apply_row_click, art_drop, doc_preview, drag_ghost, drag_source, drop_target_outline, ghost_row, row_click, + PanelDrag, RowClick, SwatchRows, apply_row_click, art_drag_doc, art_drop, doc_preview, drag_art, drag_ghost, drag_source, drop_target_outline, + ghost_row, row_click, }; #[cfg(test)] use dropdowns::combo_button_id; pub(crate) use dropdowns::{combo, combo_menu, combo_menu_field_named, combo_named, field_focused_in, menu_min_width, popover_is_open}; pub use dropdowns::{ - dropdown, dropdown_icon_names, dropdown_named, dropdown_names, dropdown_names_named, dropdown_with, dropdown_with_named, list_scroll_style, - menu_room, menu_scroll, panel_scroll, popover, set_menu_floor, strip_scroll, + dropdown, dropdown_icon_names, dropdown_icon_names_sized, dropdown_named, dropdown_names, dropdown_names_named, dropdown_with, + dropdown_with_named, list_scroll_style, menu_room, menu_scroll, panel_scroll, popover, set_menu_floor, strip_scroll, }; #[cfg(test)] pub(crate) use dropdowns::{menu_floor, menu_room_either}; pub use labels::{dim_label, dim_name, divider, field_label, label_row, link_label, section_header, section_toggle, section_toggle_name, subheader}; -pub(crate) use labels::{dim_label_width, label_field, take_previous_label, text_width}; +pub(crate) use labels::{dim_label_width, field_panel_label, label_field, take_previous_label, text_width}; pub(crate) use numeric::{ANY, round_to, set_bare_numbers_are_points, typed_unit}; pub use numeric::{ SpinPick, mixed_field, mixed_field_named, num_field, num_field_live, num_field_named, num_field_refusing, num_field_within, @@ -210,7 +212,7 @@ pub(crate) mod accessibility_tests { let tree = tree(|ui| { icon_button(ui, "link", "Constrain Proportions", true, 24.0); toggle_icon(ui, "eye", true, 18.0, "Show all plates"); - toggle_icon(ui, "eye", false, 18.0, "Show/hide plate (Alt-click: only this plate)"); + toggle_icon(ui, "eye", false, 18.0, "Show/hide plate (Alt-click: only this plate; Alt-click again: all plates)"); orientation_button(ui, false, true, "Portrait"); orientation_button(ui, true, false, "Landscape"); layout_button(ui, &[(0, 0), (1, 0)], true, "Grid by Row"); @@ -220,7 +222,7 @@ pub(crate) mod accessibility_tests { let off = |label| assert_eq!(role_and_state(&tree, label), (Role::Button, Some(Toggled::False)), "{label}"); on("Constrain Proportions"); on("Show all plates"); - off("Show/hide plate (Alt-click: only this plate)"); + off("Show/hide plate (Alt-click: only this plate; Alt-click again: all plates)"); on("Portrait"); off("Landscape"); on("Grid by Row"); @@ -607,7 +609,7 @@ mod decimal_point_tests { } assert_eq!(mm("1,000.5"), None, "a point and a comma"); assert_eq!(mm("1,2,3"), None, "two commas"); - for thousand in ["1,000", "12,500 mm", "-1,000", "999,999mm"] { + for thousand in ["1,000", "12,500 mm", "-1,000", "+1,000", "999,999mm", "1,000\"", "1,000'"] { assert_eq!(mm(thousand), None, "{thousand} reads as thousands: refused, not a thousand times too small"); } for (text, want) in [("0,125", 0.125), ("1,25", 1.25), ("1,0000", 1.0), ("1,500+2", 3.5)] { @@ -651,6 +653,15 @@ mod field_number_tests { assert_eq!(field_number("50% / 2", "%", false), Some(25.0)); } + /// A resolution field reads the unit it shows: "200 ppp" in a French interface. + #[test] + fn a_resolution_field_reads_its_translated_unit() { + crate::i18n::set_current(crate::i18n::Lang::from_code("fr").unwrap()); + let read = [field_number("200 ppp", &crate::dialogs::ppi_suffix(), false), field_number("200", &crate::dialogs::ppi_suffix(), false)]; + crate::i18n::set_current(crate::i18n::Lang::EN); + assert_eq!(read, [Some(200.0), Some(200.0)]); + } + /// A thousands comma is refused inside Kerning's pair of parentheses and before `%` or the /// suffix, as it is in plain text, rather than read as a decimal comma (`(1,000)` as 1). #[test] diff --git a/crates/ui-egui/src/widgets/color.rs b/crates/ui-egui/src/widgets/color.rs index 2c7711321d..54d52a6ccf 100644 --- a/crates/ui-egui/src/widgets/color.rs +++ b/crates/ui-egui/src/widgets/color.rs @@ -12,7 +12,7 @@ pub enum Live { } /// A colour slider with a gradient track (`track(t)` gives the colour at 0..1) and a triangular -/// thumb below it, like Illustrator's Color panel. Returns the new normalized value and the phase. +/// thumb below it, as in the Color panel. Returns the new normalized value and the phase. pub fn color_slider(ui: &mut Ui, id: impl std::hash::Hash, value: f32, width: f32, track: &dyn Fn(f32) -> Color32) -> (Option, Live) { color_slider_named(ui, id, "", value, width, track) } @@ -141,7 +141,7 @@ pub fn color_slider_stepped( ) -> (Option, Live, Option) { let id = id_with(ui.scope_id(), id); let (resp, picked, phase) = color_rail(ui, id, name, shown.clone(), value, width, track); - let stepped = slider_keys(ui, &resp, shown); + let stepped = slider_keys(ui, &resp, shown, false); (picked, phase, stepped.filter(|_| picked.is_none())) } @@ -152,19 +152,27 @@ pub fn color_slider_stepped( /// `shown`'s units that a key or an action gives. pub fn stepped_area(ui: &Ui, resp: &Response, name: &str, shown: Option) -> Option { slider_info(ui, resp, name, shown.clone()); - slider_keys(ui, resp, shown) + slider_keys(ui, resp, shown, false) +} + +/// Gives the keyboard focus to the control `id` of [`stepped_area`] as a click or a drag on it +/// does, with no focus outline until a key steps it, for a control whose pointer input another +/// response reads. +pub(crate) fn focus_by_pointer(ui: &Ui, id: egui::Id) { + ui.memory_mut(|m| m.request_focus(id)); + ui.data_mut(|d| d.insert_temp(id.with("focused-by-pointer"), true)); } /// The focus, keys, actions and focus outline of [`color_slider_stepped`] on the control `resp`: -/// the number a key or an action gives. -fn slider_keys(ui: &Ui, resp: &Response, shown: Option) -> Option { +/// the number a key or an action gives. With `always`, a key or an action that leaves the number +/// as it was still gives it. +fn slider_keys(ui: &Ui, resp: &Response, shown: Option, always: bool) -> Option { let id = resp.id; // Focus a click or a drag gave shows no outline until a key steps the rail: the outline tells // a keyboard user where the focus is, and after a drag it only framed the rail. let by_pointer = id.with("focused-by-pointer"); if resp.drag_started() || resp.clicked() { - resp.request_focus(); - ui.data_mut(|d| d.insert_temp(by_pointer, true)); + focus_by_pointer(ui, id); } let focused = ui.memory(|m| m.has_focus(id)); if !focused { @@ -177,7 +185,7 @@ fn slider_keys(ui: &Ui, resp: &Response, shown: Option) -> Option(by_pointer)); @@ -190,8 +198,9 @@ fn slider_keys(ui: &Ui, resp: &Response, shown: Option) -> Option Option { +/// readers' actions on it ([`color_slider_stepped`]); `None` when they leave it as it was, unless +/// `always` and a key or an action came. +fn rail_step(ui: &Ui, id: egui::Id, focused: bool, always: bool, s: &SliderValue) -> Option { use egui::accesskit::{Action, ActionData}; use egui::{Event, Key}; let (lo, hi) = (*s.range.start(), *s.range.end()); @@ -208,6 +217,8 @@ fn rail_step(ui: &Ui, id: egui::Id, focused: bool, s: &SliderValue) -> Option Option return true, } + asked = true; false }); }); @@ -246,8 +258,9 @@ fn rail_step(ui: &Ui, id: egui::Id, focused: bool, s: &SliderValue) -> Option 0; + v = by(v, up as f64 - down as f64).clamp(lo, hi); // The last set-value request this frame. let set = i.accesskit_action_requests(id, Action::SetValue).last().and_then(|request| match request.data { Some(ActionData::NumericValue(value)) if value.is_finite() => Some(value), @@ -260,9 +273,10 @@ fn rail_step(ui: &Ui, id: egui::Id, focused: bool, s: &SliderValue) -> Option Color32, ) -> (Option, Live) { + let id = id_with(ui.scope_id(), id); + let (_, picked, phase) = channel_rail(ui, id, name, shown, value, true, size, track); + (picked, phase) +} + +/// [`channel_slider_valued`] that also responds to the keyboard and to screen readers' actions as +/// the rail of [`color_slider_stepped`] does: a click or a drag gives it the keyboard focus, and +/// while it has the focus ↑ and → raise the number `shown` holds and ↓ and ← lower it. When not +/// `marked`, the rail draws no arrows and screen readers read 0, as [`hue_ring`] does, while the +/// keys and actions still step from `shown` and give a number even when it equals `shown`'s, as +/// [`color_field`] does. Returns the new value from 0 to 1 that a click or a +/// drag gives, its phase, and the number in `shown`'s units that a key or an action gives. +#[allow(clippy::too_many_arguments)] +pub fn channel_slider_stepped( + ui: &mut Ui, + id: impl std::hash::Hash, + name: &str, + shown: Option, + value: f32, + marked: bool, + size: Vec2, + track: &dyn Fn(f32) -> Color32, +) -> (Option, Live, Option) { + let id = id_with(ui.scope_id(), id); + let read = if marked { shown.clone() } else { shown.as_ref().map(|s| SliderValue { value: 0.0, text: None, ..s.clone() }) }; + let (resp, picked, phase) = channel_rail(ui, id, name, read, value, marked, size, track); + let stepped = slider_keys(ui, &resp, shown, !marked); + (picked, phase, stepped.filter(|_| picked.is_none())) +} + +/// The vertical rail of [`channel_slider_valued`] with the id `id`, with its arrows at `value` +/// when `marked`: its response, the new value from 0 to 1 that a click or drag gives and the +/// phase. +#[allow(clippy::too_many_arguments)] +fn channel_rail( + ui: &mut Ui, + id: egui::Id, + name: &str, + shown: Option, + value: f32, + marked: bool, + size: Vec2, + track: &dyn Fn(f32) -> Color32, +) -> (Response, Option, Live) { let t = Tokens::get(ui.ctx()); let (rect, _) = ui.allocate_exact_size(size, Sense::hover()); - let resp = ui.interact(rect, id_with(ui.scope_id(), id), Sense::click_and_drag()); + let resp = ui.interact(rect, id, Sense::click_and_drag()); let bar = rect.shrink2(vec2(6.0, 0.0)); gradient_strip(ui, bar, (bar.height() / 2.0).ceil().max(2.0) as usize, true, track); ui.painter().rect_stroke(bar, 0.0, Stroke::new(1.0, t.border), StrokeKind::Outside); let y = bar.bottom() - value.clamp(0.0, 1.0) * bar.height(); let fill = if resp.dragged() || resp.hovered() { t.text_strong } else { t.icon }; - for (x, d) in [(rect.left(), 1.0), (rect.right(), -1.0)] { + for (x, d) in [(rect.left(), 1.0), (rect.right(), -1.0)].into_iter().filter(|_| marked) { let tip = pos2(x + d * 5.0, y); ui.painter().add(egui::Shape::convex_polygon(vec![tip, pos2(x, y + 4.0 * d), pos2(x, y - 4.0 * d)], fill, Stroke::NONE)); } slider_info(ui, &resp, name, shown); - match pointer_phase(&resp) { + let (picked, phase) = match pointer_phase(&resp) { Some((p, phase)) => (Some(((bar.bottom() - p.y) / bar.height()).clamp(0.0, 1.0)), phase), None => (None, Live::Idle), - } + }; + (resp, picked, phase) } /// A hex colour field (`E67828`, no `#`) after a `#` label. Returns the text on commit when it diff --git a/crates/ui-egui/src/widgets/drag.rs b/crates/ui-egui/src/widgets/drag.rs index a3df5a4098..e0eec69ecd 100644 --- a/crates/ui-egui/src/widgets/drag.rs +++ b/crates/ui-egui/src/widgets/drag.rs @@ -13,19 +13,23 @@ pub enum PanelDrag { /// it is dropped. Paint { paint: Paint, params: serde_json::Value, rows: Option, library: Option<(String, String)> }, /// The Appearance panel's thumbnail: art it is dropped on takes object `0`'s appearance - /// (`appearance.copyFrom`); the Graphic Styles panel makes a style of it. + /// (`appearance.copyFrom`); the Graphic Styles panel makes a style of it, or with Alt held + /// replaces the style it is dropped on with it (`graphicStyle.redefine`). Appearance(vectorcraft_doc::NodeId), /// A Graphic Styles panel style: art it is dropped on takes it (`graphicStyle.apply` with its - /// `ids`); the panel moves it to where it is dropped. + /// `ids`); the panel moves it to where it is dropped, or with Alt held replaces the style it is + /// dropped on with its look (`graphicStyle.redefine` with `from`). GraphicStyle(String), /// The selected art, dragged off the canvas with the Selection tool: the Graphic Styles panel - /// makes a style of the first object (`graphicStyle.new`), the Symbols panel a symbol of it all + /// makes a style of the first object (`graphicStyle.new`), or with Alt held replaces the style + /// it is dropped on with that object's look (`graphicStyle.redefine`), the Symbols panel a symbol of it all /// (`symbol.new`), the Swatches panel a pattern swatch of a copy (`object.pattern.make`) and the /// Brushes panel an Art brush (`brush.new`). Art(Vec), - /// A Symbols panel symbol: the canvas places an instance of it centred where it is dropped - /// (`symbol.place`). - Symbol(String), + /// A Symbols panel symbol (`document`: the uid of the document whose panel it was dragged + /// from): the canvas places an instance of it centered where it is dropped, adding the symbol + /// first when another document is active by then (`symbol.placeFromDocument`). + Symbol { document: u64, name: String }, /// A symbol of a symbol library panel (`name`: its name in `library`): the canvas adds it to the /// document's Symbols and places an instance where it is dropped (`symbol.addFromLibrary` with /// `place`). @@ -48,14 +52,34 @@ pub enum PanelDrag { } /// A panel list `zone` that takes art dragged off the canvas: outlined while art is held over it; -/// → the dragged ids when it is released there. +/// → the dragged ids when the primary button is released there (the release of another button +/// ends the drag). pub fn art_drop(ui: &Ui, zone: &Response) -> Option> { let drag = zone.dnd_hover_payload::()?; let PanelDrag::Art(ids) = &*drag else { return None }; ui.painter().rect_stroke(zone.rect, 0.0, Stroke::new(1.5, Tokens::get(ui.ctx()).accent), StrokeKind::Inside); + if !ui.input(|i| i.pointer.button_released(egui::PointerButton::Primary)) { + return None; + } zone.dnd_release_payload::().map(|_| ids.iter().map(|id| id.0).collect()) } +/// Key of the document whose art a [`PanelDrag::Art`] carries. +fn art_doc_id() -> egui::Id { + egui::Id::unique("panel-drag-art-doc") +} + +/// Start (or keep up) a panel drag of the art `ids` of document `uid`, dragged off its canvas. +pub fn drag_art(ctx: &egui::Context, uid: u64, ids: Vec) { + ctx.data_mut(|d| d.insert_temp(art_doc_id(), uid)); + egui::DragAndDrop::set_payload(ctx, PanelDrag::Art(ids)); +} + +/// The document (`uid`) whose art the last [`drag_art`] carried. +pub fn art_drag_doc(ctx: &egui::Context) -> Option { + ctx.data(|d| d.get_temp::(art_doc_id())) +} + /// The Swatches panel rows a drag from that panel moves: the swatch, None, Registration or colour /// group under the pointer when the drag started (`grabbed`) and `names`, the panel selection when /// the grabbed one is part of it (only colour groups, or only swatches, like the grabbed one), in diff --git a/crates/ui-egui/src/widgets/dropdowns.rs b/crates/ui-egui/src/widgets/dropdowns.rs index 7f088f25ef..1b2d4b421f 100644 --- a/crates/ui-egui/src/widgets/dropdowns.rs +++ b/crates/ui-egui/src/widgets/dropdowns.rs @@ -50,11 +50,23 @@ pub fn dropdown_icon_names( width: f32, icon_size: f32, icon: impl Fn(&Ui, Rect, usize, egui::Color32, bool), +) -> Option { + dropdown_icon_names_sized(ui, id, current, options, width, Vec2::splat(icon_size), icon) +} + +/// [`dropdown_icon_names`] with icons of any size, for a picture wider than it is tall, such as a +/// line with an arrowhead. +pub fn dropdown_icon_names_sized( + ui: &mut Ui, + id: impl std::hash::Hash, + current: Option, + options: &[&str], + width: f32, + icon_size: Vec2, + icon: impl Fn(&Ui, Rect, usize, egui::Color32, bool), ) -> Option { let icon = &icon; - let atom = move |i: usize, highlighted: bool| { - egui::Atom::paint(Vec2::splat(icon_size), move |ui, a| icon(ui, a.rect, i, a.fallback_text_color, highlighted)) - }; + let atom = move |i: usize, highlighted: bool| egui::Atom::paint(icon_size, move |ui, a| icon(ui, a.rect, i, a.fallback_text_color, highlighted)); let shown = match current.and_then(|i| options.get(i).map(|name| (i, *name))) { Some((i, name)) => (atom(i, false), egui::RichText::new(name).size(12.0)).into_atoms(), None => egui::RichText::new("").size(12.0).into_atoms(), diff --git a/crates/ui-egui/src/widgets/labels.rs b/crates/ui-egui/src/widgets/labels.rs index 221d418a46..d7c0d9813d 100644 --- a/crates/ui-egui/src/widgets/labels.rs +++ b/crates/ui-egui/src/widgets/labels.rs @@ -144,6 +144,14 @@ pub fn field_label(ui: &mut Ui, text: impl Into) -> Response { resp } +/// A field's label (`text` as given) that a click follows to a panel ([`scrub::panel_label`]): +/// before a numeric field it scrubs the field and names it. +pub fn field_panel_label(ui: &mut Ui, text: egui::RichText) -> Response { + let resp = scrub::panel_label(ui, text); + remember_next_label(ui, resp.id); + resp +} + /// [`dim_label`] for a name that is user or file data (a swatch, style, artboard or font name): /// shown as it is, never translated. pub fn dim_name(ui: &mut Ui, text: &str) -> Response { @@ -176,7 +184,7 @@ pub fn subheader(ui: &mut Ui, text: &str) { ui.label(egui::RichText::new(tl!(text)).size(12.5).color(t.text)); } -/// A label drawn with a dotted underline (Illustrator's link labels: "Stroke:", "Opacity:"). +/// A label drawn with a dotted underline (the panels' link labels: "Stroke:", "Opacity:"). pub fn link_label(ui: &mut Ui, text: &str) -> Response { let t = Tokens::get(ui.ctx()); let galley = ui.painter().layout_no_wrap(tl!(text).to_string(), egui::FontId::proportional(12.5), t.text_strong); diff --git a/crates/ui-egui/src/widgets/look_tests.rs b/crates/ui-egui/src/widgets/look_tests.rs index 274861386b..0b89811929 100644 --- a/crates/ui-egui/src/widgets/look_tests.rs +++ b/crates/ui-egui/src/widgets/look_tests.rs @@ -421,7 +421,7 @@ fn a_popover_stays_open_for_a_click_on_its_anchor_or_during_a_panel_drag() { shown.get() }; let far = Some(pos2(500.0, 350.0)); - let panel_drag = || Some(PanelDrag::Symbol("s".into())); + let panel_drag = || Some(PanelDrag::Symbol { document: 1, name: "s".into() }); // Whether it is open after: a click elsewhere; a click on its anchor that doesn't toggle it; // a panel drag released elsewhere. let open = [open_after_click(far, None), open_after_click(None, None), open_after_click(far, panel_drag())]; @@ -524,3 +524,28 @@ fn kerning_reads_parentheses_around_its_text_with_a_manual_value_too() { assert_eq!(typed(automatic, "(1,5)"), Some(SpinPick::Value(1.5)), "a decimal comma, automatic: {automatic}"); } } + +/// Enter on text that reads as no number in a range field refuses it as a unit field does: the +/// field flashes and an open dialog is not confirmed with the old value. +#[test] +fn a_range_field_refuses_text_that_reads_as_no_number() { + let typed = |text: &str| { + let ctx = themed(Default::default()); + let picked = std::cell::Cell::new(None); + let mut add = |ui: &mut Ui| { + if let Some(v) = range_field(ui, "count", 12.0, 0.0..=100.0, "", 0, 80.0) { + picked.set(Some(v)); + } + }; + arm_field_focus(&ctx, "count"); + frame(&ctx, 0.0, vec![], &mut add); + frame(&ctx, 0.1, vec![], &mut add); + let enter = |pressed| egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; + frame(&ctx, 0.2, vec![egui::Event::Text(text.into()), enter(true), enter(false)], &mut add); + let refused = ctx.data_mut(|d| d.remove_temp::(dialog_reject_commit_flag())).unwrap_or(false); + (picked.get(), refused) + }; + assert_eq!(typed("40"), (Some(40.0), false), "a number commits"); + assert_eq!(typed("abc"), (None, true), "text that reads as no number is refused"); + assert_eq!(typed("(10+5)*2"), (None, true), "parentheses the field doesn't read are refused"); +} diff --git a/crates/ui-egui/src/widgets/numeric.rs b/crates/ui-egui/src/widgets/numeric.rs index 89ce8d70d5..a9d4020ab3 100644 --- a/crates/ui-egui/src/widgets/numeric.rs +++ b/crates/ui-egui/src/widgets/numeric.rs @@ -22,29 +22,7 @@ pub(crate) fn typed_unit(ctx: &egui::Context, unit: Unit) -> Unit { if bare_points && unit == Unit::Picas { Unit::Points } else { unit } } -/// `text` typed in a numeric field, with a decimal comma read as a point: `0,1 mm` is `0.1 mm` -/// (#3837), and each number of a sum reads its own separator, so `100.5 mm-0,5` (a comma typed -/// after the value the field shows) is 100 mm (#5684). A number written with both separators has -/// two points once read, so `1,000.5` and `1.234,5` are refused rather than guessed at; so is a -/// number that reads as thousands ([`thousands`]). -pub(super) fn decimal_point(text: &str) -> std::borrow::Cow<'_, str> { - if text.contains(',') && !thousands(text) { text.replace(',', ".").into() } else { text.into() } -} - -/// Is `text` a number written with a thousands comma, as `1,000` or `12,500 mm`: one to three -/// digits (not a lone 0), a comma, exactly three digits, then at most a unit? Read as a decimal it -/// would be a thousand times too small, so the field refuses it instead (`0,125` and `1,25` are -/// decimals). -fn thousands(text: &str) -> bool { - let number = text.trim().trim_start_matches('-'); - let Some((whole, rest)) = number.split_once(',') else { return false }; - let (part, unit) = rest.split_at(rest.find(|c: char| !c.is_ascii_digit()).unwrap_or(rest.len())); - (1..=3).contains(&whole.len()) - && whole.bytes().all(|b| b.is_ascii_digit()) - && !whole.starts_with('0') - && part.len() == 3 - && unit.trim().chars().all(char::is_alphabetic) -} +pub(super) use vectorcraft_doc::decimal_point; /// A recessed numeric field showing `value` (points) in `unit`. Returns the new value (points) /// when the user commits (Enter / focus loss / Shift+Enter, which keeps the focus outside dialogs). @@ -142,7 +120,8 @@ fn unit_field( /// [`unit_field`] whose blank field (`value` is `None`) steps from `blank_from` (points) with /// ↑/↓ and the wheel instead of doing nothing. With `refuse_outside`, a value typed outside -/// `bounds` is refused as text that doesn't read is, rather than kept at the nearer end. +/// `bounds` is refused as text that doesn't read is, rather than kept at the nearer end. Armed +/// with id salt `id` ([`arm_field_focus`]), it takes the keyboard focus with its value selected. #[allow(clippy::too_many_arguments)] fn unit_field_from( ui: &mut Ui, @@ -160,10 +139,18 @@ fn unit_field_from( empty: &str, refuse_outside: bool, ) -> Option { + let armed = take_armed_focus(ui, &id); let id = id_with(ui.scope_id(), id); let shown = value.map(|v| unit.format(v)).unwrap_or_else(|| empty.to_string()); take_dialog_focus(ui, id, &shown); + if armed { + focus_field(ui, id, &shown); + } let (mut buf, commit, resp, rect) = recessed_text(ui, id, &shown, width, 1, label, name); + if armed { + // A field armed while it has focus keeps the text typed into it: select all of that text. + select_all(ui, id, &buf); + } select_all_on_focus(ui, &resp, &buf); // ↑/↓ and the wheel step in the field's unit; a drag on its label scrubs it. let typed = typed_unit(ui.ctx(), unit); @@ -293,8 +280,8 @@ pub(super) fn shown_alike(show: impl Fn(f64) -> String) -> impl Fn(f64, f64) -> /// goes to the next whole number in its direction (5.1 up to 6, down to 5), a Ctrl/Cmd step goes to /// the next tenth, and a Shift step adds or takes ten. Steps stop at the field's `bounds` (#3370: /// a weight stops at 0, a miter limit at 1), and a plain step also stops at each of `stops` -/// ([`step_through`]). The new value is applied at once, as in -/// Illustrator's panels and dialogs, and the new text replaces `buf`, all selected so typing +/// ([`step_through`]). The new value is applied at once, and +/// the new text replaces `buf`, all selected so typing /// replaces it when focused. Returns the new number when a step was taken. An enabled field takes /// the wheel without taking keyboard focus, and the panel under it doesn't scroll, when the wheel /// stream began over the field and the pointer was moved onto it, or pressed on it, after the @@ -745,7 +732,7 @@ impl egui::Plugin for WheelTailPlugin { /// A [`num_field`] for a width or height (Transform panel, Properties panel, Control bar): Ctrl/Cmd+Enter /// also commits it and ends its editing, as Enter does, and [`enter_modifiers`] reports Command. A -/// percentage typed alone (`50%`) is that share of the size shown, as in Illustrator (#2401). +/// percentage typed alone (`50%`) is that share of the size shown (#2401). pub fn size_field(ui: &mut Ui, id: impl std::hash::Hash, value: Option, unit: Unit, width: f32) -> Option { size_field_named(ui, id, None, value, unit, width) } @@ -930,7 +917,19 @@ fn bounded_field_reading( let stepped = step_value(ui, &resp, &mut buf, bounds, (read, show), step, &[]).map(|v| round_to(v, decimals)); let scrubbed = scrub::field(ui, id, rect, &buf, value, decimals, bounds); if commit && buf != shown { - read(&buf) + let typed = read(&buf); + if typed.is_none() { + // Text that reads as no number is refused as [`unit_field_from`] refuses it: the field + // flashes, shows its value again, and an open dialog is not confirmed by this Enter. + let end = ui.input(|i| i.time + 0.25); + ui.data_mut(|d| { + d.remove::(id); + d.insert_temp(id.with("invalid-flash"), end); + }); + crate::widgets::reject_dialog_commit(ui.ctx()); + ui.ctx().request_repaint(); + } + typed } else if let Some(v) = stepped.or(scrubbed).filter(|&v| Some(v) != value) { Some(v) } else if live && resp.changed() { diff --git a/crates/ui-egui/src/workspaces.rs b/crates/ui-egui/src/workspaces.rs index 2a764a6968..886589b5f0 100644 --- a/crates/ui-egui/src/workspaces.rs +++ b/crates/ui-egui/src/workspaces.rs @@ -94,7 +94,7 @@ pub const ESSENTIALS: &str = "Essentials"; /// Touch workspace (Window → Workspace → Touch; Preferences › Devices › Enable Touch Workspace). pub const TOUCH: &str = "Touch"; -/// Built-in workspaces, in Illustrator's menu order (Essentials first). +/// Built-in workspaces, in menu order (Essentials first). pub fn builtins() -> Vec { let base = Workspace::default(); let w = |name: &str, f: &dyn Fn(&mut Workspace)| { diff --git a/docs/control-protocol.md b/docs/control-protocol.md index adac088a13..e3d6636c3e 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -131,7 +131,10 @@ the two can still win that race. Swatch editors: `engine.execute` with `ui.swatchOptions {name}` opens the `swatchOptions` dialog for a colour swatch (fields `name`, `spot`, `global`, `mode`: `gray`/`rgb`/`hsb`/`lab`/`cmyk`/`web`, `color`: `"#rrggbb"` or a colour object, `preview`), which previews on the canvas while open; `ui.dialog.confirm` applies it with `swatch.edit` as one undo -step and `ui.dialog.cancel` rolls the preview back. For a gradient swatch the dialog has `name` only (it shows the +step and `ui.dialog.cancel` rolls the preview back. Under the colour it shows the out-of-gamut warning (in RGB, HSB +and Lab) and the out-of-web-color warning (in every mode but `web`); a click on one sets `color` to the correction +and `mode` to `cmyk` for the gamut correction, or to `rgb` for a web correction of a `gray`, `lab` or `cmyk` colour. +The warnings are not fields: set `color` and `mode` to apply a correction from a script. For a gradient swatch the dialog has `name` only (it shows the gradient) and OK renames it; pattern swatches open pattern editing instead. Dropping a gradient (or colour) on a swatch of its kind in the Swatches panel with Alt held replaces it (`swatch.edit {name, paint}`), unless that is a tint swatch. A swatch dragged from the panel with Alt held also replaces the swatch of its kind it is dropped on, @@ -265,7 +268,9 @@ My Themes tab lists the saved themes; every action runs a command (`colorTheme.s Color Wheel panel (`window.panel {panel: "colorWheel"}`): a hue ring around a saturation and brightness square. A pick runs the commands the Color panel's sliders run: `paint.setFill` or `paint.setStroke` with `keepModel`, `paint.editGradient` for a gradient's selected stop, and `paint.freeform.setPoint` for a freeform gradient's selected -point (the first stop or point when none is selected). +point (the first stop or point when none is selected). `ui.colorWheel {view?, channel?}` shows the wheel or the box (a +color field with a channel strip at its right) and picks the box's channel; it returns the settings, and `ui.inspect` +reports them as `ui.color_wheel`. Edit Colors dialogs: `ui.colorBalanceDialog` opens Adjust Colors (`colorBalance`: fields `mode` `gray`/`rgb`/`cmyk`/ `global`, the channels `r` `g` `b` / `c` `m` `y` `k` / `gray` / `tint` (global mode) from −100 to 100, `convert`, `fill`, `stroke`, @@ -302,7 +307,11 @@ right-click menu has Remove Color too. The base color can't be removed. A remove has current colors and art or a group is open: it then keeps them with `to: null`, that art keeps its colors, and the group's swatch at that place is removed. A row with no current colors recolors no art; with a group, the new color of one with `added: true` that is not excluded is added to the group after the group's other colors, and a row made with New Row adds none. -Setting `colors`, a preserve flag or `limitTo` reduces the rows again (also on `ui.dialog.confirm`). The dialog previews +`groupStorage` shows the Color Groups list (true when the dialog opens); setting `group` to a color group's name makes +it the group being edited, as opening on it does, and refuses a name no group has; `groupAction` (`save`, `new` or +`delete`) runs the list's Save Changes, New Color Group or Delete button on the next frame, or first on confirm (see +`docs/mcp.md`). Setting `colors`, a preserve flag or `limitTo` reduces the rows again (also on `ui.dialog.confirm`). +The dialog previews `recolor.apply` on the canvas; confirm keeps it as one undo step (with a group, the group is rewritten in the same step; with no art selected only the group changes). In the Swatches panel, double-clicking a colour group's folder, or the options button while a group is selected, opens it. @@ -496,7 +505,10 @@ the desktop each floating window is an OS window of its own; on the web and on W window. `ui.toolbar_pos` in `ui.inspect` is the Tools panel's corner (null: docked); `window.panel.float` and `window.panel.dock` with `panel: "tools"` float it at `x`, `y` or dock it on the window's left edge. With `window.toolsBesideCanvas {on?}` (Window › Toolbars › Keep Tools Beside the Canvas, off by default; `ui.tools_beside_canvas`) -the docked Tools panel sits between left-side panels and the canvas, and `window.panel.dock` docks it there. +the docked Tools panel sits between left-side panels and the canvas, and `window.panel.dock` docks it there. Dropping +a floating Tools panel on the canvas's left edge, right of panels docked on the left, turns the setting on, and on the +window's left edge turns it off; with no panels docked on the left, a drop leaves the setting as it is +(`docs/mcp.md` › Tools panel placement). Flatten Transparency: `ui.flattenTransparencyDialog` opens the `flattenTransparency` dialog for the selection (fields `preset`: a preset name, setting it loads that preset's options; the option keys of @@ -592,6 +604,9 @@ Width Point Edit: double-clicking a width point with the Width tool, or `ui.widt `widthPoint` dialog (fields `id`, `index`, `t`, `side1` and `side2`: the left and right widths in points, `linked`, `adjustAdjoining`). `ui.dialog.confirm` runs `stroke.widthPoint.set` with them; `ui.dialog.set {field: "discard", value: true}` then confirm (the Delete button) removes the point with `stroke.widthPoint.remove`. +Either half of a discontinuous point opens both: `index` is the incoming half, and `outIndex`, `outSide1`, `outSide2` +and `outLinked` hold the outgoing half; `single` (`""`, `"incoming"` or `"outgoing"`) is Single Width Only. Confirm +sets both halves in one `stroke.widthPoint.set` (one undo step), and Delete removes both. Corners: double-clicking a Live Corners widget with the Selection or Direct Selection tool, or `ui.corners {id?, corners?}`, opens the `corners` dialog for a path's corners (the Direct-Selected ones, else every corner; fields `id`, @@ -729,13 +744,14 @@ folder, then opens the dialog searching it. The web shows a status line instead disabled there. Text Import Options: placing a `.txt` file through the app (`file.place` with a file and no `text` options, the Place -dialog, a drop) opens the `textImport` dialog (fields `platform`: `windows`/`mac`, `characterSet`: `unicode`/`ansi`, +dialog, a drop) opens the `textImport` dialog (fields `platform`: `windows`/`mac`, `characterSet`: a `text.characterSet` value, `removeLineReturns`, `removeParagraphReturns`, `replaceSpaces`, `spaces`). `ui.dialog.confirm` places the file as area type with those options (`file.place {text: {…}}`). System clipboard formats: through the desktop app, `edit.copy`, `edit.cut`, `artboard.copy` and `artboard.cut` publish what `clipboard.flavours` lists to the system clipboard (once they are written, the status bar shows the first of the PNG's and PDF's -`warnings`, such as an image that couldn't be decoded), and every Paste command first loads what another app copied (`clipboard.importSvg`, +`warnings`, such as an image that couldn't be decoded, and how many there are, and hovering the message lists them, unless +another message has replaced the Copy or Cut's meanwhile), and every Paste command first loads what another app copied (`clipboard.importSvg`, `importPdf`, `importEps`, `importText` or `importImage`, centred in the view; the desktop app reads PDF and EPS from the Windows clipboard and, with SVG, from the macOS pasteboard, and an `.eps` file, or a `.ai` or `.ait` file that holds a PDF or PostScript, copied in a file manager anywhere; a copied `.ai` or `.ait` file that holds a PDF loads with `importPdf {editingData: true}`, which reads its editing data); an import error answers the Paste with that error and pastes nothing. Cmd+V also pastes a bitmap or PDF with no text beside it (on the key's release, as egui sends no @@ -818,13 +834,21 @@ selected slices. Hidden or locked slices (`view.slices.hide`, `view.slices.lock` EPS Options: Export As… with the EPS format (`file.exportAs {format: "eps"}`, then the save dialog), or `ui.epsOptionsDialog {path?, …document.exportEps options}` for agents, opens the `epsOptions` dialog. Its fields are `document.export` params: `previewFormat` (`none`, `tiffBw`, `tiffColor`), `transparentPreview`, `overprints` -(`preserve`, `discard`), `flattenerPreset` (a built-in or saved preset's name), `includeLinkedFiles`, `thumbnails`, +(`preserve`, `discard`), `flattenerPreset` (a built-in or saved preset's name), `flattener` (custom flattener options +over the preset, as `object.flattenTransparency` takes them), `includeLinkedFiles`, `thumbnails`, `cmykPostScript`, `compatibleGradients`, `level` (`2`, `3`), plus `path` and the artboard choice (`useArtboards`, `range`). `ui.dialog.confirm` checks them (a bad value or an unknown preset keeps the dialog open), remembers them for the next EPS Options and writes the file(s), asking for a path when there is none. With Use Artboards and two or more artboards, it writes a central file of the whole document under the chosen name and one `{stem}_{artboard}.eps` per artboard. When no art shows, it writes only the artboard files. +The Custom… button beside the preset opens the `epsFlattenerOptions` dialog over EPS Options, on the options the +export would use. Its fields are the flattener options; `preserveAlpha` is always off, and overprints are kept only +with `overprints: "preserve"`. Its `ui.dialog.confirm` sets every option as `flattener` (the preset then shows +[Custom]) and goes back to EPS Options; `ui.dialog.cancel` goes back with the options unchanged. Choosing a preset, +in the dropdown or with `ui.dialog.set {flattenerPreset}`, drops `flattener`, and so does `ui.epsOptionsDialog` with +a `flattenerPreset` and no `flattener`. + Data Recovery: at launch, copies left behind by a crash open the `recovery` dialog (never copies another running instance keeps, so instances started side by side for screenshots don't get it). Fields: `copies` (`[{file, title, saved}]`, from `file.recovery.list`) and `discard`. `ui.dialog.confirm` restores them all (`file.recovery.restore` @@ -953,7 +977,11 @@ Halftone… (`engine.execute {command: "ui.menuDialog", params: {command: "objec Tool options last: `tool.setOption {key, value}` or `{values: {…}}` (and `tool` to set another tool's) sets them, and the options a tool keeps (Liquify brush and tool options, Mirror & Cut, Puppet Warp, Symbolism, drawing tools) stay when you switch tools or documents and are saved with the preferences. The Liquify tools share their Global Brush -Dimensions (`width`, `height`, `angle`, `intensity`). +Dimensions (`width`, `height`, `angle`, `intensity`). `{}` reads the options and sets nothing; parameters that are +not an object are an error. Every option given is checked before any is set: an option the tool doesn't have, a value +of the wrong type, a number outside the tool's range or an unknown choice is an error that names the tool and the option +(``tool `smooth`: `fidelity` must be a number from 0.05 to 100``), and no option, preference or undo step changes. +The Live Paint tools' `width` and the Shape Builder's `gapLength` are set to the nearest end of their range instead. Perspective grid: View → Perspective Grid → Define Grid… (`ui.perspectiveGridDialog`) opens the `perspectiveGrid` dialog prefilled from the grid. Its fields are those of `perspective.grid.define` (`kind`, `units`, `scale`, diff --git a/docs/development.md b/docs/development.md index 508c0aea06..50e5cbb972 100644 --- a/docs/development.md +++ b/docs/development.md @@ -84,6 +84,7 @@ The canvas is rasterized on the CPU (`vectorcraft-render`, vello_cpu); the GPU ( - On Linux with Mesa, `MESA_VK_DEVICE_SELECT=10de:2f04!` (vendor:device as `vulkaninfo --summary` or `lspci -nn` show it) leaves only that GPU to Vulkan, and `DRI_PRIME=1` picks the other GPU. - Help › About and the control channel's `ui.inspect` (`graphicsAdapter`) show the adapter in use, and the app logs it at startup. - **How frames reach the display.** By default the window presents with `autovsync` and lets the display queue one frame. With `autovsync`, wgpu uses relaxed vsync (FifoRelaxed, which tears a frame that arrives late) where the driver offers it, else vsync (Fifo). For a launch, `--present-mode` (or `VECTORCRAFT_PRESENT_MODE`) sets the present mode to `fifo` (vsync), `autovsync` or `novsync` (wgpu uses Immediate, else Mailbox, else Fifo, whichever the driver offers), and `--frame-latency` (or `VECTORCRAFT_FRAME_LATENCY`) sets the frames the display may queue, `1` to `3`. A flag overrides its variable, and a value that is not one of these stops the app with a message. On Windows and Linux, a launch with either one set opens its files in a new window, as with `--new-instance`, instead of handing them to a running VectorCraft. At startup the log records what the app asks the window surface for, for example `requested window surface: autovsync, frame latency 2 (override)`. The driver chooses the mode that `autovsync` and `novsync` resolve to and may clamp the latency, and on macOS egui uses at least 2 frames while the window is being resized. The code is `apps/vectorcraft/src/presentation.rs`. +- **Preferences › Performance › Low-Latency Drawing** (`lowLatencyDrawing`, off by default) presents with `novsync` and is read when the app starts, so a change applies after a restart. The present mode comes from `--present-mode` first, then `VECTORCRAFT_PRESENT_MODE`, then this preference, then the default (`autovsync`); `--frame-latency` and `VECTORCRAFT_FRAME_LATENCY` still set the latency with it on. The log names where the mode came from: `requested window surface: novsync (preference), frame latency 1`. Whenever the window presents without vsync (`novsync`, from the preference or an override), frames start at most 240 times a second (about 4.17 ms apart); with vsync the display paces them and no cap applies. ## Logs diff --git a/docs/effects-parity.md b/docs/effects-parity.md index b797dcfd45..d92dc159f7 100644 --- a/docs/effects-parity.md +++ b/docs/effects-parity.md @@ -180,7 +180,7 @@ VectorCraft choices; an original approximation, never compared with another appl |---|---| | Revolve | initial: live, editable profile, rotation and light gizmos, default-on Cap with continuous curved rims that also closes a partial sweep's cut sides, smooth vector shading and round seam joins, overlapping faces drawn in the order of their depths where they overlap, SVG/PDF output, Expand Appearance ([revolve.md](revolve.md), #846) | | Extrude & Bevel, Inflate, Rotate | initial: live, round seam joins, depth, twist, taper, solid or hollow caps, five original bevel shapes, Inflate volume, both sides, twist, taper and cap, Rotate of every fill and stroke, groups and layers turned about one shared axis (#4506), contours that cross, touch or overlap merged first ([three-d.md](three-d.md)), Position presets, rotation and light gizmos, SVG/PDF output, Expand Appearance ([three-d.md](three-d.md)) | -| Materials panel, lighting, ray-traced render | Window › 3D and Materials panel with the object types (Plane, Extrude, Revolve, Inflate) and the Object, Rotation and Lighting settings of the applied effect, Render Settings › Wireframe, which draws the live effect as the edges of its faces, and Quick Actions › Expand as Wireframes ([three-d.md](three-d.md#3d-and-materials-panel)); one to ten directional lights with per-light Color (opaque RGB, white by default), Intensity, Rotation, Height, Softness and neutral Ambient Light, Revolve and colored Inflate use smooth vector shading; Extrude & Bevel and Rotate retain planar shading; original Standard, Diffuse, Top Left and Right lighting rigs; shadows behind or below the object from the first light, blurred by its Softness ([three-d.md](three-d.md#shadows)); the Materials tab's Graphics, document symbols mapped onto Extrude & Bevel's caps and onto a plane, moved with an artboard handle, and wrapped around Revolve's side ([three-d.md](three-d.md#graphics)); no base materials, graphics on Inflate or on Extrude & Bevel's walls and bevels, or ray tracing | +| Materials panel, lighting, ray-traced render | Window › 3D and Materials panel with the object types (Plane, Extrude, Revolve, Inflate) and the Object, Rotation and Lighting settings of the applied effect, Render Settings › Wireframe, which draws the live effect as the edges of its faces, and Quick Actions › Expand as Wireframes ([three-d.md](three-d.md#3d-and-materials-panel)); one to ten directional lights with per-light Color (opaque RGB, white by default), Intensity, Rotation, Height, Softness and neutral Ambient Light, Revolve and colored Inflate use smooth vector shading; Extrude & Bevel and Rotate retain planar shading; original Standard, Diffuse, Top Left and Right lighting rigs; shadows behind or below the object from the first light, blurred by its Softness ([three-d.md](three-d.md#shadows)); the Materials tab's Graphics, document symbols mapped onto Extrude & Bevel's caps and onto a plane, moved with an artboard handle, and wrapped around Extrude & Bevel's walls and bevels and around Revolve's side ([three-d.md](three-d.md#graphics)); no base materials, graphics on Inflate, or ray tracing | | 3D (Classic): Extrude & Bevel, Revolve, Rotate | Extrude & Bevel (Classic) initial: live, round seam joins, Extrude Depth, Cap, five original bevel shapes with Height and Bevel Extent In or Out, Position presets and rotation gizmo, Perspective, Wireframe, No Shading, Diffuse and Plastic surfaces with one to ten lights, Light Intensity, Ambient Light, Highlight Intensity and Size, Blend Steps, Black, Custom, Black Overprint or no Shading Color ([Black Overprint](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=188)), Draw Hidden Faces ([create 3D objects](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/create-3d-objects.html)); Revolve (Classic) initial: live, round seam joins, Angle, Cap, Offset from the left or right edge, Position presets and rotation gizmo, Perspective, the same four surfaces, lights, highlight, Blend Steps and Shading Color, groups and layers revolved about one shared axis (same page); Rotate (Classic) initial: live, round seam joins, every fill and stroke turned as one plane, Position presets and rotation gizmo, Perspective, No Shading and Diffuse surfaces with lights, Ambient Light, Blend Steps and Shading Color ([rotate objects in 3D](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/rotate-objects-in-3d.html)); Preserve Spot Colors in all three, unavailable with a Custom Shading Color ([Preserve Spot Color](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=260)); all three: a lighting sphere on the Lighting tab whose lights drag, move to the back or front, and are added at the front center or deleted down to one ([lighting options](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=272)); all three: the track cube (face, edge, Shift and ring drags, keyboard steps; [three-d.md](three-d.md#track-cube)); Map Art: none | | Turntable (30.0 beta) | none | | Export 3D objects (OBJ, USDA, glTF) | initial: Asset Export's Export 3D Object, and the 3D and Materials panel's Export 3D Object button (which then shows Asset Export with the new assets selected, [three-d.md](three-d.md#3d-and-materials-panel)), collect an object with Extrude & Bevel, Revolve, Inflate or Rotate as a 3D asset, and Export writes its solids as a USDA (the default), USDZ, glTF or OBJ mesh with a material in each solid's paint color (`assets.add3D`, `assets.set3DFormat`, `assets.export3D`); graphics mapped onto a plane or Extrude & Bevel's caps are exported as PNG textures of those faces, flat and unlit; no graphics on Revolve's side, no materials and no shading ([3D export help](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/export-3d-vector-artwork.html)) | diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 48250c14e6..36e73837d8 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-17 · **Change:** minor (PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; scores and estimates unchanged; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, not butt caps and miter joins, #7741; `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; `.ai` and EPS import: a top-object envelope whose mesh saves its sides' curves in pieces draws its contents along each whole curve, as its drawn art does, #7097; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: `.ai` and EPS import: type from the text document, type a PostScript program sets and legacy `.ai` type are set in an installed face of their font's PostScript name, exact name first, in the version a text document's record keeps; the `.ai` save writes a static font's version when its name alone gives another copy, #6983; `.ai` and EPS import: type keeps the manual kerning of its text document, #6899; `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, its strokes' miter tips and strokes a Transform effect moves included, after its glyphs grown by half its strokes' weight, #6824; `.ai` and EPS import: type filled or stroked with a pattern swatch keeps its pattern, from the art style its text document paint names, #6856; #6865: explicitly requested oversized editing artboard; PDF import: Indic type keeps its marks on their line, and a line whose type would not draw as the file does keeps the file's glyphs as outlines, #5235; previously: newly imported SVG/SVGZ titles are filtered and bounded without changing restored titles, #3626; `.ai` and EPS import, and what every export and `.ai` save draw: type's strokes in an envelope paint at their own weight along its bent outlines, Distort Appearance on or off, #6644; `.ai` and EPS import: centred and right-aligned lines of tracked type are aligned without the tracking after their last character, as the file's page aligns them, #6610; `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art, #6570; `.ai` save and open: layer colour presets Yellow, Magenta and Cyan keep their colour, as the `Lb` colour index now follows the file's numbering, #6502; `.ai` save: stroked type keeps its stroke's cap, join and miter limit in the text document, #6472; `.ai` and EPS import, PDF import: tracking and manual kerning in horizontally scaled type take the Horizontal Scale, as the file's page spaces such type; `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke, #3179; `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid, #3179; `.ai` and EPS import: stroked type keeps its stroke's cap, join and miter limit from the text document, #6472; `.ai` save: type in a variable font's named instance names its design-space setting, #6388; `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page, #3179; `.ai` and EPS import: a note for type in an envelope, #3179; `.ai` and EPS import: the live envelope and warped type check sees white art; PDF import: DeviceN images of one ink or of process plates keep their inks, #6348; `.ai` import: images in a spot ink's Separation space keep their ink, #6350; PDF import: Separation images keep their ink, #6314; PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; PDF import: image masks open colorized by the color they are painted in, #6313; EPS and `.ai` editing data: a ligature the page names by a private-use glyph matches its text object; EPS import: CIDFonts only named, over a Unicode CMap, set as live type; EPS import: CMap mappings to base-font codes and glyph names; EPS import: CID-keyed fonts in FontSets (CFF) draw their glyphs; EPS import: `kshow` procedures kern live type; EPS import: embedded Type 1 fonts' glyphs and widths; EPS import: CID-keyed fonts draw their glyphs; EPS import: Type 42 fonts' characters and widths from the font they carry, show operators' spacing kept as tracking; EPS import: an image decoder's own buffers stop counting against the memory budget once it is decoded; EPS import: sampled functions interpolate between their samples; `.ai` and EPS type from the text document keeps its tab stops; it keeps auto leading and hyphenation options, and may show more of the file's last lines in an area frame; `.ai` and EPS import: Art brushes in the older form of their objects come into the Brushes panel; EPS import: gradients drawn as abutting strips come in as one gradient, without seams; EPS import: composite fonts draw their Type 42 glyphs; SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (PDF export writes the document language as the catalog's `/Lang`, #3644; PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; scores and estimates unchanged; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, not butt caps and miter joins, #7741; `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; `.ai` and EPS import: a top-object envelope whose mesh saves its sides' curves in pieces draws its contents along each whole curve, as its drawn art does, #7097; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: `.ai` and EPS import: type from the text document, type a PostScript program sets and legacy `.ai` type are set in an installed face of their font's PostScript name, exact name first, in the version a text document's record keeps; the `.ai` save writes a static font's version when its name alone gives another copy, #6983; `.ai` and EPS import: type keeps the manual kerning of its text document, #6899; `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, its strokes' miter tips and strokes a Transform effect moves included, after its glyphs grown by half its strokes' weight, #6824; `.ai` and EPS import: type filled or stroked with a pattern swatch keeps its pattern, from the art style its text document paint names, #6856; #6865: explicitly requested oversized editing artboard; PDF import: Indic type keeps its marks on their line, and a line whose type would not draw as the file does keeps the file's glyphs as outlines, #5235; previously: newly imported SVG/SVGZ titles are filtered and bounded without changing restored titles, #3626; `.ai` and EPS import, and what every export and `.ai` save draw: type's strokes in an envelope paint at their own weight along its bent outlines, Distort Appearance on or off, #6644; `.ai` and EPS import: centred and right-aligned lines of tracked type are aligned without the tracking after their last character, as the file's page aligns them, #6610; `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art, #6570; `.ai` save and open: layer colour presets Yellow, Magenta and Cyan keep their colour, as the `Lb` colour index now follows the file's numbering, #6502; `.ai` save: stroked type keeps its stroke's cap, join and miter limit in the text document, #6472; `.ai` and EPS import, PDF import: tracking and manual kerning in horizontally scaled type take the Horizontal Scale, as the file's page spaces such type; `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke, #3179; `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid, #3179; `.ai` and EPS import: stroked type keeps its stroke's cap, join and miter limit from the text document, #6472; `.ai` save: type in a variable font's named instance names its design-space setting, #6388; `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page, #3179; `.ai` and EPS import: a note for type in an envelope, #3179; `.ai` and EPS import: the live envelope and warped type check sees white art; PDF import: DeviceN images of one ink or of process plates keep their inks, #6348; `.ai` import: images in a spot ink's Separation space keep their ink, #6350; PDF import: Separation images keep their ink, #6314; PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; PDF import: image masks open colorized by the color they are painted in, #6313; EPS and `.ai` editing data: a ligature the page names by a private-use glyph matches its text object; EPS import: CIDFonts only named, over a Unicode CMap, set as live type; EPS import: CMap mappings to base-font codes and glyph names; EPS import: CID-keyed fonts in FontSets (CFF) draw their glyphs; EPS import: `kshow` procedures kern live type; EPS import: embedded Type 1 fonts' glyphs and widths; EPS import: CID-keyed fonts draw their glyphs; EPS import: Type 42 fonts' characters and widths from the font they carry, show operators' spacing kept as tracking; EPS import: an image decoder's own buffers stop counting against the memory budget once it is decoded; EPS import: sampled functions interpolate between their samples; `.ai` and EPS type from the text document keeps its tab stops; it keeps auto leading and hyphenation options, and may show more of the file's last lines in an area frame; `.ai` and EPS import: Art brushes in the older form of their objects come into the Brushes panel; EPS import: gradients drawn as abutting strips come in as one gradient, without seams; EPS import: composite fonts draw their Type 42 glyphs; SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) > > Oversized artboard import update (2026-11-12): Explicit editing-data import retains a single artboard beyond a capped 14,400 pt PDF page (#6865). @@ -300,7 +300,7 @@ private editing data. VectorCraft: The app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping (several clipping paths in a clipping group, a layer or an opacity mask's art clip to their intersection, and a compound path of clipping paths stays one clip; a filled clipping path keeps its fill, which paints under the art it clips, except the path of a mask that covers several layers, whose fill is read as a path of its own in the layer that holds the mask's path, and a compound clipping path whose subpaths paint differently, whose filled subpaths are read as a compound path of their own under the art it clips; clipping paths that would nest the art past the document's 32 levels stop the editing data from being read: #5789), object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint; a stroke of width 0, `0 w`, on a path, a gradient-filled path, legacy type or in an art style comes in as a 0.25 pt hairline, as from PDF: #1671), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), gradient and pattern names in the file up to their first newline (a name that another swatch, or a gradient or pattern defined earlier, already has is numbered "Sky 2"; a name without a newline is kept, and when another swatch has it, the pattern's swatch, or a named color sharing a gradient or pattern swatch's name, is numbered the same way), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), with the folder the file keeps relative to the document's, where the link is looked for when its path is gone, placed PDF and `.ai` pages as placed documents of the [page and Crop to box](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/adobe-pdf-placement-options.html) their dictionary names (`AI11 PlacedPDFPageIndex`, `AI11 PlacedPDFCropTo`; a value VectorCraft doesn't read, or a binding to an image variable, leaves a linked image), guides, and every artboard where it is, with its center mark, cross hairs, video safe areas and video ruler pixel aspect ratio. VectorCraft reads `CropAreaActive`, an `/Int` in the dictionary that holds the artboard array, as the index of the active artboard in that array, and the file opens with that artboard active; without it, or when it names no artboard that opens, the first artboard is active. It also reads the Document Raster Effects Settings (resolution, color model, background, anti-alias, clipping mask, Add Around Object and Preserve Spot Colors), the author from the header's `%%For` (an EPS's own header when the editing data's has none), swatches for the header's `%%CMYKCustomColor` and `%%RGBCustomColor` colors that the document has none of, and `%%TemplateBox` in older files; a setting with a value of another type or out of range keeps its default. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile on a Stroke Offset stroke or written as each side's widths) with Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners, Scribble, Offset Path, Outline Object, Outline Stroke, Convert to Shape, Tweak (only when it moves nothing), Pucker & Bloat at 0 or Bas Relief (read from its settings block: [raster effects reference](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/raster-effects-reference.html), [layered image file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), [scripting the filter gallery](https://community.adobe.com/questions-712/scripting-support-for-the-filter-gallery-1064646)) comes in as itself with them and their saved settings. A path, compound path or group (not a clipping group) whose only effect is Transform (not with copies or Random) or a Free Distort whose corners make a parallelogram comes in as itself with it too, when neither it nor anything in it paints with a gradient or pattern and everything in it is a path, compound path or group with no opacity mask and no effects of its own; Transform that scales, rotates or reflects needs nothing in it to be stroked and, with Transform Objects on, no guide in it that reaches past the rest of its art (hidden members count as art), and a Free Distort that moves a corner of a group needs no guide in the group that reaches past the rest of its art. Twist as the only effect is read the same way when nothing in the object is stroked: up to 180° either way (a limit VectorCraft sets) on a path or compound path whose segments are all straight, except a compound path with a guide member that reaches past its other members at an angle other than 0°, and up to 90° either way (a limit VectorCraft sets) on another path, compound path or group with no guide in it. One with more, other effects (Zig Zag, a Pucker & Bloat of another amount, a Free Distort with other corners), an effect setting that is not read (an unknown key, a missing or out-of-range value, a Scribble with a color of its own), a variable-width stroke with one centered width array, dashes aligned to corners, a brush other than a Calligraphic or Art one, a Calligraphic brush with settings of its own, an entry that isn't read, a variable width or an angle that follows the path, a path followed by samples of the pen (`(…) Xt n XD`) whose Calligraphic brush varies with the pen, or an Art brush other than the ones described next comes in as its drawn look (a group named after it). Objects in a symbol defined before the file's art styles section, as newer files write it, take the same styles as the layers' objects. A path with a Calligraphic brush otherwise comes in as the path, the brush on its stroke at the stroke's weight, which scales the brush (#372), and so does a path with an Art brush, whose weight scales the art across the path, when all of these hold: the brush is in Tints or None, at a fixed width from 1% to 1,000%, stretched to the path or stretched between guides that leave art between them, flipped along or across or not ([Art brush options](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf), printed page 193), with `Spacing` 0, `Adjustment` 1 and `FoldAdjustment` 1 (VectorCraft's own reading of these numbers; a brush that scales its art proportionately comes into the Brushes panel with that option, and its paths keep their drawn look); the path's settings are the brush's own (apart from the lowest and highest width of a fixed width and the guides' lengths without Stretch Between Guides, which don't draw), with no entry that isn't read, no variable width and no effects; a stroke in Tints isn't a swatch; and the art is paths, compound paths and groups in solid fills, with no strokes, masks or effects, and has some length along the path. A stroke takes the brush the Brushes panel keeps under its name, and one whose name the panel doesn't keep comes in as its drawn look. Type with an Art brush keeps its drawn look under the type. A Calligraphic brush's Pressure, Tilt, Bearing and Rotation come in as those channels (a 6D Art Pen's brushes vary with the pressure, the bearing and the barrel's rotation); its Stylus Wheel varies at random. The file's Calligraphic, Scatter, Art and Bristle brushes replace the default ones in the Brushes panel, in the file's order, also when the file comes in as its PDF part (a brush library has no layers); pattern brushes and brushes it can't read are left out with a note. When the file opens from its layers, the spot colors in the art of each brush that comes in become swatches, and that art's colors count toward the document's color mode, as a pattern's do. The swatches take at most 20,000 color names in all across the brush art, and each brush-art section keeps at most 20,000 names. Each name keeps its first definition, with the color operators' names before the gradient stops' names. A spot color past those limits makes no swatch, and its color still counts toward the color mode. A spot color that the page's art, a pattern or a symbol also defines keeps the value defined there. Type keeps its art style as a live appearance whatever its stack (an Art brush aside), so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Outline Object, Outline Stroke, Transform (with copies, Transform Objects, Transform Patterns and Scale Strokes & Effects; not with Random), Free Distort, Pucker & Bloat, Twist, Zig Zag, Tweak (only when it moves nothing, the file holding none of its random outline), Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners, Scribble, Gaussian Blur, Bas Relief (its detail, smoothness and light direction from its settings block, or the effect's defaults when the style holds no settings block; a settings block that isn't read keeps the drawn look) and Convert to Shape, and a style with others, or with an effect setting that isn't read, keeps the type's drawn look. Convert to Shape keeps its Rectangle, Rounded Rectangle or Ellipse, its Absolute or Relative size (a relative size in the file is added to each side) and its corner radius; a relative Ellipse, or a setting that isn't read, keeps the drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and its stroke, and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an EPS with editing data from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); area type keeps its frame's Area Type Options rows and columns, the gutter between rows and the gutter between columns, and its first baseline (Fixed, Cap Height, Leading or x Height) with its minimum; type on a path keeps its frame's Type on a Path effect, Align to Path and Flip (a frame whose options set key 6 to true keeps their defaults), and the first frame's Spacing is fitted from the file's layout, not read from the dialog's value; the distance from the path under Align to Path is measured for each character at its size and vertical scale (in vertical type, its horizontal scale), from the top of its font's em box (Ascender), half the height of the top of its font's H (Center) or the bottom of its font's bounding box (Descender); the fit under Gravity does not reproduce the file's layout, and its glyphs can lie up to 7.4 pt from the positions the file keeps; the page's drawing of it (often in pieces) is left out. Vertical type keeps its orientation, its columns from right to left, and a run set to Tate-chu-yoko keeps that setting. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Text wrap is read too: an object whose dictionary has the wrap options (offset and Invert Wrap), or any graphic of a legacy wraparound group (`*w` … `*W`, before or after its type, with no offset), is a wrap object, and area type below it in its layer flows around it when the file opens, threaded type included (#2763). Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). In a PDF saved with some of its artboards, the type on each page after the first goes to an artboard of that page's size after the previous page's artboard, and only to one that leaves an artboard for each later page; the first page's artboard also leaves one for each later page. When several artboards fit a later page, VectorCraft takes the one whose art draws most like the page, and compares at most 16 artboards for all the later pages together. Symbols are read into the Symbols panel, in the file's symbol list order, with their art, their registration point and the instances in their art, and their instances come in live with their matrix, name, hide, lock, opacity, blending mode, isolation, knockout and opacity mask; a symbol whose art isn't read whole (type, placed files, an image it leaves out or anything else it doesn't read) isn't kept. A file that comes in as its page or PDF part because its editing data has no layers (a symbol library), or because its layers can't be read or used (any of the cases below), gets the symbols its editing data defines before its first layer, in the symbol list's order, while its page art stays as the page draws it. Instances of symbols it can't read, instances with appearance changes of their own (a dynamic symbol's), pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards or lies on an artboard that has no page, when no page art lies inside its box, when that page art is inside a page group with a clip, mask, transparency or appearance, when the object holds a frame of threaded type, when the page art uses a pattern, image or swatch that the page lacks or that differs from the editing data's, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). A `.ai` is not compared with its page, and its PDF part is not imported, when its text document makes the type of every text object (at least one shows, and none is drawn by the appearance of the layer or group it is in), no object is unread, no placed file has a second placement, no live envelope keeps its drawn art, it declares no large canvas, and its artboards are its pages' trim boxes one for one, in points or in the first page's `UserUnit`: it opens from its layers, with the bleed of its pages' bleed boxes. When they differ because some objects draw differently (an object in another color, or one that only one of them draws), each top-level object of the layers that holds such a difference comes in as a group of the page's objects inside its box and the layers stay, with a warning that names the layer or sublayer of each such object as the Layers panel shows it (`` for one without a name) and how many came in from it; an export or Save As to the file's own path then needs `acknowledgeLoss: true`, and a wrap object replaced this way keeps its wrap options. The file still comes in as its page when only edges or type differ, when a difference lies outside every top-level object, when more than half of the top-level objects or more than 64 hold one, when such an object is or holds type or holds a wrap object inside a group, when the page's type of a text object that stays lies inside such an object's box, when the page's art can't replace such an object for one of the reasons above for an unread object, when matching the differences to the objects would take too much work, or when the result still differs from the page. `editingData: "always"` keeps the objects as read, and placed files at the other point their data gives are tried as well. An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so live objects that only the editing data holds arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (the PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068); the page of the artboard `CropAreaActive` names is then the active artboard. A `.ai` whose editing data has artboards but no layers also opens on that page under the same check, and its pages stay where they are. A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. A run of type in the editing data whose baseline direction is 1 opens with Standard Vertical Roman Alignment (https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html) on, which is VectorCraft's own mapping: its half-width characters stand upright in vertical type, and horizontal type keeps the mark with no change to its layout. A run whose baseline direction is 2 or 3 (Tate-chu-yoko), or that names none in the run, its character style or the document's defaults, opens with it off. The scripting reference lists 1, 2 and 3 as the Standard, vertical rotated and Tate-chu-yoko baseline directions (https://web.archive.org/web/20170621180804/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20VBScript%20Reference.pdf, page 256). -A Scatter brush in the editing data whose last 15 numbers start with 1 comes into the Brushes panel in Tints. Each brush art section is read without its frame: an unnamed, unpainted rectangle with no settings of its own at the art's bounds (within 1/1000 pt), closed, or open with its first corner again at the end. A wider frame stays in the art, and an art group with a state or look of its own (hidden, locked, isolated, knockout, an opacity, a blend mode, a name, a mask, a note or an appearance) stays a group. +A Scatter brush in the editing data whose last 15 numbers start with 1 comes into the Brushes panel in Tints. A Scatter brush's art comes in turned over from its section, as an Art brush's does: in each copy the side of the section with y up goes down the page before the copy's rotation, and the writer writes the art back the same way. Each brush art section is read without its frame: an unnamed, unpainted rectangle with no settings of its own at the art's bounds (within 1/1000 pt), closed, or open with its first corner again at the end. A wider frame stays in the art, and an art group with a state or look of its own (hidden, locked, isolated, knockout, an opacity, a blend mode, a name, a mask, a note or an appearance) stays a group. An object in a pattern's art or in a brush's art takes the file's art styles in the same way as an object on a layer: with a style VectorCraft reads, it comes in as itself with its effects live, not as the look it draws. An object in a pattern's art with a style in the file's style list keeps that graphic style's id, as does an object in an opacity mask's art. An art styles section inside a symbol's, a pattern's or a brush's art is skipped. @@ -315,7 +315,7 @@ Gradient meshes in the editing data keep each point's own color where a patch's | VectorCraft `.vectorcraft` / `.vctemplate` | — | yes | yes | lossless JSON, versioned, save down to v1; property-tested round trips (`format/tests/prop_format.rs`); documents with a lot of path data are written as compact JSON, about a fifth of the size (#1492); a save falls back to a plain fsync and to writing elsewhere and copying in when the folder refuses the usual steps (#1625, #1649, part of #1620; not confirmed on a real network share); the size limits on embedded data also apply to files read from memory (#1783), and saving over a private file on Unix leaves no readable temporary copy beside it (#1778); a dynamic symbol's type (`dynamic` on the symbol) and an instance's appearance changes to its art (`symbol_overrides`, each path at most 64 deep, counted against the object budget) are written only when set, so documents without them save as before (#4938) | | Illustrator template `.ait` | open, save | yes | PDF-compatible only, from Save as Template (`.vctemplate` stays its default) | New from Template opens a saved `.ait` untitled with its layers and art (`tests_pdfedit.rs`) | | Illustrator `.ai` | open, save | yes (PDF-compatible + editing-data structure with template layers and ruler guides, File Info) | PDF-compatible, or legacy version 7 (layers and groups) | see above; no real-file corpus | -| PDF | open, place, save | yes (authored ActualText in editable import, #6165; layers, masks, editable text, security, overprint, File Info from the XMP packet and the document information dictionary; Crop To › Trim takes the bleed box as the document's bleed; Import PDF pages as links opens each page as a placed document linked to it, on its own artboard, `tests/placed_document.rs`) | yes (presets, PDF/X-1a/3/4, layers, marks and bleed, ICC, fast web view, 1.3+; objects' URLs as link annotations, not in PDF/X) | fuzzed import; shared guarded writer and windowed reader ([pdf-backend.md](pdf-backend.md)), metadata, incomplete-content and dependency-source regressions; PDF text opens where the file draws it, glyph by glyph (#722: kerning or none, spacing per character, text rise as baseline shift, vertical writing, justified text boxes); alpha soft masks drawn as images import with the mask (#1551); a clip only counts as covering the page when its shape does (#1542); a PDF another app copied pastes as editable vector art (#1499); letter-spaced type on a path keeps its length and its glyph-by-glyph stroke comes in as one text object (#1586, #1585); a crafted name tree with shared nodes no longer takes exponential time on open (#1781); fonts named with hyphens (`Noto-Sans-Bold`) or with a composite font's CMap (`Name-Identity-H`) find the installed family; invisible text (rendering mode 3: a scanned page's recognized text) opens as type with no fill or stroke and saves back as invisible, searchable text (#2675); PDF/X-1a and X-3 flattening in a CMYK document keeps CMYK inks where it rasterizes (#2160); an image mask (`/ImageMask true`) painted in a solid color opens as a grayscale image colorized by that color, a spot color keeping its swatch and tint, so Fill and Recolor Artwork reach it, and the same mask painted again in another color keeps that color (#6313); an image in a Separation space opens as a grayscale image of its tints colorized by its ink at 100 % (a spot swatch, a process plate or Registration), its soft mask as its opacity mask (#6314); a DeviceN image of one colorant opens the same way, and one of process plates only (the ink `None` may be among them) opens in CMYK with each colorant's tint in its plate (#6348) PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. | +| PDF | open, place, save | yes (authored ActualText in editable import, #6165; layers, masks, editable text, security, overprint, File Info from the XMP packet and the document information dictionary; Crop To › Trim takes the bleed box as the document's bleed; Import PDF pages as links opens each page as a placed document linked to it, on its own artboard, `tests/placed_document.rs`, and is checked when All is picked and cleared when Range is picked) | yes (presets, PDF/X-1a/3/4, layers, marks and bleed, ICC, fast web view, 1.3+; objects' URLs as link annotations, not in PDF/X; the document language as the catalog's `/Lang` and XMP `dc:language`, #3644) | fuzzed import; shared guarded writer and windowed reader ([pdf-backend.md](pdf-backend.md)), metadata, incomplete-content and dependency-source regressions; PDF text opens where the file draws it, glyph by glyph (#722: kerning or none, spacing per character, text rise as baseline shift, vertical writing, justified text boxes); alpha soft masks drawn as images import with the mask (#1551); a clip only counts as covering the page when its shape does (#1542); a PDF another app copied pastes as editable vector art (#1499); letter-spaced type on a path keeps its length and its glyph-by-glyph stroke comes in as one text object (#1586, #1585); a crafted name tree with shared nodes no longer takes exponential time on open (#1781); fonts named with hyphens (`Noto-Sans-Bold`) or with a composite font's CMap (`Name-Identity-H`) find the installed family; invisible text (rendering mode 3: a scanned page's recognized text) opens as type with no fill or stroke and saves back as invisible, searchable text (#2675); PDF/X-1a and X-3 flattening in a CMYK document keeps CMYK inks where it rasterizes (#2160); an image mask (`/ImageMask true`) painted in a solid color opens as a grayscale image colorized by that color, a spot color keeping its swatch and tint, so Fill and Recolor Artwork reach it, and the same mask painted again in another color keeps that color (#6313); an image in a Separation space opens as a grayscale image of its tints colorized by its ink at 100 % (a spot swatch, a process plate or Registration), its soft mask as its opacity mask (#6314); a DeviceN image of one colorant opens the same way, and one of process plates only (the ink `None` may be among them) opens in CMYK with each colorant's tint in its plate (#6348) PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. | | EPS | open, place, save | yes (own PostScript L3 interpreter, Illustrator EPS editing data structure) | yes (L2/L3, TIFF previews) | CIDFonts the file doesn't carry not drawn, but for those over a predefined CMap (`UniJIS-UCS2-H`, `90ms-RKSJ-H`, `GBK-EUC-H`, `KSCms-UHC-H`, `ETen-B5-H`), set as type in the font of the CIDFont's name, vertical over a `-V` CMap; a name that ends in the row-and-cell CMap `H` or `V` splits off the CMap only when the file defines the CIDFont of that name, the CIDFont is `Ryumin-Light` or `GothicBBB-Medium` (the Japanese CIDFonts a printer carries), or the name has a hyphen and an installed face that covers Japanese has it; name-keyed fonts in a FontSet set as type by name; #505; images encoded with `CCITTFaxDecode` (ITU-T T.4 Group 3 and T.6 Group 4, with `K`, `Columns`, `Rows`, `EndOfBlock`, `EndOfLine`, `EncodedByteAlign` and `BlackIs1`) draw, and damaged data keeps the rows decoded before its first damaged row; Type 42 (TrueType) fonts set type at its size (#1553); an embedded Type 1 font's encrypted part is read for its glyphs, which space its type, outline it and draw glyphs without a character, in plain and composite fonts; a Type 42 font that carries its TrueType font gives each code its character by its glyph name or, for names that say nothing (`/g12`), by the glyph's entry in the font's own character map, spaces its type by its own widths and draws glyphs that stand for no character from its outlines; the show operators' spacing along the baseline (`ashow`, `widthshow`, `xshow`, `yshow`, `xyshow`, and the moves of `kshow`'s procedure, run between each two characters) is kept on live type as tracking, so type in a font that isn't installed keeps the file's line lengths (spacing that moves characters off the baseline, as `yshow`, `xyshow` or a `kshow` procedure can, places each character as its own text object); composite (Type 0) fonts with the 8/8 mapping, as PDF-to-PostScript converters write two-byte fonts, draw a Type 42 descendant's glyphs from the TrueType outlines it carries and an embedded Type 1 descendant's from its charstrings, and set other descendants' characters as type at the composite font's size (other mappings are still set as type in the font of their name); CID-keyed fonts (`composefont`, `FMapType` 9 over a CMap built with the CIDInit operators or `Identity-H`/`Identity-V`; `bfchar` and `bfrange` mappings give a base-font descendant its codes or glyph names) draw the glyphs of the Type 0 CIDFonts (Type 1 charstrings in their `StartData` binary data or `GlyphDirectory`) and Type 2 CIDFonts (TrueType glyphs through `CIDMap`) they carry, and the CID-keyed fonts of a FontSet's Compact Font Format data (Type 2 charstrings); a clip only counts as covering the page when its shape does (#1542); an EPS another app copied pastes as editable vector art (`clipboard.importEps`, #1499); a stitched shading keeps its hard colour changes on import (#1654); sampled functions (type 0) interpolate between their samples, multilinearly or by cubics with `Order 3`, and a sampled axial or radial gradient has a stop at each sample; a gradient the page paints as a row of abutting one-colour strips (as Level 2 writers draw smooth shades) imports as one linear gradient, without the seams the strips leave when each is drawn alone; CMYK images, CMYK JPEGs included, keep their ink amounts on import, as from PDF, and the pixels a `MaskColor` or `ImageType 3` mask hides become a grayscale opacity mask; ruzstd 0.9.1 for compressed editing data (#1807, RUSTSEC-2026-0344) | | PostScript `.ps` | open, place | yes (the EPS reader reads its first page; `.epsf` files open and place as EPS) | via Print to PostScript | `tests_epsimport.rs` | | DCS 1.0 / 2.0 | place linked | place linked only (one image of the plates; spot plates as spot swatches; the composite's clipping path; each plate on its own ink in Separations Preview and print separations) | no | `crates/eps/src/dcs/tests.rs`, `crates/engine/src/tests/dcs.rs` | @@ -336,7 +336,7 @@ Gradient meshes in the editing data keep each point's own color where a patch's | Pixar PXR | open, place (legacy) | yes (any set of the R, G, B and A channels in 8 or 12 bits, dumped or run-length encoded, in tiles; R alone is gray; alpha matted to black or unassociated) | no | recognized by its magic number; 12-bit samples are clamped to 0.0 to 1.0; null tiles are transparent with A and black without; the offsets aren't read, and the image takes the default resolution; a file cut short, with header values or packets the format doesn't define, or past the pixel allowance is refused with a message; tested on synthetic files only; tests in `crates/engine/src/cmd/fileio/tests_pxrread.rs` and `crates/engine/tests/import_fuzz.rs` | | FreeHand `.fh*` | open (legacy) | no | no | | | CorelDRAW `.cdr` | open | no | no | | -| Text `.txt` | place, export | place (Text Import Options) | yes | | +| Text `.txt` | place, export | place (Text Import Options) | yes | place reads Unicode and ANSI, and Shift JIS, GB2312, Chinese Big 5, Cyrillic, GB18030, Greek, Turkish, Baltic and Central European through the WHATWG Encoding Standard's decoders (VectorCraft's own mapping); `tests/textimport.rs`, `place/text.rs`; fuzzed (`text_import_fuzz.rs`) | | RTF `.rtf` | place | place (area type with fonts, size, bold, italic, underline, strikethrough, caps, superscript and subscript, color, alignment, indents and paragraph spacing) | no | `tests/textimport.rs`, `place/rtf.rs`; fuzzed (`text_import_fuzz.rs`); `\'hh` bytes read as Windows-1252 or Mac Roman only | | Word `.docx` | place | place (area type with the document's styles and its fonts, size, bold, italic, underline, strikethrough, caps, superscript and subscript, color, alignment, indents and paragraph spacing) | no | `tests/textimport.rs`, `place/docx.rs`; fuzzed (`text_import_fuzz.rs`); list numbers, pictures and text boxes are left out | | Word `.doc` | place | place (area type with the same formatting as `.docx`, from the style sheet's styles and direct formatting; Word 97 and later) | no | `tests/textimport.rs`, `place/doc.rs`; fuzzed (`text_import_fuzz.rs`); pictures, headers, footers, notes, comments and text boxes are left out with a warning; encrypted and fast-saved documents are refused | @@ -383,6 +383,7 @@ Stop opacity on translated artboards remains outside this regression coverage. | Date | Change | Summary | |---|---|---| +| 2026-11-18 | minor | PDF export (#3644): the document language chosen in Document Setup is written as the catalog's `/Lang` (BCP 47, `en-US` by default) and as XMP `dc:language`; a language without a tag writes none. Scores and estimates unchanged. | | 2026-11-17 | minor | PDF import (#8300): a glyph filled only (text rendering mode 0) right after one filled and stroked (mode 2) joined the stroked run and came in stroked too: `2 Tr (B) Tj 0 Tr (C) Tj` came in as `BC` stroked throughout. A glyph filled only now joins only a run drawn alike, so it starts a run of its own, filled only, in the same type object, and takes a stroke only when the file draws one over it (the #8015 matching); a word filled whole then stroked whole, and fill and stroke rendering glyph by glyph, still come in as one run filled and stroked. Tests: `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked`, `glyphs_filled_and_stroked_one_by_one_stay_one_run`; scores and estimates unchanged. | | 2026-11-17 | minor | PDF import (#8015 follow-up): type filled and stroked at less than full opacity is no longer joined into one type object, since the file composites the fill and the stroke apiece, darker where they overlap, while one object's opacity applies to both together; it stays a filled object and a stroked one, as a fill and stroke at different opacities already did. An upright glyph (vertical type) filled and stroked is no longer kept as an outline for a line that comes in as its outlines, as glyphs filled only weren't, so such a line can't lose them. The #8015 entries now say what is left: translucent type filled and stroked, and a `TJ` whose kerning starts a new line part way through, still come in as two objects. Tests: `translucent_fill_and_stroke_text_stays_two_objects`, `a_vertical_line_with_one_glyph_filled_and_stroked_keeps_every_glyph_filled`; scores and estimates unchanged. | | 2026-11-16 | minor | PDF import: fill and stroke rendering (text rendering modes 2 and 6) draws all the glyphs of a text-showing operator (`Tj`, `TJ`, `'`, `"`) filled, then the same glyphs stroked, so a word shown at once came in as two type objects: a stroke-only copy over a fill-only one. Each stroke is now matched, in order, to the glyph filled with the same placement (where, how large, how wide, slanted and turned) in the same font with the same text on the line, and only that glyph takes the stroke, so the word comes in as one type object, filled and stroked; glyphs stroked with another join part way through still split into runs of their own, and stroked type over no filled glyph (modes 1 and 5) stays stroke only (#8015; `a_word_filled_then_stroked_imports_as_one_filled_and_stroked_type` in `crates/pdf/src/tests/textstroke.rs`, `a_vertical_column_filled_then_stroked_is_one_filled_and_stroked_type` in `crates/pdf/src/tests/text_placement.rs`). Scores and estimates unchanged. | diff --git a/docs/gaps.md b/docs/gaps.md index 0c1a018c20..a2fab88f0b 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,8 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: Type: the Middle Eastern & South Asian composers are done as a per-paragraph choice with the Standard composers (#4935); G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: G5: built-in Weather Icons symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow); estimate 5–15 → 4–14 h; previously: 3D: the seams of white-light Extrude & Bevel, Inflate and Rotate, and the face seams of the 3D (Classic) effects, have round joins instead of miters; previously: PDF import: preserve Type 3 font text runs as named groups , or as live text in TextAs::Text mode if ToUnicode exists on non-colour fonts (TextAs::Outlines produces grouped outlines), #6740; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: oversized editing artboard import; Glyphs panel: Alternates for Current Selection applies an OpenType feature value (`salt=2`) to the selected letter alone, so an Arabic word stays joined, and Entire Font lists the unencoded glyphs, #5514; #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: G5: built-in Energy Beams brush library; estimate 5–15 → 4–14 h; previously minor: G5: built-in Skill Icons symbol library; estimate 6–16 → 5–15 h; previously minor: ruler double-click adds a guide at the pointer, #5239; G5: built-in Status Effects graphic style library; estimate 7–17 → 6–16 h; MCP docs catch-up for UI Frames and Map Markers; previously minor: G5: built-in Inventory Icons symbol library; estimate 8–18 → 7–17 h; previously minor: G9: `.ai` save names a variable font instance's design-space setting, #6388; previously minor: G5: built-in Game Trails brush library; estimate 9–19 → 8–18 h; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: G5: built-in Game HUD graphic style library; estimate 10–20 → 9–19 h; previously minor: G5: built-in Map Markers symbol library; estimate 11–21 → 10–20 h; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview; estimate 1–2 h → 0; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: built-in UI Frames symbol library with default 9-slice; estimate 11–21 h; previously minor: G5: dynamic symbol part on-canvas takes opacity, blend, gradient and pattern; docs Overlap/auto-corners sync; estimate 12–22 h; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap, Pattern brush auto corners and Global Edit Shift-click leave-out moved from Missing to Done (code already shipped); previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; G9: EPS gradients drawn as abutting strips import as one gradient, without seams; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (PDF export writes the document language as the catalog's `/Lang`, #3644; Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: Type: the Middle Eastern & South Asian composers are done as a per-paragraph choice with the Standard composers (#4935); G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: G5: built-in Weather Icons symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow); estimate 5–15 → 4–14 h; previously: 3D: the seams of white-light Extrude & Bevel, Inflate and Rotate, and the face seams of the 3D (Classic) effects, have round joins instead of miters; previously: PDF import: preserve Type 3 font text runs as named groups , or as live text in TextAs::Text mode if ToUnicode exists on non-colour fonts (TextAs::Outlines produces grouped outlines), #6740; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: oversized editing artboard import; Glyphs panel: Alternates for Current Selection applies an OpenType feature value (`salt=2`) to the selected letter alone, so an Arabic word stays joined, and Entire Font lists the unencoded glyphs, #5514; #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: G5: built-in Energy Beams brush library; estimate 5–15 → 4–14 h; previously minor: G5: built-in Skill Icons symbol library; estimate 6–16 → 5–15 h; previously minor: ruler double-click adds a guide at the pointer, #5239; G5: built-in Status Effects graphic style library; estimate 7–17 → 6–16 h; MCP docs catch-up for UI Frames and Map Markers; previously minor: G5: built-in Inventory Icons symbol library; estimate 8–18 → 7–17 h; previously minor: G9: `.ai` save names a variable font instance's design-space setting, #6388; previously minor: G5: built-in Game Trails brush library; estimate 9–19 → 8–18 h; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: G5: built-in Game HUD graphic style library; estimate 10–20 → 9–19 h; previously minor: G5: built-in Map Markers symbol library; estimate 11–21 → 10–20 h; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview; estimate 1–2 h → 0; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: built-in UI Frames symbol library with default 9-slice; estimate 11–21 h; previously minor: G5: dynamic symbol part on-canvas takes opacity, blend, gradient and pattern; docs Overlap/auto-corners sync; estimate 12–22 h; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap, Pattern brush auto corners and Global Edit Shift-click leave-out moved from Missing to Done (code already shipped); previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; G9: EPS gradients drawn as abutting strips import as one gradient, without seams; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) + +> Selection update (2026-11-11): path and compound-path interiors follow enabled non-None fill rows, including lower fills beneath a top None row (#6625). Hidden-only interiors miss; zero-opacity fills remain selectable. Cap/join follow-up (2026-11-12): hidden-fill and no-fill stroke hits must respect cap and join geometry; focused cap/join CPU regressions passed. Scores and estimates unchanged. ## Feature submission evidence @@ -36,6 +38,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-18 | minor | G19: PDF export writes the document language chosen in Document Setup as the catalog's `/Lang` (its BCP 47 tag, `en-US` by default) and the XMP packet's `dc:language`, in exported and printed PDFs (#3644); `/MarkInfo` stays with tagged PDF (#3643). Scores and estimates unchanged. | | 2026-11-16 | minor | G1: Recolor Artwork - native Lab entry in Color Picker, swatch libraries access in Color Picker, and row right-click context menu ("Pick from Swatches", "Limit to Library") (#4028); scores and estimates unchanged. | | 2026-11-15 | minor | G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…, `ui.checkSpelling`, #4936) with Not in Dictionary sentence context, suggestions, Ignore, Ignore All, Change, Change All, Add to Dictionary, Done/Cancel, keyboard navigation, and one-step Undo/Redo; spell check complete; scores and estimates unchanged. | | 2026-11-15 | minor | G5: Neon & Glow joins Shadows and Glows, Outlines and Rules, Hand-Drawn, Textures, Painted and Sketched, Gradient Finishes, Shape Effects, Blends and Transparency, Game HUD and Status Effects as an eleventh built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor; original procedural styles generated in code); estimate unchanged (3–13 h). | @@ -122,6 +125,8 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall macOS cursor delivery (#2292) is narrowed to a native host adapter using the existing artwork and aligned 1×/2× representations. Headless tests cover visible fallbacks, preparation and ownership; native focus/menu/handback timing, mixed displays, Spotlight and full-screen Spaces remain open validation work (see [hardware parity](hardware-parity.md)). This does not close the interaction-fidelity gap or change its score/estimate. +- **Selection fill eligibility (#6625):** Path and compound-path interiors use any enabled non-None fill row (#6625). A lower visible fill remains selectable beneath a top None row in the same object; hidden-only and true-None interiors miss. Zero-opacity fills remain selectable. Original CPU-render and document-hit regressions in `crates/engine/tests/path_fill_hits.rs` cover seven Path and five Compound cases, including stroke edges, geometric outlines, Outline/path-only modes and compound holes. Hidden-fill and no-fill stroked paths must respect butt, round and square caps and bevel, round and miter joins. Focused cap/join CPU regressions passed. Scores and estimates unchanged. + - **Panel collapse controls (#5925, in part):** The small » in a floating tab-group header moves that group into the side icon rail, reusing the existing rail or creating one. An opened rail panel has the same control to fold its flyout back into the rail, including after a tab switch. Both controls preserve the tab group and its menu; other floating groups and full-width docked headers stay as they were. Pointer regressions in `crates/ui-egui/src/panel_docking/tests.rs` cover grouped tabs, reopening, separate groups, a missing rail, the menu and flyout closure after switching tabs; `native_tests.rs` covers the native-window click and removal of the empty palette. Scores and estimates unchanged. - **Done:** Distance Guides ([public page](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/use-distance-guides-for-accurate-placement.html)): with Smart Guides on and something selected, the Selection tool with Alt/Option held over another object shows the horizontal and vertical distances between them, and over an empty part of an artboard the selection's distances from its four edges, labelled in the General unit; Preferences › Smart Guides › Invoke Distance Guides turns them off. Hover only, as documented: not while moving or nudging. No entry closed; estimates unchanged. @@ -813,7 +818,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Evidence:** Brazilian Portuguese catalog complete under the tests (menus, literals, messages; one|other plurals; #1914). Vietnamese catalog complete under the tests (menus, literals, messages; one plural form). Czech render-site bypasses reduced in file dialogs, diagnostics, preset names and contributor tooltips; gradient grammar and printer-mark context corrected (see [localization-parity.md](localization-parity.md)). Native review and the remaining missing-language work remain. - **Missing:** Arabic catalog and right-to-left layout; current gaps in other catalogs and native - review; Hindi wording/layout review and a web Devanagari font; a Korean UI font for the web. + review; Hindi wording/layout review. The web build fetches NanumGothic for Korean and Noto Sans + Devanagari for Hindi when the interface needs them (`crates/text/web-fonts.txt`, `demand`). Hindi now has a catalog and the pinned egui fork shapes Devanagari. Indonesian already has a catalog (see [localization-parity.md](localization-parity.md)); it is not an absent language. - **Estimate:** 50–85 h plus human review (Brazilian Portuguese completed 2026-10-14). @@ -868,7 +874,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Missing:** AccessKit is on by default, so egui widgets reach screen readers, but custom panels, the canvas and its objects aren't described and nothing has been tested with VoiceOver, Narrator or Orca; keyboard-only canvas operation; high contrast. Illustrator's own accessibility is limited, so this is mostly beyond parity. -- **Done:** PDF export writes `/ViewerPreferences << /DisplayDocTitle true >>` when File Info has a Document Title (or an explicit export title is supplied), so viewers and accessibility checkers use that title instead of the file name (#3646). +- **Done:** PDF export writes `/ViewerPreferences << /DisplayDocTitle true >>` when File Info has a Document Title (or an explicit export title is supplied), so viewers and accessibility checkers use that title instead of the file name (#3646). It writes the document language chosen in Document Setup as the catalog's `/Lang` (its BCP 47 tag, `en-US` by default) and the XMP packet's `dc:language`, so screen readers and checkers know the language (#3644). Tagged PDF (structure tree, `/MarkInfo`) is still missing (#3643). - **Estimate:** 15–25 h. ## Highlighted-text Eyedropper (2026-10-21) @@ -916,6 +922,7 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | 2026-11-12 | minor | 3D: The seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins (the seams of Revolve and of colored lights, and 3D (Classic) Wireframe edges, were already round): no thorns on edge-on facets, and facets with no neighbour now have rounded convex corners ([three-d.md](three-d.md#seams)). Scores and estimates unchanged. | | 2026-11-15 | minor | G12: Swatches item menus validated in all five views: 39 focused tests passed, regression fails without the menu hooks, rendered list/thumbnail layouts inspected, and fresh local deep CodeRabbit review found zero issues. Full workspace CI passed on Linux/WSL on the merged branch (all 13 gates), including the test-helper correction for the upstream compile error tracked in #7727; native Windows full CI has two unchanged engine-test failures. Scores and estimates unchanged. | | 2026-11-12 | minor | Explicit editing-data import keeps a single artboard beyond a capped 14,400 pt PDF page (#6865), with a warning; automatic mode stays unchanged. Scores and estimates unchanged. | +| 2026-11-12 | minor | #6625 cap/join follow-up: hidden-fill and no-fill stroke hits must respect their cap/join geometry; focused CPU regressions passed. Existing fill-stack evidence, scores and estimates unchanged. | | 2026-11-09 | minor | G4 review (#6084): positional variants no supported feature draws can be applied as glyph choices in both Glyphs views; unlisted glyphs still respect name ownership. OpenType style options keep only a valid last on-value when enabling a set. Existing contextual/ligature lookup and unsupported-feature gaps remain; estimate unchanged. | | 2026-11-07 | minor | G4: the Glyphs panel's Alternates for Current Selection applies the OpenType feature that draws a variant to that letter alone (`salt=2`; the style commands take `tag=N`; runs that differ only in their features shape as one piece of text), so an Arabic word stays joined, and Show › Entire Font lists the unencoded glyphs (#5514). Estimate unchanged. | | 2026-11-12 | minor | G11: numeric fields keep the caret when a focus click is released more than 1 pt from its press; a tap within 1 pt still selects the whole value (#6659, follow-up to #1326); short-drag and jitter-tap regressions in `tests/numfields.rs`; estimates unchanged. | @@ -927,6 +934,7 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | 2026-11-11 | minor | Eraser: fixed and varied tips and the Alt-drag marquee cut fill-only open contours and compound holes as areas; stroked open paths retain main behavior (#6582). Scores and estimates unchanged. | | 2026-11-11 | minor | G5: built-in Status Effects graphic style library (Poison Tint, Freeze Edge, Burn Aura, Stun Pulse, Stealth Fade, Shield Buff); Missing trimmed; estimate 7–17 → 6–16 h; MCP docs list UI Frames and Map Markers under Symbol libraries. | | 2026-11-11 | minor | G5: built-in Inventory Icons symbol library (Sword, Shield, Potion, Key, Gem; no default 9-slice); Missing trimmed; estimate 8–18 → 7–17 h. | +| 2026-11-11 | minor | #6625: path and compound-path interior hits follow enabled non-None fill rows, including lower fills beneath a top None row; hidden-only interiors miss; zero-opacity fills remain selectable. Scores and estimates unchanged. | | 2026-11-10 | minor | G6: MCP catalogue (#6460): headless lists `UI_COMMANDS` (`ui: true`), eight prompts, effect vs command ids, 33 tools, commands/reference; estimate unchanged. | | 2026-11-10 | minor | G4 type: Edit › Edit Custom Dictionary… adds, deletes and changes the custom dictionary's words, #4936; the Check Spelling dialog remains; scores and estimates unchanged. | | 2026-11-10 | minor | Tidy-up, no content change: in Feature submission evidence, a stray table row and two "PR #NNNN revision" notes move into Feature revisions, the three "Feature evidence last updated" lines become one, the duplicate Flyout update note goes (its row stays), and eight reconciliation rows become two. Scores and estimates unchanged. | diff --git a/docs/localization-hi.md b/docs/localization-hi.md index 743a1697ec..55c91c6505 100644 --- a/docs/localization-hi.md +++ b/docs/localization-hi.md @@ -131,9 +131,12 @@ The pinned egui fork shapes Devanagari with HarfRust. The desktop's existing `Ui finds an installed covering face, such as Nirmala UI, Kohinoor Devanagari or Noto Sans Devanagari. If a `CRAFT_FONTS_DIR` build includes a face tagged `Deva`, it is also installed at the end of each UI font family. No font binaries are added to this repository. Without either an embedded -or installed covering face, Hindi cannot display correctly. The web has no system fonts and -needs a Devanagari face supplied through craft-fonts; this catalog alone does not supply one. +or installed covering face, Hindi cannot display correctly. The web has no system fonts. A web +build made with craft-fonts serves Noto Sans Devanagari Regular beside the wasm and fetches it +when the interface language is Hindi or the interface paints Devanagari +(`crates/text/web-fonts.txt`, `demand`); until it arrives, Devanagari draws as missing-glyph boxes. +Other languages do not fetch it. Before release: native-speaker review of the draft (especially less common labels and error -messages), visual checks for clipped labels and matras at different UI scales, and a web-font -build. Reviewers should use this glossary to make terminology corrections consistently. +messages), and visual checks for clipped labels and matras at different UI scales, on the +desktop and on the web. Reviewers should use this glossary to make terminology corrections consistently. diff --git a/docs/localization-parity.md b/docs/localization-parity.md index 7dba5ca0b4..66b73023bd 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -31,7 +31,7 @@ Chinese by `imachus`). Georgian and the original Gujarati catalog are recorded a | English | `en` | source, 100% | all | Latin | — | full | — | | Simplified Chinese (Mandarin) | `zh-hans` | 5,102 rows, 791 of them `@msg` (counted 2026-10-21): menus, `tl!` literals and messages complete when counted | all (3,554 `@msg` and 48 `@msgplural` rows, counted 2026-11-13: the untranslated report lists 55 missing messages for it, which open #7116, #7211, #7330, #7378 and #7405 translate) | CJK UI font from craft-fonts (BIZ UDPGothic) when embedded, else a system font; IME with marked text at the caret; vertical type partial ([type-parity.md](type-parity.md)) | no | full | — (review) | | Spanish | `es` | 4,009 / 4,020 (99.7%) | all (604 messages) | Latin | no | full | — (review) | -| Hindi | `hi` | 8,782 rows (2026-11-13): 3,014 `@msg`, 47 `@msgplural`, 41 `@plural`; the untranslated report on main `f793044f83` (2026-11-14) lists 676 missing rows for it: 608 in its own section and 68 that every checked language lacks | menus, dialogs, tooltips and scanned messages; contributor-approved loanword terminology; agent wording pass | UI and document text shape with HarfRust; installed desktop Devanagari fallback, or a `Deva` craft-fonts face; web font still needed | contributor terminology review; 2026-11-13 wording pass on messages and longer labels, and a word-sense pass on short labels, with a glossary-term test; wider proofread welcome | complete catalog, machine-assisted draft | reported missing rows, native review, layout and web font | +| Hindi | `hi` | 8,782 rows (2026-11-13): 3,014 `@msg`, 47 `@msgplural`, 41 `@plural`; the untranslated report on main `f793044f83` (2026-11-14) lists 676 missing rows for it: 608 in its own section and 68 that every checked language lacks | menus, dialogs, tooltips and scanned messages; contributor-approved loanword terminology; agent wording pass | UI and document text shape with HarfRust; installed desktop Devanagari fallback, or a `Deva` craft-fonts face; the web fetches Noto Sans Devanagari when the interface needs it | contributor terminology review; 2026-11-13 wording pass on messages and longer labels, and a word-sense pass on short labels, with a glossary-term test; wider proofread welcome | complete catalog, machine-assisted draft | reported missing rows, native review and layout | | Gujarati | `gu` | 4,673 rows (2026-11-14): original 4,286 unchanged; all 387 additions contributor-reviewed and approved | menus and dialogs; status/error messages partial | installed Gujarati fonts on desktop; optional `Gujr` craft-fonts fallback; no Gujarati face in the pinned CI/release fonts or web startup list | original catalog reviewed by a native speaker; all 387 later additions approved by the contributor, with 11 wording corrections | contributor-reviewed catalog | remaining messages and a bundled Gujarati web font | | Arabic | `ar` | 0 | none | document text: bidi layout and Paragraph Direction; interface: no right-to-left layout, no Arabic shaping in egui | no | none | 25–40 | | 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) | @@ -39,13 +39,13 @@ Chinese by `imachus`). Georgian and the original Gujarati catalog are recorded a | 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%) | 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) | +| 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 fetches NanumGothic from craft-fonts when the interface needs it; IME path exists | no (AI-drafted) | full | — (review) | | 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) | **Historical 12-language score: ~82%** (equal weights: 100 + 85 + 100 + 0 + 0 + 100 + 100 + 100 + 100 + 98 + 100 + 100, over 12). **To `full` for all twelve: ~50–85 h** (historical estimate, not re-scored here). Hindi now has a catalog that the tests count as complete, and UI shaping; its remaining work is the rows the -untranslated report lists for it, native review, layout checking and the web font. Arabic still needs its catalog and right-to-left interface. Each new Latin-script catalog is ~4,000 rows; the existing ones were written in a few agent hours each +untranslated report lists for it, native review and layout checking. Arabic still needs its catalog and right-to-left interface. Each new Latin-script catalog is ~4,000 rows; the existing ones were written in a few agent hours each plus review. Native-speaker review is human work and isn't in the hours. ## Other shipped languages @@ -66,7 +66,7 @@ plus review. Native-speaker review is human work and isn't in the hours. | Swedish | `sv` | 8,991 rows, 3,106 of them `@msg` and 48 `@msgplural` (counted 2026-11-14): the untranslated report lists 518 missing messages for it, and 12 menu strings, 1 `tl!` literal and 3 undo labels; one/other plurals | full; native review welcome | | 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 | +| Georgian | `ka` | 9,758 rows, 3,740 of them `@msg` and 49 `@msgplural` (counted 2026-11-15): menus, panels, dialogs and plurals (one count-neutral form); the untranslated report lists 1 missing Georgian message; reviewed by a native speaker | 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 | | 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/mcp.md b/docs/mcp.md index 4c1b661f42..655efa1b4c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -270,9 +270,32 @@ the suite) keep the agent to the folders you give it: selected objects only, and `clipboard.exportSvg` checks the copied objects, following a relative path from the document they came from while it is open; in a frame a request drives, Copy then puts no SVG on the system clipboard. An image whose pixels the document holds exports embedded, and a URL is not checked. -- With `preserveEditing`, the document an SVG or SVGZ of these outputs carries leaves out the Export for Screens - folder (`export_settings.folder`) when it is outside the read roots, as `document.exportSettings` does; the - other export settings and the art are kept, and the open document keeps the folder. +- The same error refuses, before any file or folder is written, every output of these commands and + `document.exportPdf` that carries the native document (the native file or template, EPS, `.ai`, `.ait` and + PDF files the JavaScript rule above lists, with `selectedOnly` and `document.exportSelection` the selected + objects' document) when that document names a file outside the read roots: a linked image or placed file, the + relative path kept of one (taken from the document's folder), or a data set's image, in every symbol, + pattern, graph design and brush, used or not. A stored brush entry that does not read as a brush is refused + too, since its links cannot be checked. Files that carry no native document are written as before, and the + document keeps every link and data set. +- The document these outputs carry (an SVG or SVGZ with `preserveEditing`, a native file or template, an EPS + file, a `.ai` or `.ait` file, a PDF with Preserve Editing, and the document `file.package` writes and the + linked native documents it rewrites) leaves out the Export for Screens folder (`export_settings.folder`) when + it is outside the read roots, as `document.exportSettings` does; the other export settings and the art are + kept, and the open document keeps the folder. `file.package` copies a linked PDF, `.ai` or EPS file, and a + linked native document with `relink: false`, as it is: when the native document such a file is or carries + keeps a folder outside the read roots, the package is refused before anything is written with "a linked + file's export folder is outside the read roots", which names no file or folder. +- An exporter plug-in's format (`plugin.`) carries the native document too: its plug-in is given the + document's JSON. The JavaScript and linked image rules above refuse its files from every command that writes + them, before the plug-in runs and before any file or folder is written, and the JSON the plug-in is given + leaves out an Export for Screens folder outside the read roots. +- `file.package` refuses, before anything is written, a linked file whose native document it can't read to + check against the read roots: a native document that doesn't load, a PDF or `.ai` file that can't be opened + (one that needs a password to open, or a damaged one), and a PDF, `.ai` or EPS file whose editing data + doesn't load. The error, "a linked file's editing data can't be read to check it against the read roots", + names no file or folder. A PDF, `.ai` or EPS file without editing data is copied as before, and the person at + the keyboard packages every linked file as before. - `plugin.list`, `plugin.safeMode`, `file.recovery.*` and `ui_inspect`'s `scriptReport` leave out the paths outside the read roots, also those the person or an earlier request put there. In `plugin.list`, the plug-in folder last loaded is `null` in `folder.folder`, and a failed file in `folder.failed` and a plug-in's `source` @@ -657,6 +680,11 @@ applied colors still join the list while it is hidden. `ui.colorPanel {"rgbPerce RGB fields in percent, as a double-click right of an RGB field does, and `false` shows them from 0 to 255 again. `ui.colorRgbPercent` (Toggle RGB Percent in the command palette and Keyboard Shortcuts) switches between the two and answers true when the fields show in percent. +`ui.colorWheel {"view": "box", "channel": "red"}` shows the Color Wheel panel's box (a color field with the channel's +strip at its right) in place of the wheel, as the panel menu's Box View and Box Channel do, and `"view": "wheel"` +shows the wheel again. Keys left out keep their values. Params that are not an object, another key or a value off +the list return an error and change nothing. The command returns `{view, channel}`, and both settings are kept with +the preferences. In remote desktop mode, `invoke_menu` with `{"command":"ui.sampleScreenColor","params":{}}` shows the system's screen color sampler and returns `null` before a color is picked: the system's sampler on macOS, the XDG desktop @@ -693,13 +721,13 @@ ends the wait, so the sampler can be shown again. The BSDs and headless sessions | `open_file` | `{path, importer?, params?}` | Opens any readable file as a new active document: `.vectorcraft`/`.drawcraft`, `.vctemplate`, `.svg`/`.svgz`, `.pdf`/`.ai`, `.ait`, `.eps`/`.epsf`, `.ps`, `.dxf`, `.emf`, `.wmf`, PICT (`.pct`/`.pic`/`.pict`, and a version 2 picture of any extension), HP-GL (`.plt`/`.hpgl`/`.hgl`/`.hpg`, and a file of an extension no other format reads that starts with plotter instructions), PNG (`.png`/`.pns`), JPEG, GIF, WebP, TIFF, BMP (`.bmp`/`.dib`/`.rle`), Targa (`.tga`/`.vda`/`.icb`/`.vst`), PCX, Pixar (`.pxr`), JPEG 2000 (`.jpf`/`.jpx`/`.jp2`/`.j2k`/`.j2c`/`.jpc`), HEIC/HEIF (`.heic`/`.heif`), JPEG XL (`.jxl`), PSD (`.psd`/`.pdd`)/PSB (an image opens as a document of its pixel size; a PSD or PSB file with its layers as layers, or as its merged image through `run_command document.open` with `layers: false`; a JPEG XL file as its first frame). Templates (`.vctemplate`, `.ait`) open as a new untitled document. PDF, `.ai` and SVG files saved with Preserve Editing reopen as the document they carry. The reply is `document.open`'s: its `warnings` say what didn't come in as it was (an EPS whose PostScript can't be read opens as its preview, and the warning names the PostScript error, the operator and the procedure). A file of an extension only an installed importer plug-in lists opens with that importer ([Plug-ins](#plug-ins)); `importer: "plugin."` opens the file with the importer it names, which must list the file's extension, also one a built-in format reads (in the app, as File › Open With does), and `params` gives that importer's parameters (their defaults when omitted). `run_command document.formats` lists the formats. | | `save_file` | `{path?, compress?, version?, preview?, precision?, options?}` | Runs `document.save`: the document's own file in its own format (native `.vectorcraft` unless it was opened from or saved as SVG, PDF or a restorable `.ai`; then `warnings` say what that format loses). A path's extension picks the format (`.vectorcraft`, `.vctemplate`, `.pdf`, `.svg`, `.svgz`, `.ai`: a PDF carrying the native document, which reopens editable; `.eps`: by default one file whose bounding box fits the visible art, the first artboard when no art shows; `options.useArtboards: true` makes the chosen artboard the page and, with two or more chosen, the file at the path is the central file of the visible art and each artboard is also written to `_.eps` beside it, listed in the reply's `files`). For a native file, `compress: true` gzips it (default: the `useCompression` preference, Preferences › File Handling › Use Compression), `version` (1 to 4) writes it for an older VectorCraft (1 and 2 are never compressed, and `version: 2` with `compress: true` is an error), `preview: true` embeds a PNG of the first artboard, and `precision` (0 to 9) rounds path anchors and handles to that many decimal places for that save only (colors, transforms and type stay exact). `options` passes the format's save options as `run_command document.formats` lists them. When `compress`, `version`, `preview` or `precision` is given both at the top level and in `options` with different values, the call is an error (`` `compress: true` and `options.compress: false` disagree: give the option once ``) and nothing is written. A key in `options` that no save format takes is an error, and nothing is written (see Parameter keys). The save drops each option the written format doesn't read. The reply's `warnings` then name each such option given (for example `` `compress` was not used: SVG files don't read it `` for an `.svg` path, and `` `options.preview` was not used: … `` for a key in `options`; a PDF-compatible `.ai` file reads `compress` but not `version`, `preview`, `precision`, `outlineText`, `hiddenObjects`, `transparentImages` or `preserveEditing`, and a legacy `.ai` file reads only its own options). For a `.ai` file, these warnings name the kind of `.ai` written: a legacy .ai (version 7) for `aiVersion: "7"`, a non-PDF-compatible .ai for `pdfCompatible: false`, and a PDF-compatible .ai otherwise, including a save that reuses the options the document was last saved with. `run_command document.save` and the other save commands refuse any option given beside the path and in `options` with different values, and give the same warnings for each key given beside the path or in `options` that the file doesn't read. The headless session and the app receive the same `app.save` params, and the app is also sent `wait: true`: the call returns once the file is written, or with the error (such as a path outside the write root), even with Background Save on. When the save asks first (the question before replacing a file that opened with losses, or on macOS and Linux the file dialog for an untitled document without `path`), the reply is `{pending}` or `"cancelled"` as before, and the save that runs after the answer uses the Background Save preference. Location refusals return `READ_ONLY_LOCATION: ` without a fallback panel for automation; see [Save location errors](#save-location-errors). | | `export` | `{path?, format?, scale?, artboard?, range?, selection?, outlineText?, options?}` | `svg`, `svgz`, `pdf`, `ai` (the PDF-compatible `.ai` that Save writes, which carries the document when every artboard is written in order), `eps`, `dxf`, `emf`, `wmf`, `hpgl` (a `.plt` plot file for plotters and cutters), `png`, `jpg`, `webp`, `gif`, `png8` (an indexed `.png`), `tiff`, `bmp`, `tga`, `psd` (layered), `txt` (the document's text), `vectorcraft` or `template` (a native template). The tool's `format` enum and `document.formats` list them, generated from the engine's format table. When `format` is omitted, it comes from the path's extension. PDF and `.ai` write one page per artboard: all of them, or `artboard` (0-based) / `range` (`"1-3, 5"`, 1-based). SVG and SVGZ write one file per chosen artboard. EPS writes one file of the visible art; with `artboard`, `range`, `options.artboards` or `options: {"useArtboards": true}` it writes one file per chosen artboard, after a central file of the visible art when there are two or more, and `useArtboards: false` keeps the one file. Rasters, DXF, EMF, WMF and HP-GL write one artboard, or one file per chosen artboard with `options: {"useArtboards": true}`. Rasters also take `options: {"rect": [x, y, width, height]}` (page points, y down): that area of the page at the given `ppi`/`scale`, without an artboard and without changing the document; it is refused with `artboard`, `artboards`, `range` or `useArtboards`, with a non-positive or non-finite size, and for non-raster formats. `options` carries more format options (e.g. `{"quality": 80}` for JPEG). `selection: true` exports the selected objects cropped to their bounds (the reply adds their `bounds`, and reports `format` and the encoder's `warnings` as a whole-document export does); `outlineText: true` writes SVG text as paths. Template layers are left out, live effects are kept, and exporting `vectorcraft` never changes the document's path. Without `path` the bytes come back as `dataBase64`. Both backends run the same `document.export` call. | -| `add_text` | `{text, x?, y?, width?, height?, fit?, fitMinPercent?, path?, mode?, pathEffect?, size?, font?, color?, justify?, vertical?}` | Point type at (x, y) (`justify`: `left`, `center` or `right` starts, centres or ends each line on x); area type with `width`/`height` (`fit`: `none`, `autoHeight`, `shrinkText`, as `text.areaOptions`); or `path` + `mode` (`area`/`onPath`) to flow text in or along a path, with `pathEffect` (`rainbow`, `skew`, `3dRibbon`, `stairStep`, `gravity`; SVG export writes type on a path with any effect other than `rainbow` as outlines, with a warning); `justify` (also `auto`, `justifyAll`) aligns the paragraphs of every kind, as `text.setStyle` does later. `vertical: true` uses the existing vertical writing mode for every kind (default `false`, horizontal). Returns `{id}`, with `overflow: true` when the text doesn't fit its frame or path. | +| `add_text` | `{text, x?, y?, width?, height?, fit?, fitMinPercent?, path?, mode?, pathEffect?, size?, font?, color?, justify?, vertical?}` | Point type at (x, y) (`justify`: `left`, `center` or `right` starts, centres or ends each line on x); area type with `width`/`height` (`fit`: `none`, `autoHeight`, `shrinkText`, as `text.areaOptions`); or `path` + `mode` (`area`/`onPath`) to flow text in or along a path, with `pathEffect` for type on a path (`rainbow`, `skew`, `3dRibbon`, `stairStep`, `gravity`; SVG export writes type on a path with any effect other than `rainbow` as outlines, with a warning). An invalid effect is rejected before editing. `justify` (also `auto`, `justifyAll`) aligns the paragraphs of every kind, as `text.setStyle` does later. `vertical: true` uses the existing vertical writing mode for every kind (default `false`, horizontal). Returns `{id}`, with `overflow: true` when the text doesn't fit its frame or path. | | `apply_effect` | `{effect?, params?, ids?}` | Appends a live effect. Without `effect`, returns the effect catalogue with parameters and defaults. | | `pathfinder` | `{operation, ids?}` | `unite`, `minusFront`, `intersect`, `exclude`, `divide`, `trim`, `merge`, `crop`, `outline`, `minusBack`. For a live version, apply the `pathfinder.*` effect to a group (`effect.apply` groups several loose selected objects first). In remote desktop mode, `run_command` and `invoke_menu` can both call `pathfinder.repeat` with `{}`. Successful panel operations, direct `object.pathfinder.*` commands, and `command.batch` steps (including Actions panel playback) set its history. Repeat applies it to the current selection using current Pathfinder Options. Trap, compound-shape edits, live effects and `action.batch` do not set history. With no history it returns "no Pathfinder operation applied yet". | -| `transform` | `{ids?, dx?, dy?, rotate?, scale?, scaleX?, scaleY?, reflect?, shear?, origin?, copy?}` | Runs move, rotate, scale, reflect, shear in that order. `rotate` is in degrees counter-clockwise; a positive `shear` moves the top to the right. With `copy`, the first step duplicates. | +| `transform` | `{ids?, dx?, dy?, rotate?, scale?, scaleX?, scaleY?, reflect?, shear?, origin?, copy?}` | Runs move, rotate, scale, reflect, shear in that order. `rotate` is in degrees counter-clockwise; a positive `shear` moves the top to the right. With `copy`, the first step duplicates. A `scale`, `reflect` or `shear` that its command would refuse returns that error before any step runs; nothing changes and no undo step is recorded. | | `create_graph` | `{type?, x, y, width, height, csv? \| series?, categories?, rows?}` | The nine Illustrator graph types: column, stacked column, bar, stacked bar, line, area, scatter, pie and radar. An empty CSV cell or a `null` in `rows` is a blank value; a number in straight quotes is a label. Edit later with `graph.setData` / `graph.setType` via `run_command`. `graph.column {design, columnType: vertical\|uniform\|repeating\|sliding, each, fractions: chop\|scale}` draws the columns or bars of the series picked with Group Selection (or `seriesIndexes`, or all of them) with a graph design saved by `graph.design`; with no `design` it returns the series' current design and options. Type in the design that holds a `%` followed by two digits shows each column's value, with at least the first digit's places before the decimal point and the second digit's places after it. | | `text_wrap` | `{ids?, offset?, invert?, release?}` | Area type below the objects (same layer) flows around them. `offset` is in points, from -1000 to 1000 (default 6). An offset outside that range or not a number, or an `invert` or `release` that is not true or false, is an error and changes nothing; `object.textWrap.make` and `object.textWrap.options` refuse the same values. | -| `undo` / `redo` | `{}` | Many calls that change nothing record no undo step, for example `object.align` with nothing to move, `object.move` by 0 without `copy` and `object.showAll` with nothing hidden. `undo` (`edit.undo`) after such a call undoes the step before it. `inspect_document` lists the undo steps as `history`. `run_command` with `edit.clearHistory` removes every undo and redo step of the active document and returns `{cleared}`, the number of steps removed; the document stays as it is, and the command records no undo step. `run_command` with `edit.newDocumentFromState` and `{index?, created?}` makes a new document holding the art as it was at that state and makes it the active document, and returns `{index, title}`. `index` is a row of the History panel, with 0 the oldest state kept, and an omitted or null `index` uses the current state. An `index` that names no state fails with `no history state N`, one that is not a whole number with `` `index` must be a whole number ``, and either changes nothing. `created` is File Info's created date in Unix seconds or null, and defaults to now. The new document takes the next `Untitled-N` name, is marked unsaved, has nothing selected and has no steps to undo or redo. It is out of symbol, opacity-mask and pattern editing, and the art drawn in a pattern's tile is stored in the pattern, as `object.pattern.done` stores it. The source document and its steps stay as they are, except that typing or a drag in progress is first kept as a step. When a command keeps a drag whose preview Real-time Drawing off had not applied yet (`edit.undo`, `edit.redo`, `edit.clearHistory`, `edit.newDocumentFromState` and the other commands that end a drag first), and applying that preview gives a warning, the command's result carries it as `previewWarning`, and as `warning` too when the command gives no warning of its own; the app's status bar shows `warning`. While the Type tool edits type, `undo` and `redo` put its caret, with no characters selected, at the end of the text the step changed: after the text it puts back or retypes, or where the text it takes out was. A step that changes no characters, such as a formatting change, leaves the caret and the selection where they are. | +| `undo` / `redo` | `{}` | Many calls that change nothing record no undo step, for example `object.align` with nothing to move, `object.move` by 0 without `copy` and `object.showAll` with nothing hidden. `undo` (`edit.undo`) after such a call undoes the step before it. Settings that change without an undo step stay as they are when `undo` or `redo` brings back a step that did not change them: the perspective grid's view options and active plane, the grid preferences (`gridlineEvery`, `gridSubdivisions`), the export settings (`assets.settings.set`), and the current brush and symbol. A step that changed one of them, such as a perspective grid preset that shows the grid, takes that change back. The point Automatic Plane Positioning holds comes back with the step, and is let go when the active plane kept is another one. `inspect_document` lists the undo steps as `history`. `run_command` with `edit.clearHistory` removes every undo and redo step of the active document and returns `{cleared}`, the number of steps removed; the document stays as it is, and the command records no undo step. `run_command` with `edit.newDocumentFromState` and `{index?, created?}` makes a new document holding the art as it was at that state and makes it the active document, and returns `{index, title}`. `index` is a row of the History panel, with 0 the oldest state kept, and an omitted or null `index` uses the current state. An `index` that names no state fails with `no history state N`, one that is not a whole number with `` `index` must be a whole number ``, and either changes nothing. `created` is File Info's created date in Unix seconds or null, and defaults to now. The new document takes the next `Untitled-N` name, is marked unsaved, has nothing selected and has no steps to undo or redo. It is out of symbol, opacity-mask and pattern editing, and the art drawn in a pattern's tile is stored in the pattern, as `object.pattern.done` stores it. The source document and its steps stay as they are, except that typing or a drag in progress is first kept as a step. When a command keeps a drag whose preview Real-time Drawing off had not applied yet (`edit.undo`, `edit.redo`, `edit.clearHistory`, `edit.newDocumentFromState` and the other commands that end a drag first), and applying that preview gives a warning, the command's result carries it as `previewWarning`, and as `warning` too when the command gives no warning of its own; the app's status bar shows `warning`. While the Type tool edits type, `undo` and `redo` put its caret, with no characters selected, at the end of the text the step changed: after the text it puts back or retypes, or where the text it takes out was. A step that changes no characters, such as a formatting change, leaves the caret and the selection where they are. | For example, create editable Japanese area type with the engine's vertical writing mode: @@ -821,6 +849,9 @@ stroke instead of the whole object: `run_command effect.apply {"effect": "path.o `effect.remove`, `effect.setParams` (`visible` toggles one) and `effect.duplicate` address that item's effects; `apply_effect` uses the active item. `effect.list` reports each object's item effects under `applied[].items`. +`distort.twist` keeps anchors on its outer circle fixed. Their handles follow the tangent of the +rotation inside that circle, including for positive and negative angles. + On a path directly inside a graph series, `appearance.setItem`, `appearance.addFill`, `appearance.addStroke`, `appearance.removeItem`, `appearance.moveItem`, `appearance.duplicateItem`, `appearance.clear`, `appearance.reduceToBasic`, `appearance.showAllHidden`, `appearance.transfer`, `appearance.copyFrom`, `paint.default`, @@ -1099,7 +1130,9 @@ Color Themes (local only: no online service) keeps five-colour themes in the pre harmony rule makes from a base colour (base first; `name?` defaults to "Theme N", `replace: ""` overwrites that theme in place). `colorTheme.list` answers `{themes: [{name, colors: [hex], keys: [colour keys], rule?}]}`, `colorTheme.delete {name}` removes one and `colorTheme.addToSwatches {name}` adds one to the Swatches panel as a -colour group (one undo step). +colour group (one undo step). The Create tab's Set the current fill or stroke to the selected color button runs +`paint.setFill` (or `paint.setStroke` with the Stroke proxy in front) with the selected colour and `keepModel: true`; +a script does the same with those commands. ```json {"name":"run_command","arguments":{"command":"colorTheme.save","params":{"color":"#2266aa","rule":"splitComplementary","name":"Harbor"}}} @@ -1130,7 +1163,12 @@ data larger than 8 MiB or holding more than 2,000,000 XML nodes is left out (the reads), each with a warning. With `outlineText`, the bound type is written as outlines, so its text variables open unbound (with a warning). `document.open` reads the variable data of an SVG back (unless the SVG reopens from Preserve Editing): its text variables and data sets, no active data set, and each text variable bound to the type -object its `docRef` names; the art stays as the file draws it. Variable data that `variable.loadLibrary` would refuse +object its `docRef` names; the art stays as the file draws it. Variables of other kinds are left out with one warning +that names each kind once, in the order it first comes, with its count: ``variables that aren't text were left out: +Visibility (2), Linked File (1), Unknown (1), `custom` (1)``. Visibility, Linked File and Graph Data are the +`visibility`, `fileref` and `graphdata` traits, Unknown is a variable without a `trait`, and any other `trait` is +written as the file writes it, in backticks, with each backtick in it doubled. The status bar shows the kinds VectorCraft +names in the interface language. Variable data that `variable.loadLibrary` would refuse is left out with the warning "the file's variable data wasn't read", and the art opens. `svgz` takes the same options and writes the SVG gzipped (`.svgz` files also open, place and paste). `run_command document.save {path: "x.svg", svg: {…}}` saves as SVG (or `.svgz`). Colorized grayscale and 1-bit images export in their fill color; linked mode writes a coverage PNG, and Tiny 1.2 writes a colorized PNG. @@ -1181,6 +1219,13 @@ styles and brushes. `color.removeProfile`, `view.proofSetup`, `view.proofColors`, `view.overprintPreview`, `view.separationsPreview` and `swatch.setSpot` reject a param of the wrong type, such as `"bpc": "no"`, `"on": 1`, `"to": 5` or `"colors": "#fff"`, and change nothing. Omitting a param or giving null keeps its default. +`view.separationsPreview {soloToggle: plate}` is the Separations panel's Alt-click on a plate's eye: it shows that +plate alone, and when that plate is already the only one of the active document's plates shown, it shows every +plate, spot plates included ([Print color separations](https://helpx.adobe.com/illustrator/using/printing-color-separations.html) +describes the second Alt-click or Option-click on the eye bringing every separation back, and the first one showing +that plate alone). A hidden plate, another plate while one shows alone, or any plate while none is shown becomes +the only plate shown; these cases are VectorCraft's own rules. `only` always shows just the named plate, so +repeating it changes nothing. Neither adds an undo step. The Separations panel's Assign rows (where Edit › Assign Profile… goes) act on the profile of the document's color mode: Don't Color Manage This Document runs `edit.assignProfile` with null for that model (no profile, so the colors show through the working space), Working RGB or Working CMYK with the working space's name (that profile stays @@ -1243,6 +1288,10 @@ Draw, look, export: {"name":"export","arguments":{"path":"/tmp/icon.png","range":"1-3","options":{"useArtboards":true}}} ``` +The desktop command `file.export.png` accepts `document.export` options. Without `path`, it asks for a destination +and opens PNG Options with supplied values such as `ppi`, `background`, `antiAlias`, and `interlaced` retained. +Omitted options use the dialog defaults. Nonpositive resolutions are rejected when the export is confirmed. + Export As goes through `options` too: for PNG, JPEG and WebP `useArtboards: true` writes one file per artboard (all, or `range`), named `-.`, and returns `{path, files}` (a PDF keeps them as pages of one file; an SVG writes one file per artboard of a `range`); `useArtboards: false` exports the bounds of the visible art with what @@ -1349,7 +1398,7 @@ the image at, and all paint that one image. A 16-bit PNG that is not resampled, recompressed or converted keeps its 16 bits a sample in PDF 1.5 and later files, and is written at 8 bits in PDF 1.3 and 1.4 files. CMYK images stay CMYK (DeviceCMYK, or ICC-based with the CMYK profile when colours are tagged, as in PDF/X-3 and -PDF/X-4): a CMYK JPEG neither resampled nor recompressed is written unchanged, and the others' ink amounts are +PDF/X-4, where an image in the output intent's profile is DeviceCMYK): a CMYK JPEG neither resampled nor recompressed is written unchanged except that its `ICC_PROFILE` segments are removed when `output.profiles` is `none` (except in PDF/A, and in PDF/X-3 and PDF/X-4 files that do not write CMYK colors as DeviceCMYK) and in PDF/X-3 and PDF/X-4 when they are the CMYK output intent's profile and CMYK colors are DeviceCMYK, and the others' ink amounts are resampled and compressed again (CMYK JPEG or ZIP). `output.conversion` converts them like CMYK colours: `destination` to another CMYK profile or to RGB, `preserveNumbers` (and PDF/X-1a) keeps their numbers in a CMYK destination. `document.pdfSettings` lists the options that differ from the preset and the warnings without writing a file. @@ -1451,9 +1500,11 @@ a layer named after the page (`Page 2`). A PDF-compatible `.ai` with `cropTo: "c when it opens as art. A page on its trim box shows its bleed box round the artboard, and the pages give the document their bleed; the artboards are then 36 pt apart plus the bleed on both sides. The document opens in CMYK when most of those pages are painted mostly in CMYK, unless `colorMode` names a mode. All the pages' objects share one copy of the file. The Links panel lists each -page, and `links.embed` makes a page editable art. +page, and `links.embed` makes a page editable art. The command's `linkPages` defaults to false; the dialog checks the +box when All is picked and clears it when Range is picked, for a file it can link, and `ui.dialog.set` of `allPages` +does the same. A box checked or cleared by hand keeps that state until the other of All and Range is picked. `document.open` refuses `linkPages` for a file that is not a PDF or a PDF-compatible `.ai`, for a file given as -`dataBase64` without a path, with a `password`, and with `textAs: "outlines"`, and rejects a `linkPages` that is not +`dataBase64` without a path, with a `password`, with `textAs: "outlines"` and for a file over 256 MB, and rejects a `linkPages` that is not true or false. Save then asks for a name. `document.open`, `file.place` and `document.pdfInfo` reject a `cropTo`, `crop`, `password`, `colorMode` or `textAs` that is not a string, and `document.pdfInfo` rejects a `thumbnailSize` that is not a number. The error names the param, @@ -1462,8 +1513,9 @@ Imported colours keep their model: DeviceCMYK and CMYK ICC colours stay CMYK (a file painted mostly in CMYK opens as a CMYK document), DeviceGray is Gray, and Separation and DeviceN inks become spot swatches the art links to at its tint (gradient stops too). CMYK images (DeviceCMYK, or ICC-based with four components) keep their ink amounts: a CMYK JPEG as it is, any other as a CMYK TIFF -(masked CMYK images, and ones with 1, 2 or 4 bits per sample, open in RGB with a warning). Placing a CMYK TIFF keeps it -CMYK too. +(masked CMYK images keep their inks, the mask coming in as an opacity mask; ones with 1, 2 or 4 bits per sample open in RGB with a warning). In a file with a CMYK +`/GTS_PDFX` output intent, a DeviceCMYK image carries the output intent's profile, except where it is drawn with a +`/DefaultCMYK` in the resources in scope. Placing a CMYK TIFF keeps it CMYK too. `colorMode: "rgb" | "cmyk"` opens any file in that mode instead, its colours converted as `file.documentColorMode` does (`grays` too): @@ -1754,7 +1806,8 @@ vectorcraft-cli run --cmd file.new --params '{"width":800,"height":600}' \ `run` prints one JSON line per step (`open`, `cmd`, `export`) and exits non-zero on the first failure, naming the step (counting from 0, as `"$N"` references do) and its command. `--params` applies to the `--cmd` just before it. `run` -also accepts the host commands `file.open`, `file.save`, `file.export`, `file.exportForScreens` and `tool.select`. +also accepts the host commands `file.open`, `file.save`, `file.export`, `file.exportForScreens`, `tool.select` and +`tool.selectLastSelection`. `run --in`, `convert` and `info` read every format `document.open` reads (`vectorcraft-cli --help` lists them). ### Steps from a file or standard input @@ -1812,8 +1865,8 @@ preferences (the folder the desktop app uses, so both see the same ones; `VECTOR `file.new`, `document.open`, `document.activate`, `file.close`, `file.revert`, `edit.undo`, `edit.redo` and a failed `command.batch` too; with none assigned, or no document open, the working spaces are. The `workingCmyk` target of `view.proofSetup` simulates the working CMYK space in such a document too. `color.convert`'s - `outOfGamut` and `deltaE`, `color.gamutCheck`, and the out-of-gamut warning of the Color panel and Color Picker - check against the assigned CMYK profile, else the working CMYK space; the warning updates when either changes. + `outOfGamut` and `deltaE`, `color.gamutCheck`, and the out-of-gamut warning of the Color panel, the Color Picker, + Swatch Options and New Swatch check against the assigned CMYK profile, else the working CMYK space; the warning updates when either changes. Not remembered: the document, anything else. Nothing is read or written when `VECTORCRAFT_NO_PREFS` is set, and a server confined with `--automation-read-root` or @@ -2274,6 +2327,11 @@ path to a value inside a list or an object, and the document and its undo histor → invalid parameters for `view.saved.edit`: `edits[0].delete` must be true or false, not 1 ``` +A refused step of a `command.batch` gives its command's error as it is. A refused step of an `action.batch` is named +by its place in `commands`, from 1, before its command's error: with `commands` of an Unlock All and the +`view.saved.new` above, the error is +``invalid parameters for `action.batch`: action step 2 (`view.saved.new`) failed: invalid parameters for `view.saved.new`: `zoom` must be a number > 0, not 0``. + A schema nests at most 16 lists and objects. A value that would go past that depth is refused with the same kind of parameter error, ``invalid parameters for ``: `` is nested too deeply``, where `` is the path to the value. A schema that is wrong in itself, such as one that nests past 16 levels or puts a list of ids or a point @@ -2680,8 +2738,8 @@ script reads files with them: - `open('r')` opens a file to read, and `read([chars])`, `readln()`, `readch()`, `seek(pos[, mode])`, `tell()`, `eof` and `close()` read it. `read`, `readln` and `readch` count characters, and `seek` and `tell` count bytes. `readln` and `readch` take CR, LF, CRLF and LF CR as one line end. `folder.getFiles([mask])` lists a folder, sorted by name; - the mask matches `*` and `?` without regard to case, and a function as the mask keeps the entries it returns true - for. + the mask matches `*` and `?`, without regard to case on Windows and macOS and with case elsewhere, and a function + as the mask keeps the entries it returns true for. - A method that fails returns `false`, `null` or an empty string and sets `error`, such as `Script file access denied`, `Script file does not exist` or `Script file is not open`. A count or a position that is not a finite number, or a negative count, throws a `RangeError`. @@ -2696,7 +2754,9 @@ VectorCraft reads files by these rules of its own: `getFiles` leaves such an entry out. A missing file is refused the same way unless the nearest folder above it that exists is inside the script's folder. It is also refused when a link above it leads to a folder that does not exist. - `open` reads the whole file. A file larger than 8 MiB is refused from its size before any of it is read, with - `Script file exceeds 8 MiB`, and a run that opens more than 32 MiB in all ends with an error. A run has at most 256 + `Script file exceeds 8 MiB`, and a run that opens more than 32 MiB in all ends with an error. A file opened again + after its objects closed counts only the bytes it grew by, and a file that another object has open counts again. A + run has at most 256 files open at once; another `open` returns `false` with `Script has 256 files open` until one is closed. - The encoding is the one the file's byte order mark gives (UTF-8, UTF-16LE or UTF-16BE), otherwise the `encoding` the script set before `open`, otherwise UTF-8 when the bytes are valid UTF-8, otherwise CP1252. `BINARY` reads each @@ -2707,11 +2767,116 @@ VectorCraft reads files by these rules of its own: folder gives `null` with `Script folder mask takes too many steps to match`. - A path longer than 32,767 characters throws a `RangeError` (`Script file path exceeds 32,767 characters`) when a `File` or `Folder` is made from it. -- Writing is not available yet: `open('w')`, `open('e')`, `open('a')`, `write`, `writeln`, `copy`, `remove`, - `rename`, `create` and `createAlias` return `false` with `Script file writing is not available`, and setting - `length`, `hidden` or `readonly` sets `error` to that message and changes nothing. The file - and folder dialogs return `null`, and `execute` opens nothing and returns `false`. In the web build every lookup - fails with `Script file access is unavailable on the web`. +- `createAlias` returns `false` with `Script files cannot make aliases`, setting `hidden` sets `error` to `Script + file hidden setting cannot be changed` and changes nothing, and `execute` opens nothing and returns `false`. In the + web build every lookup fails with `Script file access is unavailable on the web`. + +The help page's writing members work as it describes +(, +): + +- `open('w')` empties the file, or makes it, `open('e')` opens a file that is there, and `open('a')` opens it at its + end. `write(...values)` writes the values as `String(value)` gives them, and `writeln(...values)` adds the line end + `lineFeed` names: CR LF for `Windows`, CR for `Macintosh` and LF for `Unix`. A byte order mark is written only + when the script writes `\uFEFF`. +- `copy(target)` copies the file to a path or a `File` and replaces a file that is there. `remove()` deletes a file, + or a folder only when it is empty (`Script folder is not empty`), at once and without the trash. `rename(name)` + takes a name without a folder; a name that is in use gives `Script file name is already in use`, and the object + takes the new path; another object that has the file open writes to the new path. An object whose changes + `close` could not write does not remove or rename its file, and another object that has a removed file open + drops its changes and takes no more writes. `copy` of a file over 8 MiB gives `Script file exceeds 8 MiB`, and `copy` of a file that + is open copies what the open file holds; an object that has the target open then holds the copy. `folder.create()` makes the folder and the folders above it, and gives `Script file access denied` without making any when one of them is outside the places the script may write. Setting `length` cuts the file or + pads it with zero bytes, also in an object that has the file open, and setting `readonly` changes the file (on + Unix, setting it clears every write bit, and clearing it gives back the bits the run cleared, or else the owner's + write bit). `changePath` of an object whose changes cannot be written gives `false` with `error` set and keeps its path. `copy` onto the file itself leaves it as it is, and `open('w')` with an + encoding that is not one gives `false` and leaves the file as it is. +- `File.openDialog(prompt, filter, multiSelect)`, `File.saveDialog(prompt, filter)` and `Folder.selectDialog(prompt)`, + and the objects' `openDlg`, `saveDlg` and `selectDlg`, give a `File` or a `Folder`, or `null` when the person + cancels; `multiSelect` gives an array of the files picked. A string `filter` such as `"JavaScript:*.jsx;All + files:*.*"` gives the file types the dialog shows: each `name:pattern` starts a type, a pattern without a name adds + to the type before it, and patterns are separated by `,` or `;`. `*.ext` patterns name extensions and `*` or `*.*` + every file; other patterns are left out. A `filter` that is a function is called with a `File` for each file + picked, and the files it gives a false value for are left out of the result; when none is left, the dialog + gives `null`. The dialog itself then shows every file. + +VectorCraft writes files by these rules of its own: + +- A script writes only in `Folder.temp`, `Folder.userData` and what a person allowed it in a file dialog. Its own + folder is only read. `Folder.temp` is a folder for the run, made when the script first names it and deleted when + the run ends; `new File()` names a new file there. `Folder.userData` is the script's own folder in the Script Data + folder next to the settings, kept between runs; a script given as `source`, or a session without a settings + folder, gets one inside `Folder.temp`. When that folder is a link, `Folder.userData` is `null` and the place the + link leads to is not granted. When automation write roots are set and do not take the folder, `Folder.temp` or + `Folder.userData` is `null` and the folder is not made; the same holds when they do not take a missing folder above it. When automation write roots are set, the place written must also be inside + them. Opening a file with `e` or `a` reads it, so the automation read roots apply to it as well. The folder that + holds the settings (the Scripts and Plug-ins folders among them) is kept out of every grant, also before it has + been made, apart from the script's own `Folder.userData`, and a folder that holds it cannot be renamed. Anything + else gives `false` with + `Script file access denied`. +- What a script writes is written when it closes the file or when the run ends, also when the run fails. At the + run's end the files left open are written in the order they were opened. A file + that `close` could not write stays open, so a later `close` tries again, and is written again when the run ends; a + `write` that would pass the run's limit + is not written. A run that + would otherwise succeed fails when a changed file it left open cannot be written, with + `Error: the script left open files that could not be written` and the files' paths. One file + holds at most 8 MiB, and a run that writes more than 32 MiB in all ends with an error. `write` encodes in the + file's encoding: `ASCII` and `ISO-8859-1` give `false` with `Script file cannot encode the text` for a character + they cannot hold, and `BINARY` writes each character's low byte. `write` and `writeln` turn their values into text + only for an open file, and stop once the text is longer than 16,777,216 UTF-16 code units, giving `false` with + `Script file exceeds 8 MiB`. Each object that has a file open holds its own bytes, so the 32 MiB counts what + setting `length` adds to the file and to each such object, and what `copy` writes to its target and to each such + object of the target. The report's `written` names each file written, at most 4,096 of them; a run that wrote more + also has `writtenMore: true`. +- In the app a file dialog shows the script's prompt and what the script asks for: a file to read (open), a file to + read and write (save), or a folder to read and write with everything in it. The person chooses with Choose…, whose + dialog picks several files at once, and adds them to those chosen before, when the script asked for several with + `multiSelect` (Choose… keeps at most 2,048, and the dialog says when it left out the files picked after them), and + then picks Allow Once, Always Allow This Script or Deny; Deny, Enter, Escape and Cancel give `null`, and Stop ends + the run. Choose… for a folder's `selectDlg` opens the host's folder dialog in that folder. + The prompt and what the dialog says the script asks for come from the script's request, so `ui.dialog.set` on the + dialog's `kind` or `prompt` does not change them. Only the person at the keyboard allows access: an `answer` of + `once` or `always` from `ui.dialog.set`, `ui.dialog.confirm` or synthetic input gives `Only the person at the + keyboard can allow a script's file access`, and the dialog stays open; `deny` and `stop` are taken from automation. + Always Allow This Script keeps the grant in `Script Grants.json` next to the settings for that script file with + that text with the files it includes, by its SHA-256, so a changed or moved script, or a changed included file, + asks again. It is offered only for a script run from a file. The grant also keeps the SHA-256 of each source the + run evaluated up to its end (a file `$.evalFile` ran, a string given to `eval` or `Function`, at most 256). A later + run loses the grant before it evaluates a source the grant does not list, and from the start when its + `#targetengine` engine holds code the grant does not list, such as another script's. A file opened under a + grant the run loses gives `Script file access denied` when it is read or `seek` is called after that. A kept grant stays on the + real path that was allowed: when that path now leads elsewhere, through a link put in its place or in a folder + above it, the grant is not used. +- A command a script runs with `vc.run` reads and writes files only where the script's `File` and `Folder` objects + may, and in the files the open documents were opened from or saved to. Anything else fails with + `Script file access denied` and the path, saving into a user library (swatches, brushes, symbols or graphic + styles) included; reading the app's own libraries is allowed. A script given as `source` that a person allowed nothing writes only in + its `Folder.temp` and `Folder.userData` and to the open documents' own files. + A pick inside the folder that holds the settings gives `null` and sets `error` to `Script file access to the app's + own folders is not allowed`. +- A run with nobody to ask, as over MCP or the command line, gives `null` from every file dialog and sets `error` to + `Script file dialogs need a person to answer them`, and takes no kept grant. In the app, a file dialog inside a + built-in's callback, a getter, a conversion or a file `$.evalFile` runs throws an error. + +`script.grants {}` lists the kept grants: `{grants: [{script, sha256, code, path, write, folder}], file}`, with `code` +the SHA-256 of each evaluated source (of its UTF-16 code units in little-endian order), `folder` true for a folder's +grant, which covers everything in the folder (a file's grant covers its own path only, also when a folder later +takes its place), and `file` the grants +file's path, or `null` without a settings folder. Under automation read roots, a `script`, `path` or `file` outside them +is given as its file name alone. `script.grants.revoke {script?, path?, all?}` removes the grants of +a script file, of a path, of both together, or with `all: true` every grant, and returns `{removed}`. A path is +matched after its links are followed; under automation read roots, a path outside them is matched as given. While a script +runs it is refused with the busy error, as the run keeps the grants it started with. A grants file that is there but +cannot be read is left as it is: `script.grants.revoke` fails, and a grant picked with Always is not kept. A script +cannot run either command. + +```json +{"name":"run_command","arguments":{"command":"script.grants.revoke","params":{"all":true}}} +``` + +```sh +vectorcraft-cli run --cmd script.grants --params '{}' +``` Window › Script Console shows the session's script lines, oldest first: each run's start, its `$.write` and `$.writeln` output, its `vc.log` entries, its uncaught error as `name:line:column: message` (or `name: file:line:column: message` when the error is in another @@ -2774,6 +2939,10 @@ The rest of this section is VectorCraft's own rules: read finds new names after the menus have shown 16,384 different script and folder names since VectorCraft started. When the folder is there and cannot be read, the menu shows `The Scripts folder cannot be read`. +- Until the first read ends, the menu shows `Loading scripts…` in place of the listing, and + `The Scripts folder is still being read` once that read has taken 2 seconds. A first read that cannot start, or + ends without a listing, shows `The Scripts folder cannot be read`, and the next read tries again. Later reads keep + the last listing in the menu while they run. - A listed file is checked again when it is chosen. A file that is gone, is no longer a `.js` or `.jsx` file under the folder, or is or lies behind a link ends with `the script is no longer in the Scripts folder`, and nothing runs. The file is read once for that check, and the text that read checked is the text that runs; its `#include` lines @@ -3176,16 +3345,26 @@ dropped. ## Navigator panel options The Navigator panel menu's Panel Options… opens the `navigatorPanelOptions` dialog (fields `color`, `solidDashes`), -and `ui.navigatorPanelOptions {color?, solidDashes?}` sets the options without it → `{color, solidDashes}`; with -neither key it opens the dialog. `color` is the color the panel's view box is drawn in: `#rrggbb` or a preset name. +and `ui.navigatorPanelOptions {color?, solidDashes?, viewArtboardContentsOnly?}` sets the options without it → +`{color, solidDashes, viewArtboardContentsOnly}`; with none of the keys it opens the dialog. `color` is the color the +panel's view box is drawn in: `#rrggbb` or a preset name. The presets are VectorCraft's own list: Light Red (`#ff3030`, the default), then the layer colors ("Light Blue", "Red", "Green" and the rest). `solidDashes` (Draw Dashed Lines as Solid Lines, off by default) makes the panel's -thumbnail draw dashed strokes without their dashes; the canvas, printing and exports keep the dashes. Both are kept -with the UI state. A `color` that is not a color, or a `solidDashes` that is not true or false, is an error and -changes neither option. Behavior reference: [View artwork](https://helpx.adobe.com/illustrator/using/viewing-artwork.html). +thumbnail draw dashed strokes without their dashes; the canvas, printing and exports keep the dashes. +`viewArtboardContentsOnly` is the panel menu's View Artboard Contents Only, on by default: the thumbnail fits the +artboards and draws only the art inside them, so art on the pasteboard and in the gaps between artboards is left out +and a shape that crosses an artboard's edge is cut there. Off, the thumbnail also fits and draws the art outside the +artboards. The view box still shows the canvas's view either way. All three are kept with the UI state and apply to +every document; UI state saved without `viewArtboardContentsOnly` reads it as on, and a saved off stays off. Fitting +the thumbnail to the union of the artboards with a small margin, cutting the art at each artboard, and keeping the +choice with the UI state are VectorCraft's own rules. A `color` that is not a color, or a `solidDashes` or +`viewArtboardContentsOnly` that is not true or false, is an error and changes none of the options. Behavior +references: [View artwork](https://helpx.adobe.com/illustrator/using/viewing-artwork.html) and +[Navigate and zoom artwork](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/navigate-and-zoom-artwork.html). ```json {"name":"invoke_menu","arguments":{"command":"ui.navigatorPanelOptions","params":{"color":"Light Blue","solidDashes":true}}} +{"name":"invoke_menu","arguments":{"command":"ui.navigatorPanelOptions","params":{"viewArtboardContentsOnly":false}}} ``` ## Info panel @@ -3226,10 +3405,15 @@ By default the docked Tools panel sits at the window's left edge, outside any pa `window.toolsBesideCanvas {on?}` (Window › Toolbars › Keep Tools Beside the Canvas, remote mode, `invoke_menu`) docks it between those panels and the canvas instead (`on: true`), back at the window's edge (`on: false`), or toggles it (`on` omitted or null), and answers the new state. Any other value of `on` is an error and changes -nothing. With the setting on, a floating Tools panel docks when it is dropped on the canvas's left edge as well as -on the window's left edge, and `window.panel.dock {panel: "tools"}` docks it beside the canvas. A floating Tools -panel stays floating when the setting changes. The setting is VectorCraft's own layout option, off by default; it is -kept with the workspace, and built-in workspaces and workspaces saved without it keep Tools at the window's edge. +nothing. A floating Tools panel dropped on the canvas's left edge, right of any panels docked on the left, docks +beside the canvas and turns the setting on; dropped on the window's left edge, it docks there and turns the setting +off. With no panels docked on the left, both edges put Tools in the same place (left of any toolbars made with +New Toolbar docked there), and a drop on either docks it where the setting puts it and leaves the setting as it +is; so does a drop in the column both edges share when left-side panels are collapsed to icons narrower than the +window's edge strip. With the setting on, `window.panel.dock {panel: "tools"}` docks it beside the canvas. A +floating Tools panel stays floating when the setting changes. The setting is VectorCraft's own layout option, off +by default; it is kept with the workspace, and built-in workspaces and workspaces saved without it keep Tools at +the window's edge. ```json {"name":"invoke_menu","arguments":{"command":"window.toolsBesideCanvas","params":{"on":true}}} @@ -3272,6 +3456,39 @@ own layout rules. {"name":"invoke_menu","arguments":{"command":"window.toolbar.dock","params":{"name":"Toolbar 1","side":"left","order":0}}} ``` +## Help search + +Help › VectorCraft Help… and F1 show the Help panel. `help.discover {query?}` opens it without +toggling it closed. A supplied string searches tools, menu commands, and VectorCraft's built-in +tutorials. Omitting `query` preserves the current search. Empty or whitespace-only text clears +the results. VectorCraft limits a query to 1024 characters and rejects a longer supplied string. + +`help.discover.search {query}` runs the same search and shows the panel. Both commands return +`{query, results: [{kind, id, label, path, shortcut}], selected}`. `kind` is `tool`, `command`, or +`tutorial`; `selected` is a zero-based result index or `null`. Search matches all the query's +words without regard to case, using translated tool labels, command labels as their menus show +them, and the English labels, ids, and menu paths. A result's `path` names the menus as they are +drawn, with plug-in submenus and Scripts folders under their own names. Outside macOS, items of +the VectorCraft application menu, which only the macOS menu bar shows, are left out. Tutorial text remains in English. After a shortcut or the interface +language changes, the kept results show the current shortcuts, labels, and menu paths, with the +query and the selected result unchanged. A command result also shows its menu item's current +label (Show Grid becomes Hide Grid), and a command that no menu lists any more, such as a removed +recent file, drops out of the results. Parameters other than an object are an error. + +`help.discover.choose {index}` shows that result. A tool result marks its toolbar location without +choosing the tool. A command result shows its menu path and current shortcut without running it. +A tutorial result shows its numbered steps; a tool link in a step marks that tool's location. +The reply is `{result, location}`, with the chosen result and the tool-location reply, tutorial +id, or command path. An invalid index returns an error and preserves the selected result. When a +tool cannot be marked because Tab or Presentation Mode hides the toolbars, the panel shows the +tool-location reply's `reason` in the status bar. + +Home clears the search. Back and `help.discover.back {}` return to its results with the query +preserved. Escape in the search field closes the panel. Escape on the canvas still cancels an +active tool operation. The panel uses the existing tool-location marks; command guidance is a +menu path. Articles, Quick Actions, personalized recommendations, and Discover preferences are +not included. + ## Learn panel Window › Learn and the Explore tutorials button beside the search field at the right end of the app bar show and hide @@ -3450,7 +3667,13 @@ already walks Image Trace. Short agent entry points: - Symbols: `symbol.list` (each row includes `registration` 0..8, `exportType`: `movieClip`|`graphic`, `type`: `static`|`dynamic` and `alignToPixelGrid`), - `symbol.new {name?, registration?, exportType?, nineSlice?, nineSliceGuides?, type?, alignToPixelGrid?, ids?}`, + `symbol.new {name?, registration?, exportType?, nineSlice?, nineSliceGuides?, type?, alignToPixelGrid?, ids?, keepArt?: false}` + (New Symbol: the selection, or `ids`, becomes the symbol's art and an instance of it in one undo step; with + `keepArt: true` the art stays ordinary art in its place, with its ids, and stays selected unless it is hidden or + locked, and the result's `id` is null; a `keepArt` other than true or false is an error; the Symbols panel sends + `keepArt: true` when its New Symbol button, with or without Alt, or its New Symbol… menu item is used with Shift + held, through Symbol Options' OK (`ui.symbolOptions {keepArt: true}`), and when art dragged off the canvas is + released on the panel with Shift held), `symbol.options {name?, newName?, registration?, exportType?, nineSlice?, nineSliceGuides?, type?, alignToPixelGrid?}` (`nineSlice` bool turns 9-slice guides on or off; `nineSliceGuides` is `[left, top, right, bottom]`, fractions of the symbol size in from each edge, each -16..16 with `left + right < 1` and `top + bottom < 1`, a quarter each when none are given; below 0 @@ -3466,9 +3689,19 @@ already walks Image Trace. Short agent entry points: art, where it is, snaps the art again after it is edited, and does not count instances in `select.object.notAlignedToPixelGrid`; `alignToPixelGrid` alone with the value the symbol already has adds no undo step), - `symbol.place {name?, x?, y?}`, `symbol.breakLink {ids?}` (the art keeps the instance's opacity mask and its bounding box, square after + `symbol.place {name?, x?, y?}`, `symbol.placeFromDocument {sourceDocument, name, x?, y?}` (an instance of a symbol + of another open document, as a symbol dragged from that document's Symbols panel onto the canvas places it: the + symbol, the symbols it nests and the resources they use are added as `edit.dropSelection` adds them, in the same + undo step, and a symbol with the same name but other art or Symbol Options is added under a free name; an error + when that document is no longer open; plug-ins cannot call it), `symbol.breakLink {ids?}` (the art keeps the instance's opacity mask and its bounding box, square after `object.resetBoundingBox`; a hidden or locked instance's art stays hidden or locked and is not selected), `symbol.replace`, + `symbol.update {name, ids?|id?, keepArt?: false}` (Redefine Symbol: the selection, or `ids`, becomes the symbol's art and an instance + of it in one undo step; with `keepArt: true` the art stays ordinary art in its place, with its ids, and stays selected + unless it is hidden or locked, and the result's `id` is null; a `keepArt` other than true or false is an error; art that holds an instance of the symbol (opacity masks included), directly or through the art + of the symbols it holds instances of, is refused and nothing changes; the Symbols panel menu's Redefine Symbol sends `keepArt: true` when it + is chosen with Shift held, and the panel sends it with the dragged art's `ids` when art dragged + off the canvas is released on a symbol's tile or row with Alt (Option on macOS) held), `symbol.edit {id?, ids?, name?, x?, y?, artboard?, viewCenter?}` (symbol editing mode: the symbol's art on a temporary isolated layer, where the instance `id` shows it or centered on (x, y), by default on the center of artboard `artboard`, the active one the app passes, or in a document without artboards on `viewCenter`, the view's center the @@ -3576,7 +3809,7 @@ already walks Image Trace. Short agent entry points: - Brushes: `brush.list`, `brush.get {name}`, `brush.apply {name, ids?}`, `brush.new {type, name?, params?, ids?}`, `brush.setCurrent {name}`, `brush.options {name, params?, newName?}`, `brush.delete {name} | {names}`, `brush.duplicate {name, newName?} | {names}`, `brush.freehand {…path.freehand params, brush?}`, - `object.expandBrush {ids?}`. `brush.freehand` draws the plain path when `brush` is left out or null. It refuses a + `object.expandBrush {ids?}`, `brush.objectOptions {ids?, params?, reset?}`. `brush.freehand` draws the plain path when `brush` is left out or null. It refuses a `brush` that is not a string with "`brush` must be a string", a name that no brush in the document has (an empty name included) with "no brush named ``", a `style` other than "pencil" or "brush", a `brush` for a path with no stroke (a continued or redrawn path without one, or a new filled "pencil" path while the stroke is None) @@ -3593,7 +3826,21 @@ already walks Image Trace. Short agent entry points: `brush.new` or `brush.options` without a `key` takes the color that the art's fills and strokes use most (on a tie, the one found first), or black when they use no solid color. `brush.options` changes only the fields of `colorization` and of an art brush's `scale` that `params` gives, so `{colorization: {method: "hueShift"}}` keeps a - Hue Shift brush's key. `brush.new` and `brush.options` take a bristle brush name of at most 31 characters: + Hue Shift brush's key. A scatter brush's `hue_jitter` (0 to 180 degrees, VectorCraft's own range; 0, the + default, leaves every copy's colors as the colorization gives them) turns the hue of each copy's solid fills and + strokes, its type's characters included, by that copy's own amount between minus and plus that many degrees. The + turn comes after the colorization: with None it turns the art's own colors, with Tints and Tints and Shades the + tints and shades of the stroke color, and with Hue Shift the shifted colors. Black, white and grays (equal RGB + values, a Gray color, CMYK without C, M or Y ink, Lab without a or b) have no hue and stay as they are, so a Tints + brush on a black or gray stroke draws its copies unturned. A color turns in its own model: RGB in the HSB of its + values, CMYK over its C, M and Y with its K kept, and Lab by turning its a and b, so its saturation and brightness + (Lab: lightness and chroma) stay. Gradients and patterns stay as they are, and a turned color loses its swatch + link. A symbol instance in the art turns only its own fill, the stain it draws its symbol's art with; the + symbol's own colors stay. The amounts depend only on the stroke's path + and the brush's name, so a stroke draws the same colors on every redraw, after Save and Open, and in export. Hue + jitter does not change where the copies go or their size and rotation. A value outside the range is clamped, as + the brush's other values are. A brush saves `hue_jitter` only when it is above 0, and a brush without the key + reads as 0; `brush.get` shows it for every scatter brush. `brush.new` and `brush.options` take a bristle brush name of at most 31 characters: `brush.new` refuses a longer one, counting the number it adds to a taken name, and `brush.options` refuses a longer `newName`. `brush.duplicate` does not check the length. A bristle brush that already has a longer name keeps it, and `brush.options` without a new name, or with a `newName` that only trims the white space around the @@ -3609,6 +3856,28 @@ already walks Image Trace. Short agent entry points: words. Corner tiles also take `autoCentered`, `autoBetween`, `autoSliced` and `autoOverlap`. A swatch choice copies its whole art and tile frame into the brush. `original` keeps the current art and clears its swatch label. `side_tile: "none"` fails with "You must choose a side pattern." An unknown swatch name also fails; neither error edits the brush or adds an Undo step. + `brush.objectOptions {ids?, params?, reset?}` (the Brushes panel menu's Options of Selected Object…, from the + [Modify brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/modify-brushes.html) + page) changes the brush settings of the selected brushed paths on those paths only; the brush and its other strokes + keep their settings. The fields a path can set are VectorCraft's own choice: calligraphic `angle` (counter-clockwise from + level), `roundness`, `size`, `variation` and `modes`; scatter `size`, `spacing`, `scatter`, `rotation` + (counter-clockwise), `modes`, + `rotation_relative_to_path` and `colorization`; art `width`, `width_mode`, `width_max`, `flip_along`, `flip_across`, + `overlap` and `colorization`; pattern `scale`, `spacing`, `fit`, `flip_along`, `flip_across` and `colorization`. + Values outside their ranges are clamped as in `brush.options`, a `colorization` object changes only the fields it + gives, a `null` item of an array (`size: [40, null]`) keeps each path's own item, else the brush's, and a setting + equal to the brush's own value is dropped. The dialog sends only the items and fields changed in it, so editing one + end of a range leaves each selected path's other end as it was. A mode that `params` does not set (no `modes`, or + a `null` item) stays the one each path draws with, so a changed calligraphic variation or scatter range does not + change it. An art `width` without a `width_max` keeps the largest width of each path whose width follows the pen, + and a calligraphic path's `modes: null` (modes that follow its values) stays when another value changes. The dialog + changes nothing when another document has become the active one. `reset: true` clears a path's settings. The command + refuses `params` together with `reset`, a selection with no brushed path, paths whose brushes are of different + types, a bristle brush and a field the type does not take. It records one undo step, and none when nothing changes. + `brush.options` edits still reach the settings a path does not set, `brush.apply`, a brush change in + `stroke.setAdvanced`, Global Edit or a `brush.freehand` extend, and removing the brush clear the path's settings, + and renaming the brush keeps them. Without + `params` or `reset` the command only returns the first path's settings. The native file saves them on the stroke as `brush_options`. - Pen tilt, bearing and barrel rotation (#764): `path.freehand` and `brush.freehand` take points as `[x, y, pressure, tiltX, tiltY, rotation]` or `{x, y, pressure?, tiltX?, tiltY?, rotation?}`, with `null` for what a point lacks, and a `pointer_gesture` event takes `tiltX`, `tiltY` and `rotation`, which the Paintbrush records. @@ -3667,7 +3936,7 @@ already walks Image Trace. Short agent entry points: - Data sets: `dataset.list`, `dataset.new {name, values?}`, `dataset.set {name, newName?, values?}` (`newName` also renames the row, in the same undo step; Edit Data Set's Name field sends it), `dataset.rename`, `dataset.delete`, `dataset.capture`, `dataset.update`, `dataset.select {name}`, `dataset.next` / - `dataset.prev` (each `dataset.select` / next / prev is one undo step over every bound object), `dataset.import {path|data|dataBase64|csv}` / + `dataset.prev` (each `dataset.select` / next / prev is one undo step over every bound object), `dataset.import {path|data|dataBase64|csv, base?}` / `dataset.export {path?}` (CSV: one column per variable, and no column of data set names). `dataset.import` also reads tab-separated files. Every header cell is a variable, whatever its case (`name` and `Name` included). The first row holds the field names, as the @@ -3675,16 +3944,33 @@ already walks Image Trace. Short agent entry points: describes. The rows replace every data set of the document and are named `Data Set 1`, `Data Set 2` and so on, in file order; the document's variables and their bindings stay, and the reply's `deletedDataSets` lists the data sets that were replaced. An import error about a row's values gives the file line the row starts on. A header cell that names no variable defines one, unbound, in the same undo step as the - rows. `#Shown` defines a visibility variable `Shown`, `@Photo` defines an image variable `Photo`, and a cell without - a prefix defines a text variable. `dataset.export` writes a visibility variable's header as `#Shown` and an image - variable's as `@Photo`, and a text or graph variable's as its name alone. Its reply's `warning` names the variables - whose header or values make an import into a document without them refuse the file (a `%` header, a `#` header - whose values aren't true or false). Otherwise it names the variables that such an import does not read back with - their kind: text variables whose names start with `#` or `@`, and graph variables. Export is refused, naming both variables, when a variable's header is - another variable's name (a visibility variable `Show` next to a text variable `#Show`). A prefixed cell whose name - is already a variable of the prefix's kind names it; - one whose name is a variable of another kind fails the import. A `%` cell that isn't a variable's exact name (graph - data files) is refused, and so are two cells that name one variable (`City` twice, or `Shown` and `#Shown`). The + rows. `#Shown` defines a visibility variable `Shown`, `@Photo` defines an image variable `Photo`, `%Sales` defines a + graph variable `Sales`, and a cell without a prefix defines a text variable. The cells of a `%` column are paths of + graph data files, as the set-up page's example shows. Each file is read as the Graph Data window's Import Data reads + one ([add graph data](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/visualize-data/add-graph-data.html)): + at most 1 MB; tab-separated when any line holds a tab, else comma-separated; the first row holds the series labels + and the first column the category labels; UTF-16 by the rule below, else UTF-8. The data becomes the data set's + graph value, which `dataset.select` applies as `graph.setData` applies it, so the graph gets the data that Import + Data and Apply give it. The files are read at import. A relative path is taken from `dataset.import`'s `base` + folder, else from the folder of the CSV file at `path`; with neither (`csv`, `data` or `dataBase64` and no `base`), + it fails the import. This is VectorCraft's own rule, and it differs from an `@` column's: an image path is kept as + the cell gives it, and a relative one is taken from the document's folder when a data set is selected. A `%` path is + followed as an image path is: a path on another computer, or on a network share other than the one `base` or the + CSV file is on, a device, and a URL other than a `file:` URL without a host fail the import with the line, the + column and the reason, and no file is read. A file that is missing, can't be read or is larger than 1 MB, a file + that gives a graph value longer than 256 KB, and `%` columns whose files and graph values hold more than 256 MB in all fail the import with + the line and the column, and the document is left as it was. Each file is read once per import, however many cells + name it, and counts once toward the 256 MB; each cell's graph value counts every time. `dataset.export` writes a + visibility variable's header as `#Shown` and an image variable's as `@Photo`, and a text or graph variable's as its + name alone. Its reply's `warning` names the variables whose header or values make an import into a document without + them refuse the file (a `%` header over values, which such an import reads as file paths, and a `#` header whose + values aren't true or false). Otherwise it names the variables that such an import does not read back with their + kind: variables whose names start with `#`, `@` or `%` and aren't of that prefix's kind, and graph variables. Export + is refused, naming both variables, when a variable's header is another variable's name (a visibility variable + `Show` next to a text variable `#Show`). A prefixed cell whose name is already a variable of the prefix's kind names + it; one whose name is a variable of another kind fails the import, and so do two cells that name one variable + (`City` twice, or `Shown` and `#Shown`). A cell that is a variable's exact name, prefix included, names that + variable, so the cells under a graph variable named `%Sales` are read as graph data in CSV form. The reply's `defined` lists the variables the import defined. While the variables are locked, an import whose header would define a variable fails with "variables are locked". A `dataset.import` file that isn't UTF-8 is read as Windows-1252, unless it starts with the UTF-8 byte-order mark. @@ -3804,6 +4090,19 @@ already walks Image Trace. Short agent entry points: than 8 MiB`. The Actions panel menu's Save Actions… and Load Actions… run these; Load Actions… is disabled where there is no open dialog (the web). `ui.actionSet.load` also reads the action sets other apps save as text (`.aia`); see "Action sets from other apps". + `ui.actionSet.replace {path? | data?}` is the Actions panel menu's Replace Actions…. It reads the file at `path`, else + a picked one, or the file's text `data`, as `ui.actionSet.load` does, with the same formats (`.vcactions` and `.aia`), + limits, errors and reports of left-out steps and unknown commands, and replaces every set in the panel, the built-in + Default Actions set included, with the file's set, which keeps its name. It returns `{changed, set: 0, name, + actions}` with `unknownCommands` and `unknownCount`, or `skipped` and `leftOut`, as a load does. The set becomes + current and selected, the panel's selected action and step and its expanded actions are cleared, and an open Set + Options, New Action, Batch or step dialog that names a set closes; when the panel already holds only a set that saves + alike, in that state, nothing changes, the set keeps its ids and `changed` is false. Omitted params count as `{}`. + Params of another type, another key, a `path` or `data` that is not a string, a file that can't be read or is + refused (an empty one too), a canceled pick (`cancelled`), or a replace while an action records or plays (also while + it waits at a stop) is an error and changes nothing. Replace records no undo step. The menu item asks no question + first, and it is disabled where there is no open dialog (the web) and while an action records or plays. These are + VectorCraft's own rules. - Actions: `ui.action.rename {set, action, name}` renames the Actions panel's action at `action` in set `set` (0 is the top set) to `name` with spaces trimmed from both ends, keeps its steps, function key and color, and returns `{name}`. An index past the last set or action, or an empty name, is an error, and then nothing is renamed. So is a @@ -3879,8 +4178,11 @@ already walks Image Trace. Short agent entry points: menu step (`ui.action.insertMenuItem`) plays at every speed in its place among the steps, as its menu item runs, and adds no undo step. At Accelerated the steps before it and the steps after it are one undoable batch each, and the result is `{results}` with every step's result in order. A step that fails ends the playback with its error: the - batch it is in changes nothing, and the steps before that batch stay done. While another action records, the View - menu step is recorded too. Batch… refuses an action with an included View menu step. + batch it is in changes nothing, and the steps before that batch stay done. At every speed, and after + `ui.action.continue`, the error names the step by its place in the action, 1 for the first step, counting excluded + steps and stops (``action step 4 (`object.align`) failed: …``). A failing step of a recorded `command.batch` is + named by the batch's place and its own command. An error about the whole batch names no step. While another action + records, the View menu step is recorded too. Batch… refuses an action with an included View menu step. - Actions: `ui.action.playAt {set, action}` plays the action at `action` in set `set` (0 is the top set) as `ui.action.play` plays it and returns what `ui.action.play` returns. A click on an action's button in Button Mode runs this. A missing index, or one that is not a whole number or is past the last set or action, is an error, and @@ -4327,7 +4629,16 @@ A graphic style holds an appearance (fills, strokes, effects) plus opacity, blen object's, type its characters'). `graphicStyle.apply {name, ids?}` gives the objects the style and links them; `add: true` adds the style on top of the existing appearance instead. Linked objects stay linked while they keep the style's look: editing their appearance or transparency breaks the link, and `graphicStyle.redefine {name?, id?}` -updates only the objects still linked. The art of a column or marker design in a graph series is never linked: +updates only the objects still linked. Art dragged off the canvas, or the Appearance panel's thumbnail, dropped on a +style in the Graphic Styles panel with Alt held runs `graphicStyle.redefine` with that style's `name` and the object's +`id` (the first object of the art); an object already linked to the style with its look changes nothing. +`graphicStyle.redefine {name, from}` gives the style `name` the look of the style `from` instead (fills, strokes, +effects, opacity, blend mode, isolate and knockout): `name` keeps its name, place and id, its objects still linked +follow in one undo step, and `from` and its objects stay as they are. `from` naming the same style, or a style with +the same look, records nothing; a `from` that names no style or is not a string, or `from` with `id`, is an error. A +style dragged onto another in the Graphic Styles panel with Alt held runs it with the dragged style as `from`; +without Alt the style moves (`graphicStyle.move`). The art of a column or marker design in a graph series is never +linked: `graphicStyle.new` can make a style from it, and `graphicStyle.redefine` leaves its look as it was and unlinks it, whether it is the source or a linked object. `graphicStyle.list` returns each style with the ids linked to it and the style of the first selected object; `select.same.graphicStyle` selects an object's fellow users. @@ -4519,20 +4830,24 @@ unique) and leaves the art as it is: the 3D and Materials panel's Add as Single `name` that is not a string or is empty, or any other key, is refused. `threeD.mapGraphic {symbol, face?, x?, y?, scale?, rotation?, index?, item?, ids?|id?}` adds a graphic to the 3D -effect of each selected object, in one undo step: `face` is `front` (default) or `back`, `x` and `y` are the +effect of each selected object, in one undo step: `face` is `front` (default), `back` or `side`, `x` and `y` are the offset in points of the graphic's center from the center of the object's bounds in the face's plane, `scale` is a percentage of the symbol's size (1..10000; omitted, 100 or less so the graphic fits inside the object) and `rotation` is in degrees counterclockwise (-360..360). Without `index` each object's first 3D effect takes it, and `item` is refused. -Every object's 3D effect must be Extrude & Bevel with Cap on (front only at a depth of 0), Rotate (the Plane type, -front only) or Revolve (front only: its swept side), and `symbol` must name a document symbol; otherwise the command is refused and nothing changes. It returns `{ids, graphic}`. -On Revolve, `x` and `y` are measured on the side unrolled flat from its middle, and a graphic that does not fit -starts scaled to fit the half of the side seen from the front ([three-d.md](three-d.md#graphics)). +Every object's 3D effect must be Extrude & Bevel (front only at a depth of 0; `front` and `back` need Cap on, and +`side`, its walls and bevels, does not), Rotate (the Plane type, front only) or Revolve (front only: its swept +side), and `symbol` must name a document symbol; otherwise the command is refused and nothing changes. It returns `{ids, graphic}`. +On Revolve and on Extrude & Bevel's side, `x` and `y` are measured on the side unrolled flat from its middle (on +Extrude & Bevel, `x` along the outline, clockwise from its top, and `y` from the front toward the back), and a +graphic that does not fit starts scaled to fit the part of Extrude & Bevel's side unrolled about `x` = 0 that does +not reach its cut, or the half of Revolve's side seen from the front ([three-d.md](three-d.md#graphics)). The graphics are the `graphics` parameter of `threeD.extrude`, `threeD.rotate` and `threeD.revolve`, which `effect.setParams` also edits: an array of up to 64 `{symbol, face, x, y, scale, rotation}` objects, drawn on the face turned, foreshortened and shaded with it and clipped to it ([Map artworks on 3D object](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/map-artwork-on-3d-objects.html)). Revolve takes graphics on its swept side and shades them with the object's light ([the archived reference, page 185](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=185)); -how a graphic wraps around the side is VectorCraft's own rule. +how a graphic wraps around the side is VectorCraft's own rule. Extrude & Bevel takes graphics on its side, its +walls and bevels unrolled as one surface; how they are unrolled is VectorCraft's own rule. A graphic naming a symbol the document does not have is refused, unless the effect already holds a graphic of it. The drawing rules are VectorCraft's own; see [three-d.md](three-d.md#graphics). @@ -4772,9 +5087,13 @@ linked moves and the Color Theme Picker leave its new color as it is, and Save A from colors alone leave its new color out. With `limitTo`, a row's `tint` (a percentage, default 100) gives the art linked to the global or spot swatch its new color is that share of its tint; `tint` must be a number. `recolor.randomize` moves a row's `tint` with its new color and removes it from a color it changes, and moves a row's `model` with its new color. `swatch.editGroup {group, colors, rename?}` rewrites a colour group in one undo -step (art linked to its global swatches follows), and `recolor.apply` with `group` recolours the art and rewrites the +step (art linked to its global swatches follows); a `null` in `colors` removes the group's swatch at that place, and +given the group's own colors in order and no new name, it records no undo step. A color key (`recolor.colors`) that +names a swatch's color, rounded to the key's steps, counts as that color, and the swatch keeps its color unrounded. And `recolor.apply` with `group` recolours the art and rewrites the group together. A `null` in `groupColors` removes the group's swatch at that place, and the swatches after it keep -their colors and names; art linked to a removed global swatch keeps its color and is no longer linked to it. Art linked to one of the group's global swatches stays linked when the swatch is rewritten with its +their colors and names; art linked to a removed global swatch keeps its color and is no longer linked to it. `"keep"` in +`groupColors` leaves the swatch at that place its color, without the Global Adjust; past the group's swatches it adds +nothing, and it is refused for a swatch that is not a color. Art linked to one of the group's global swatches stays linked when the swatch is rewritten with its row's new color (the default without `groupColors` when the rows follow the group's order), so a later `swatch.edit` still reaches it; the reply's `relinked` counts the other linked paints that took the group's new colors. Art in a row that is linked to a swatch rewritten with another color keeps its row's new color, even an unchanged one, and is no longer @@ -4840,6 +5159,35 @@ become the `weights` field, which moves the rows' current colors and previews th beside the link button runs `swatch.newGroup` right away, as its own undo step: Save All Colors saves the new colors of the rows that are not excluded and hold current colors, in row order, and Save Prominent Colors saves the bar's colors in the bar's order. +The Recolor Artwork dialog lists the document's color groups on its right, or under the tabs in a window too narrow +for both ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html)). +The Show Color Groups button beside the tabs shows or hides the list (the `groupStorage` field, true when the dialog +opens). A click on a group, or `ui.dialog.set` of the `group` field to a group's name, makes it the group being +edited: with art the art is reduced again to a row per color of the group, which become the rows' new colors, and +without art the rows are the group's colors. A name that no group has is refused with `` no colour group `` ``, +and a `group` of null selects none. The buttons under the list are the `groupAction` field. Setting it checks the value, and the next frame of the +dialog runs it (OK with it set in the same request runs it first): +`save` (Save Changes) runs `swatch.editGroup` on the selected group with the colors OK would give it and the name in +`groupName`, `new` (New Color Group) saves the new colors of the rows that are not excluded as `swatch.newGroup` does, +and `delete` (Delete) runs `swatch.delete` on the selected group. Each is its own undo step, and the art keeps its +preview. An excluded row leaves its swatch its own color, with or without art, and an excluded row past the group's +swatches adds none. When several rows list a swatch's color, the swatch follows a row that gives the color a new color +before an excluded row or one that removes the color, as `recolor.apply` maps the art. When the art has colors of the group, +`save` and OK keep the group's swatches in order: a swatch whose color a row lists, or to which an earlier `save` gave +a row's new color, takes that row's new color (its own color when the row is +excluded), so art linked to the swatch takes the color its row shows, and every other swatch keeps its color. A row whose color was removed (`to: null`) and is not excluded +removes its swatch, and the colors added on the Edit tab follow the group's other colors, as at OK. After a `save` with art, the rows' new colors take the Global +Adjust and it goes back to 0%; when the save recolored linked art, the rows are read from the art again and a row with a +color the save gave the art is excluded, also when other art has that color, since a row recolors every use of its +colors alike. Until the rows or the Global Adjust change, OK changes the saved group only by the name +in `groupName`. `save` and `delete` with no group selected answer `` missing `group` ``. `save` on a group with a +swatch that is not a color (a gradient, pattern or None swatch) is refused, because the rows hold only the group's +colors. Any other value is refused. After a Delete without art, OK saves the rows as a new color group. + +```json +{"name":"answer_dialog","arguments":{"set":[{"field":"group","value":"Brights"},{"field":"groupAction","value":"save"}]}} +``` + ```json {"name":"run_command","arguments":{"command":"recolor.weigh","params":{"map":[{"from":["rgb 255 0 0","rgb 128 0 204"],"to":"#00ff00"},{"from":["rgb 0 0 255"],"to":"#ffff00"}],"weights":[1,1]}}} ``` @@ -4974,10 +5322,18 @@ spot or process swatches and keeps their color groups. A color book (such as a P CMYK or Lab colors named with the book's prefix and suffix ("PANTONE 185 C"), as spot colors unless the book marks them as process colors; `.acb` files are read, never written. A file in the user library folder, or a file with the same extension and bytes as one there, loads as that User Defined library (category `user`). +From a document, such as a `.ai` or `.eps` swatch library, it reads the colors, tints, gradients and pattern swatches +in the document's order and color groups; `swatch.library.add` brings a pattern swatch's pattern, with its tile and +art, into the document as a pattern swatch under the library swatch's name and in its color group. A global or spot +color the pattern's art links to keeps the library's color: when the document gives its name another color, it comes +in under a numbered name ("Ink 2") and the pattern links to that. A document with +no swatches, and a `.ai`, `.eps` or PostScript file whose swatches are only the default ones, are refused with +"`` has no swatches of its own". The Swatch Libraries filter of Other Library… lists `.ai`, `.ait` and `.eps` +(`.epsf`) files as well as the library files. `swatch.library.copyToUser {library}` copies a loaded library into the user library folder of the desktop app (a library file as it is; a document's swatches or a library loaded from `data` or `dataBase64` -as `.vcswatches`) under a name no file there has, and lists it as User Defined from then on; until the app -quits, commands given its loaded id use the copy → `{library, name, count, path, copied}` (`copied: false` +as `.vcswatches`; a library with pattern swatches is refused) under a name no file there has, and lists it as User +Defined from then on; until the app quits, commands given its loaded id use the copy → `{library, name, count, path, copied}` (`copied: false` when the folder already held the same file). Without a user library folder the command is disabled. These commands refuse a parameter of the wrong form with an error that names it: `library`, `apply`, `path`, `data`, `dataBase64`, `format` and `name` must be strings, `names` must be a list of names, and `focus`, `replace` and `user` @@ -5337,7 +5693,10 @@ anchors that don't change a result's shape off it, and `removeUnpainted` makes D of objects with no fill (or only hidden fills). Both default to false; `{}` reads the options. Each Shape Mode and Pathfinder command (`object.pathfinder.unite` … `minusBack`) also takes `precision`, `removeRedundantPoints` and `removeUnpainted` for one run; the values it used join its journal entry, so a replay or an action gives the same art -whatever the options are then. +whatever the options are then. Unite, Minus Front, Intersect, Exclude and Minus Back close open paths, so a straight +line encloses no area and does not change the result's shape. When a selected object is or holds such a path, the reply's +`warning` says so and names Object › Path › Outline Stroke. When such a path leaves the result empty (Intersect, a line +at the back in Minus Front, or a line in front in Minus Back), the error says so too. ```json {"name":"run_command","arguments":{"command":"object.pathfinder.options","params":{"precision":0.1,"removeUnpainted":true}}} @@ -5416,11 +5775,15 @@ and `layerRows`, the rows highlighted in the panel. layer, group or Intertwine group (on top of its contents), keeping their stacking order; `copy` (Alt-drag) moves copies. Layers go only in layers or at the top level and objects in layers, groups and Intertwine groups (see Intertwine for the members an Intertwine group takes; an object placed beside a top-level layer goes - inside it); a row never goes into itself or a row inside it, and a locked layer or group takes nothing. Dragging the + inside it); a row never goes into itself or a row inside it, and a locked layer or group takes nothing. With `copy`, + the target may be one of the rows copied: the copies go above or below it, as an Alt-drag onto a row's own row (or a + bottom layer's into the empty space under the list) places them, unless objects are copied with a top-level layer + that is the target, which would put them inside it (#8237). Dragging the selected-art square is `layer.move` with the selected objects. `node.move {id, parent?, index}` is the low-level form with the same nesting rules; unlike `layer.move`, it also moves a row into a locked layer or group. -- **Buttons**: `layer.new {name?, top?, below?, …options}` (above the current layer at its level; `top` with - Ctrl/Cmd; `below`, directly below the current layer at its level, with Ctrl/Cmd+Alt), +- **Buttons**: `layer.new {name?, top?, below?, …options}` (above the current layer at its level, or directly + below it in Draw Behind; `top` with Ctrl/Cmd; `below`, directly below the current layer at its level, with + Ctrl/Cmd+Alt; `top` and `below` apply in every drawing mode), `layer.newSublayer {parent?, bottom?, name?, …options}` (on top of the parent's contents; `bottom`, under them but above a clipping layer's clipping path, with Ctrl/Cmd+Alt; both refused while an opacity mask is edited), `layer.delete {ids?}` (rows with what they hold; the @@ -5429,7 +5792,9 @@ and `layerRows`, the rows highlighted in the panel. locked or nested art included, dialog `confirm` asks "Delete this layer and its artwork?" for one layer, else "Delete the selected items and their artwork?"; OK deletes the rows it asked about in that document, one undo step, and Cancel keeps them; an empty layer, a layer with only guides, and groups or objects alone are deleted at once), - `layer.locate {id?}` (highlights the selected object's row; the panel opens the rows around it) + `layer.locate {id?, layersOnly?}` (highlights the selected object's row; the panel opens the rows around it and + scrolls to it on every call, also when the row was already highlighted; `layersOnly: true`, which the panel sends while Show Layers Only is on, as Locate Layer, highlights the innermost + layer or sublayer holding the object instead, or a layer `id` itself, and returns `{id, objectId, ancestry}`) and `layer.clippingMask.toggle`. - **Panel menu**: `layer.duplicate {ids?}`, `layer.merge {ids?}` (into the layer highlighted last, keeping the stacking order), `layer.flatten {id?}` (every other visible layer's art into one layer; hidden layers are deleted, @@ -5441,7 +5806,16 @@ and `layerRows`, the rows highlighted in the panel. runs Hide or Lock Others for the row's layer, or Show or Unlock All when the others already are), `layer.pasteRemembersLayers`, `object.isolate {id?}` (a group, a layer or a single object, by default the first selected object; not type, not a hidden or locked object or one in a hidden or locked group or layer, not a guide path while Lock Guides is on, and - while a symbol is edited only the editing layer or art on it) / `object.exitIsolation`. Leaving an isolated Live + while a symbol is edited only the editing layer or art on it) / `object.exitIsolation {all?}`. With a sublayer + isolated, `object.exitIsolation` isolates its parent layer and selects the sublayer, so repeated calls go up one + layer at a time until the top-level layer is left, as the + [help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/isolate-objects.html) + describes for Exit Isolation Mode; the Layers panel menu item, the isolation bar's back arrow, the Control bar + button, the canvas context menu and a double-click outside the art run it this way. As VectorCraft's own rules, a + step up records no undo step, a hidden or locked parent layer is not isolated (the call leaves isolation mode), and + `all: true` (Esc, the top-level layer's crumb on the isolation bar) leaves isolation mode from a sublayer at any + depth; `all` must be true or false. While a symbol is edited, a group isolated in its art still goes back to the + symbol's layer first, with or without `all`. A sublayer's crumb on the isolation bar isolates that sublayer. Leaving an isolated Live Paint group (`object.exitIsolation`, or `object.isolate` on a level outside it) adds the paths, compound paths and groups of them drawn in it, shown and unlocked with everything in them, to the group as `livePaint.merge` does, in one undo step; type, images and other objects stay in it as they are, and with nothing drawn no undo step is @@ -5754,6 +6128,17 @@ link, the dimension stays where it was, no longer linked (see [dimensions.md](di `object.expand` rejects a param of the wrong type, such as `"fill": "yes"`, `"gradient": 3` or `"steps": "16"`, and changes nothing. Omitting a param or giving null keeps its default. +`ui.expandDialog {immediate?}` opens the Expand dialog (`object.expand` with no params opens it too). The dialog opens on +the Object, Fill, Stroke, Expand Gradient To and steps choices that OK last expanded with since the app started, and on +the defaults before that; Cancel and an OK that fails leave the kept choices as they were, and they are not kept across +launches. Choosing Object → Expand… in the in-window menu bar with Alt (Option on macOS) held sends `immediate: true`, which expands the selection +at once with those choices, or the defaults before any OK, in one undo step, as OK in the dialog would +([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/expand-objects.html) +describes this shortcut for a gradient; VectorCraft applies it to whatever the choices expand). When none of the kept +choices has something to expand in the selection, `immediate: true` opens the dialog on them instead and changes +nothing. A selection with appearance attributes refuses both, as the dimmed menu item does. An `immediate` of null is +treated as omitted, and any other value that is not true or false is an error. + ```json {"name":"run_command","arguments":{"command":"object.expand","params":{"stroke":false,"gradient":"mesh"}}} {"name":"run_command","arguments":{"command":"object.expand","params":{"steps":16}}} @@ -6039,7 +6424,7 @@ The command refuses another mode, and a variation below 0 or past its range, and the Eraser's tip outline at the pointer takes the angle, roundness and size the pen gives while it erases, and the outline of the area a drag covers takes, at each step, the tip the pen's readings give halfway along it. A Random value shows as the value itself there, since the release draws it. -`tool.setOption {tool: "eraser"}` takes the same keys. +`tool.setOption {tool: "eraser"}` takes the same keys, with `sizeVariation` from 0 to 1000. `path.eraseRegion {rect: [x, y, width, height]}` takes a rectangle in place of `points` and erases everything inside it from the paths (selected, or all), as an Alt-drag with the Eraser does ([Eraser tool @@ -6073,6 +6458,10 @@ with `` `t` must be from 0 to 1 ``, with `segment` or with `anchor`. The documen recorded. Left out or null, `angle` is 0° and `roundness` is 100%; left out, `t` is 0.5. The Eraser's ranges are VectorCraft's own values. +`path.eraseSegments` (the Path Eraser) refuses a `width` outside 0.001 to 1000 pt with +`` `width` must be from 0.001 to 1000 ``. The document and the selection do not change and no undo step is recorded. +Left out or null, `width` is 8 pt. The range is VectorCraft's own value. + These commands refuse a string, a number or another value that is not true or false with `` `closed` must be true or false ``, naming the key; the document does not change and no undo step is recorded: `independent` in `path.close` and `path.setHandle`; `patterns` in `path.moveAnchors`; `closed`, `keepSelected` and @@ -6083,13 +6472,25 @@ in `path.curvatureEdit`; `perpendicular` in `path.reshapeSegment`; and `keepSele `path.freehand` (and `brush.freehand`, which runs it) refuses a `style` other than "pencil" or "brush" with `style must be "pencil" or "brush"`, and an `end` of `extend` other than "start" or "end" with `extend end must be "start" or "end"`; the document does not change and no undo step is recorded. Left out or null, -`style` is "pencil" and the `end` of `extend` is "end". +`style` is "pencil" and the `end` of `extend` is "end". It refuses a `connect` without `extend` with +`connect needs extend`, and checks a `connect` given with `extend` (its `id`, a path other than the one extended with +an open end, and an `end` of "start" or "end") before a stroke of one point returns, so a bad `connect` is refused +there too and a `brush.freehand` call does not change the path's brush or the selection. A `pointer_gesture` with `mods: {cmd: true}` held at the press, with any tool but the selection tools (Command on macOS, Ctrl elsewhere), drags with the selection tool chosen last (`select_tool`), or Direct Selection with the Pen, Curvature and anchor tools until one is chosen; the release gives the tool back as it was, so the Pen goes on drawing the path it had begun while that stays selected. Its reply's `tool` is the tool given back. +`tool.selectLastSelection` (Select Last Selection Tool, `{}`) chooses the selection tool chosen last, as Ctrl+` does on +Windows and Linux ([the help page](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) lists the +shortcut among those for selections). Only Selection, Direct Selection and Group Selection count: choosing Magic Wand, +Lasso or any other tool leaves the remembered one as it was. Before any of the three is chosen it chooses the Selection +tool; with the remembered tool already active it keeps it, so running it again does not cycle. It returns `{tool}` and +adds no undo step. On macOS it has no default shortcut, because the system uses Command+` to switch between an app's +windows; Edit › Keyboard Shortcuts can assign one. The Selection tool as the first choice and the macOS default are +VectorCraft's own rules. The headless backend and `vectorcraft-cli run` run it too. + ```json {"name":"pointer_gesture","arguments":{"tool":"pen","events":[{"kind":"down","x":100,"y":300},{"kind":"up","x":100,"y":300},{"kind":"down","x":200,"y":300},{"kind":"drag","x":250,"y":300},{"kind":"up","x":250,"y":300}]}} {"name":"pointer_gesture","arguments":{"mods":{"cmd":true},"events":[{"kind":"down","x":250,"y":300},{"kind":"drag","x":250,"y":260},{"kind":"up","x":250,"y":260}]}} @@ -6176,17 +6577,32 @@ slider (`ui.menuDialog {command: "object.path.smooth"}`, dialog `smoothSlider` w Auto-Smooth level, and the slider previews the result until `ui.dialog.confirm`; `ui.smoothAuto` moves the open slider back to the Auto-Smooth level. -## Circle through three points +## Circle through two or three points -`shape.circleThroughPoints {points?: [[x, y], [x, y], [x, y]]}` draws the circle whose edge passes through three -points, as a live ellipse with the current paint, and selects it. Without `points`, it uses the three selected anchor -points, from one path or several: anchor points selected with Direct Selection, or all the anchor points of a path -selected whole, such as a triangle. The ends of selected segments do not count. The result is `{id, cx, cy, radius}`, -and one undo removes the circle. The circle is not pixel-aligned, even while the document's -[Align New Objects to Pixel Grid](#align-new-objects-to-pixel-grid) is on, so it stays through the points. The command -returns an error and draws nothing when two points are the same or the three lie on one line (twice the triangle's area -at most 10⁻¹⁰ of its longest side squared), when `points` is not three pairs of numbers, and when `points` is left out -and the selection does not hold exactly three anchor points of paths. +`shape.circleThroughPoints {points?: [[x, y], [x, y]] or [[x, y], [x, y], [x, y]]}` draws the circle whose edge passes +through the points, as a live ellipse with the current paint, and selects it. Two points are the ends of a diameter. +Without `points`, it uses the two or three selected anchor points, from one path or several: anchor points selected with +Direct Selection, or all the anchor points of a path selected whole, such as a triangle. The ends of selected segments +do not count. The result is `{id, cx, cy, radius}`, and one undo removes the circle. The circle is not pixel-aligned, +even while the document's [Align New Objects to Pixel Grid](#align-new-objects-to-pixel-grid) is on, so it stays +through the points. The command returns an error and draws nothing when two points are the same or the three lie on +one line (twice the triangle's area at most 10⁻¹⁰ of its longest side squared), when the circle would reach past the +canvas (4,000,000 pt from the origin), when `points` is not two or three pairs of numbers, and when `points` is left +out and the selection does not hold two or three anchor points of paths. + +The Circle tool, after the Ellipse tool in its toolbar group, draws with this command. A drag from one point to +another, or a click on each, draws the circle with the two points as the ends of a diameter. A click on a first point, +then a press on a second point dragged to a third, draws the circle through the three. Shift keeps the second point at +45° steps from the first, measured from General › Constrain Angle. For a circle on two points, Alt rounds the diameter +to the nearest tick of the rulers at the current zoom, in the General unit (every 5 pt at 100% in points); the three +points of a circle through three are not rounded. Each point snaps to Smart Guides. Until +the release, the tool shows the circle as a dashed outline (solid once it is more than 50,000 screen points around) +with its points, a small cross at its center, a line from +the center to each point and, with Measurement Labels on, the diameter by the pointer. Three different points on one +line, or a circle past the canvas, show "Circle too large" by the pointer instead, and the release draws nothing. +Escape, a dropped press, and an edit, Undo or Redo made outside the tool drop the first point. A second press within 3 +screen points of the first point, or one that snaps to it, is a press on it: let go there (a double-click), it places no second point, and +dragged out, it draws the circle on the diameter it drags out. With the Ellipse tool, the first two Shift-clicks place points, and the third draws the circle through the three with this command. After two points the tool previews the circle through them and the pointer as a dashed outline. Once a @@ -6279,13 +6695,18 @@ The destination is any profile `edit.colorSettings` lists (default: the document for its colour mode). `profiles` (`all`, `destination`, or `taggedSource` for a document assigned profiles with `edit.assignProfile`) writes colours in ICC-based spaces with their profiles embedded: CMYK with the destination's or the document's CMYK profile, RGB as sRGB, grey with the sRGB tone curve (PDF/A, PDF/X-3 and PDF/X-4 files are -always tagged, whatever `profiles` says). A CMYK image that keeps its numbers carries the CMYK profile it embeds -with `all` and `taggedSource`, and in PDF/A, PDF/X-3 and PDF/X-4 unless `profiles` is `destination`; PDF/X-1a +always tagged, whatever `profiles` says). In PDF/X-3 and PDF/X-4 files, CMYK colors whose profile is the profile of a +CMYK output intent are written as DeviceCMYK, and the profile is embedded once, as the output intent's. With `none` and a CMYK output intent, PDF/X-3 and PDF/X-4 files write every CMYK color as DeviceCMYK +(unless colors are converted to a CMYK `destination` of another profile, which then tags them), and RGB and gray +colors stay tagged. A CMYK image that keeps its numbers carries the CMYK profile it embeds +with `all` and `taggedSource`, and in PDF/A, PDF/X-3 and PDF/X-4 unless `profiles` is `destination`, but not when +CMYK colors are DeviceCMYK and either its profile is the output intent's or `profiles` is `none` (a CMYK JPEG +then loses its `ICC_PROFILE` segments); PDF/X-1a images are always untagged CMYK. Left unset (the default; `"default"` unsets it over a preset, while `null` keeps the preset's value), `profiles` writes device colours and gray and RGB images keep the profiles they carry (not in PDF/X-1a). Set to `none`, it also writes every image without the profile it carries, and a JPEG kept as it is without its `ICC_PROFILE` segments, its other segments and compressed samples unchanged; PDF/A, PDF/X-3 and PDF/X-4 files keep -the profiles they tag images with. The Save PDF dialog lists the unset value as Default. `outputIntent` embeds a profile as the file's +the profiles they tag images with, except CMYK images when CMYK colors are DeviceCMYK. The Save PDF dialog lists the unset value as Default. `outputIntent` embeds a profile as the file's `/GTS_PDFX` output intent with `outputCondition`, `outputConditionId` and `registry`, and `trapped` sets `/Trapped` (PDF/A files keep their own output intent). Type is written as selectable, searchable text in embedded subset fonts with a ToUnicode map (fonts whose licence forbids embedding stay outlines, with a warning); `advanced: {outlineText: @@ -6347,6 +6768,22 @@ and Shift steps follow the box the same way; a Reflect axis drawn with the tool {"name":"run_command","arguments":{"command":"object.reflect","params":{"axis":"vertical","basis":"page"}}} ``` +## Shear along an angled axis + +`object.shear` takes `axis` as `"horizontal"`, `"vertical"` or a number of degrees from -359 to 359. A number is a +line on the page at that angle, counter-clockwise from horizontal, as `object.reflect`'s numeric `axis` is, and the art +slides along that line about `origin` by the shear `angle`, which stays a separate value. 0 shears as `"horizontal"` +and 90 as `"vertical"`. A numeric `axis` outside the range, a number given as a string, or any other value is an +error, and nothing changes. The shear `angle` runs from -359 to 359 along every axis and is sheared by its tangent; +±90 and ±270 are an error. The Shear dialog's Axis has Horizontal, Vertical and Angle; the Axis Angle field beside it +starts at 0° and takes input while Angle is chosen. The [help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/shear-objects.html) +describes the Angle axis as a custom slant direction between -359° and 359°, measured from the horizontal. The +counter-clockwise direction on the page and the 0° starting value are VectorCraft's own. + +```json +{"name":"run_command","arguments":{"command":"object.shear","params":{"angle":30,"axis":45}}} +``` + ## Free Distort on a turned bounding box `object.distort` maps the corners of `from` (TL, TR, BR, BL) onto `corners`, which are page coordinates. With @@ -6487,7 +6924,15 @@ polygon (Polygon Properties): `sides` (3–1000), `polygonAngle` (degrees counte at 0), `polygonRadius` (pt, centre to vertex), `sideLength` (pt, which sets the radius) and `makeSidesEqual: true`, which drops an uneven scale or shear (its sides then differ) and keeps its centre, angle and mean radius; a radius or length that isn't a number above 0 is an error. An ellipse (Ellipse Properties): `pieStart` and `pieEnd` (degrees -counterclockwise from 3 o'clock; 0 to 360 is the whole ellipse) and `invertPie: true`, which swaps them. Each call is +counterclockwise from 3 o'clock; 0 to 360 is the whole ellipse) and `invertPie: true`, which swaps them. +`constrainPie: true` with one of `pieStart` and `pieEnd` (the panels' Constrain Pie Angle link) moves the other angle +by as much, so each selected ellipse keeps its own span, counterclockwise from its start to its end; a whole ellipse +stays whole. `constrainPie: true` with both angles, with neither, or with `invertPie: true` is a parameter error. A +line drawn with the Line Segment tool (Line Properties): `lineLength` (pt, above 0; the line's first end stays in place) and +`lineAngle` (degrees counterclockwise from 3 o'clock, from the first end to the second; the line turns about its +midpoint; any finite value is brought into 0 to 360). With both, the length applies first. A line whose ends meet reads +0° and keeps its place under `lineAngle`; `lineLength` points it to the right. A length that isn't a number above 0, +and a line that would reach past the coordinate limit (±4,000,000 pt), are errors that change no line. Each call is one undo step. `object.setLiveShape` returns a parameter error, and leaves the document and its undo history as they were, for a key @@ -6500,6 +6945,8 @@ below 3 or above 1000 counts as 3 or 1000, and a fractional or negative `sides` ```json {"name":"run_command","arguments":{"command":"object.setLiveShape","params":{"sides":8,"polygonAngle":22.5,"sideLength":40}}} {"name":"run_command","arguments":{"command":"object.setLiveShape","params":{"makeSidesEqual":true}}} +{"name":"run_command","arguments":{"command":"object.setLiveShape","params":{"pieStart":350,"constrainPie":true}}} +{"name":"run_command","arguments":{"command":"object.setLiveShape","params":{"lineLength":72,"lineAngle":90}}} ``` ## Align to Artboard @@ -6756,8 +7203,14 @@ A null is read as a key left out. When a step fails on a file or data set, that place in the `commands` sent, from 1, counting the Open steps the batch skips: with `commands` of an Open, an Unlock All and an Align, a failed Align gives `` action step 3 (`object.align`) failed: `` and the reason. The batch's own opening of a source file, choosing of a data set and destination save, export or close give their errors without a -step number. This numbering is VectorCraft's own rule. A `prefs.import` step is refused before any file is opened, -with `` commands[1]: `prefs.import` runs on its own, not as a batch step `` (counted from 0, as for an unknown command). An action recorded in the Actions panel leaves the artboard out, +step number. This numbering is VectorCraft's own rule. Before any file is opened, `action.batch` refuses a step +without a command, with a command the engine does not have, with params its command refuses, or with +`command.batch`, `action.batch` (batches cannot nest) or `prefs.import`, and names it the same way, from 1: with +`commands` of an Unlock All and a `prefs.import`, the error is +``invalid parameters for `action.batch`: action step 2 (`prefs.import`) failed: `prefs.import` runs on its own, not as a batch step``. +Override Open skips `document.open` steps, and Override Save points `document.save` and `file.saveAs` steps at the +destination folder. `file.open` and `file.save` are the app's commands, not the engine's, so a step with one is +refused as an unknown command. An action recorded in the Actions panel leaves the artboard out, and its steps of these commands get the artboard that is active when the action plays. A press with the Selection, Direct Selection or Group Selection tool inside an artboard makes that artboard the active one; with the Selection tool, a Shift-click on an empty spot inside an artboard makes it active and keeps the selection. Choosing the Artboard @@ -6841,8 +7294,13 @@ wide. `object.align` needs `horizontal` or `vertical`. The three Align commands, `object.reflect` and `object.shear` return an error that lists the choices of a `horizontal`, `vertical`, `to`, `axis` or `bounds` param given another value -(`object.reflect` also takes an angle and names the value given), and one for a `spacing` that is not a number; nothing -moves. +(`object.reflect` and `object.shear` also take a numeric `axis` and name the value given; `object.shear`'s numeric +`axis` runs from -359 to 359), and one for a `spacing` that is not a number; nothing moves. `object.shear` takes an `angle` from -359 to 359 degrees, the range of the +[Shear dialog](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/shear-objects.html), +and shears by its tangent, so 120 slants as -60. An angle of 0 or ±180 (within 1e-9 degrees) has no slant: without +`copy`, nothing moves and no undo step is recorded, and with `copy` the copies keep the art's place. It returns an error for an angle outside that range, and, as +VectorCraft's own rule, for ±90 and ±270 (within 1e-9 degrees), which have no finite shear; nothing moves and no undo +step is recorded. ## Glyph bounds for type @@ -6901,6 +7359,22 @@ The Selection & Anchor Display and General preferences apply to `pointer_gesture - `showHandlesMultipleAnchors` (on by default): off, Direct Selection (and the Anchor Point tool, and the Pen with Alt) shows and drags direction handles only while a single anchor is selected. On, the handles of the direct-selected anchors, or of every anchor of a path selected as a whole, show and drag. `handleStyle` (`solid`, `hollow`, `large`) draws their ends (desktop app). +- `interpolateControlPoints` (General › Interpolate Control Points When Moving Anchors, off by default): the default of + the `interpolate` param of `path.moveAnchors` (a Direct Selection drag), `object.nudge` (the arrow keys), + `object.move`, `object.transform` and `object.transformAgain`. It applies when they move direct-selected anchors + without turning or scaling them. `object.setBounds` (only `x` or `y` changed) and `guide.move` (with art selected + too) take the same param and follow the preference when they move direct-selected anchors. + On, both handles of each segment with one moved end are re-mapped by the turn, uniform scale and move that take the + segment's old ends to its new ends, so a segment between two corner anchors keeps its shape relative to its ends. A + segment with both ends moved, or with its ends at the same place before or after the move, moves as it does with the + preference off. A smooth anchor keeps its handles in line: its re-mapped handle takes the new length and stays in + line with the other handle, and when both of its handles were re-mapped they point along the mean of their + directions. When the two point the same way, both move with the anchor as with the preference off. A retracted + handle stays retracted. The value used joins the command's journal entry and Transform Again's options; a saved step + without `interpolate` (an action or journal entry recorded before it) moves the handles as with the preference off, + as it did when it was recorded. Align and + Distribute, and the anchors of type paths and area type frames (`text.reshapePath`, `text.reshapeArea`), move as + before. Off, the handles of a moved anchor move with it and the other handles stay where they are. - `hideCornerWidgetAbove` (177° by default): corners wider than this show no Live Corners widget (a rectangle's right angles hide below 90°). - `transformPatternTiles` (off by default): the default of the transforms' `patterns` param (`object.transform`, @@ -6966,13 +7440,25 @@ output's `_ICC_PROFILE` property when colord has no usable profile, then the scr Color on (HDR or Automatic Color Management) and macOS windows are converted by the system, and nothing is converted again. In a Wayland session, and where no profile is set or the profile is not an RGB display profile of at most 1 MiB, the canvas stays sRGB. The app reads the display again every 10 seconds and when the window moves to another display. +Edit › Refresh Monitor Profile (`view.refreshMonitorProfile`, `{}`; a desktop UI command) reads it again on the next +frame without waiting for either interval, for example after a new profile is installed for the display; a request +made while a reading runs starts when that reading ends. It returns `{requested: true}` before the profile is read, +and is an error while `monitorProfileDisplay` is off (nothing is queued) and where nothing reads the display's profile +(the web build). It changes no document, proof setting or preference and records no undo step; reading the same +profile again leaves the canvas as it is. Exports, `ui.render`, the document, panels and thumbnails are not converted; with Proof Colors on, the proof is drawn first and then converted. Translucent art and the antialiased edges of art over an artboard's paper or the transparency grid are blended with it in sRGB, and the blend is converted; over the pasteboard and in Outline the art is converted on its own. `ui.inspect` returns `displayProfile`: `{enabled, display, source, profile, from, applied, reason, -osManaged}`, where `source` is `profile`, `srgbProfile` (a profile that shows sRGB unchanged), `system`, `none`, -`pending` or `unsupported`, `applied` says whether the canvas is converted, and `reason` says why not. +osManaged, readRequested}`, where `source` is `profile`, `srgbProfile` (a profile that shows sRGB unchanged), `system`, `none`, +`pending` or `unsupported`, `applied` says whether the canvas is converted, `reason` says why not, and `readRequested` +says whether a reading Refresh Monitor Profile asked for has not started yet. + +`lowLatencyDrawing` (Preferences › Performance › Low-Latency Drawing, off by default; desktop app) is read when the app +starts. On, the window presents without vsync (wgpu's `AutoNoVsync`) and frames start at most 240 times a second. +`--present-mode` and `VECTORCRAFT_PRESENT_MODE` take precedence over it (see `docs/development.md` › Desktop graphics +processor). A value that is not a boolean is an error. `ctrlWheelScrollsSideways` (on by default): on, Cmd/Ctrl with a mouse wheel's whole notches scrolls the canvas sideways instead of zooming while `zoomWithMouseWheel` is off; off, Cmd/Ctrl-wheel zooms about the pointer. Alt + Cmd/Ctrl-wheel @@ -7051,8 +7537,8 @@ Guides change where a snapped point lands: - `anchorPathLabels` (on by default): off, no "anchor", "center", "path" or "align" label. - `measurementLabels` (on by default): off, no size or offset readout while drawing, moving (Free Transform's move too), dragging a ruler guide, drawing and resizing an artboard, or moving and resizing a slice. -- `transformToolsGuides` (on by default): off, no readout while scaling or rotating with the Selection tool, the - Free Transform tool or the Rotate, Scale, Shear and Reflect tools. +- `transformToolsGuides` (on by default): off, no readout while scaling, rotating or shearing with the Selection + tool, the Free Transform tool or the Rotate, Scale, Shear and Reflect tools. - `objectHighlighting` (on by default; desktop app): off, the Selection tools no longer outline the object under the pointer. The outline also needs View › Smart Guides on. - `snappingTolerance` (0–40 px, 4 by default): how near an anchor, edge, centre or artboard edge pulls a drawn point, @@ -7177,7 +7663,10 @@ Guides off, this drag leaves a 70 × 50 and a 90 × 50 copy and the 110 × 70 re `type.highlightTracking` (no default key) and `type.highlightFontName` (Cmd+Alt+Shift+F) show the Character panel and give its Kerning or Tracking field the keyboard focus with the value selected, or open its font family menu with the search field focused; each replies `{field: "kerning" | "tracking" | "fontName"}`. Without selected type or text the - Type tool edits, the panel shows and the command fails. + Type tool edits, the panel shows and the command fails. Type › Size › Other… runs `type.highlightFontSize` (`{}`, no + default key), which gives the Character panel's Font Size field the keyboard focus the same way (blank when the + selected sizes differ; the size typed and Enter apply through `text.setStyle {size}` as one undo step) and replies + `{field: "fontSize"}`; the menu item is dimmed without selected type or text the Type tool edits. The UI command `type.underline` (Cmd+Shift+U, in remote mode `press_key {key: "U", mods: {cmd: true, shift: true}}` or `invoke_menu`) does what the Character panel's Underline button does: it underlines the Type tool's selected text or the selected type objects, or removes @@ -7235,6 +7724,14 @@ writes over it. with `index`, edits or moves one; `adjustAdjoining` changes the nearest points either side in proportion. Moving a point onto another one's `t` (or `stroke.widthPoint.copy {id, index, t}` landing there) makes a discontinuous point: two points at the same `t` (the width before it, then after it), and the stroke's width steps there. +`stroke.widthPoint.set {id, t, index, left, right, outIndex, outLeft, outRight, single?, adjustAdjoining?}` sets both +halves of one in one undo step: `index` is the incoming half, `outIndex` the outgoing half after it, and `t` must be +their place. With `adjustAdjoining`, the nearest point before changes with the incoming half and the nearest point +after with the outgoing half. `single: "incoming"` or `"outgoing"` keeps only that half's widths, leaving one +continuous point. Indices that are not the two halves of one discontinuous point (three or more points at one `t` +included), another `t`, or another `single` value are errors that leave the document and its undo history unchanged. +Width Point Edit on either half shows both halves as Incoming and Outgoing, with Single Width Only, and its Delete +removes both. `document.inspect` reports a path's `strokeOptions.widthPoints` (`[t, left, right]`, factors of half the weight; null for a uniform stroke). `stroke.widthPoint.remove {id, index | indices}` deletes points; `stroke.widthProfile.set {ids, points}` replaces them all, as dragging several Shift-selected points with the Width tool does in one undo step. @@ -7385,6 +7882,9 @@ small caps size (1 to 200%) lies outside those ranges opens with the nearer end `document.setup` does not take the color mode or the assigned profiles. The Document Setup dialog's Color tab sets them with `edit.assignProfile` and `file.documentColorMode`: its OK runs `document.setup`, then `edit.assignProfile`, then `file.documentColorMode` in one `command.batch`, and the document's changes are one undo step. +On the dialog's Transparency tab, a click on either grid color's box (or Enter or Space with the keyboard on it) opens +the `colorPicker` dialog over Document Setup on that color. Its OK sets only that entry of the dialog's `gridColors` +and goes back to Document Setup, whose OK runs `document.setup`; its Cancel goes back with `gridColors` unchanged. ```json {"name":"run_command","arguments":{"command":"document.setup","params":{"gridColors":"Blue","gridSize":"large","language":"German","bleed":9}}} @@ -7426,15 +7926,22 @@ document current, and its tool keeps its state; closing the current document mak current, or the one before it when it was the last tab. In the desktop app a modified document comes to the front first, to ask whether to save it. `window.arrange.tile` (Window › Arrange › Tile) shows every open document in its own pane, edge to edge in the document -area, in a grid of as many columns as the square root of the number of documents, rounded up, and fits each document to -its pane; with fewer than two documents open it leaves the view and `tiled` as they are. It returns `{tiled, panes}`. -The current document's pane is the canvas, and a press in another pane makes its document the current one. -`window.arrange.consolidateAllWindows` (Window › Arrange › Consolidate All Windows) shows one document under its tab -again and returns `{tiled: false}`. The arrangement is not saved. `ui.inspect` reports `tiled` and `panes` (each pane's -`document` index, `rect` and whether it is `active`); canvas coordinates map to the current document's pane -(`canvasRect`). -its pane; it returns `{tiled, panes}`. The current document's pane is the canvas, and a press in another pane makes its -document the current one. `window.arrange.floatInWindow` (Window › Arrange › Float in Window) moves the current document +area, in a grid of as many columns as the square root of the number of windows, rounded up, and fits each document to +its pane. Each view of a document counts as a window (see `window.newWindow` below). With fewer than two windows open it +leaves the view, `tiled` and the layout as they are. It returns +`{tiled, panes, layout}`. `window.arrange.tile {layout}` picks another layout, as the other Tile items of Window › +Arrange and of the application bar's Arrange Documents button do: `grid` (the default), `vertical` (Tile All +Vertically: side by side in one row), `horizontal` (Tile All Horizontally: stacked in one column), and `2up`, `3up`, +`4up` and `6up`, which show at most that many windows (2-Up and 3-Up side by side, 4-Up two by two, 6-Up three by +two) and leave the others under their tabs. Those layouts show the first windows in tab order, and the current +window takes the last pane when it is not among them, so a click on another tab brings that window into the last +pane. Any other `layout` is an error, and the view stays as it is. The set of layouts and how each one places the panes +are VectorCraft's own. The current document's pane is the canvas, and a press in another pane makes its document the +current one. `window.arrange.consolidateAllWindows` (Window › Arrange › Consolidate All Windows, also first in Arrange +Documents) shows one document under its tab again and returns `{tiled: false}`. The arrangement is not saved. +`ui.inspect` reports `tiled`, `tileLayout` and `panes` (each pane's `document` index, `rect` and whether it is +`active`); canvas coordinates map to the current document's pane (`canvasRect`). +`window.arrange.floatInWindow` (Window › Arrange › Float in Window) moves the current document out of the tab strip into a floating window of its own, `window.arrange.floatAllInWindows` (Float All in Windows) does so for every tabbed document, and `window.arrange.cascade` (Cascade) floats every document and stacks the windows 30 pt apart from the upper left of the document area; each returns `{floating}`, the floating documents' indices. On the @@ -7512,10 +8019,25 @@ starts with one empty layer. The grid comes from Preferences › Guides & Grid, preset's color mode differs from the profile's, the profile's colors are converted as `file.documentColorMode` converts them. +A profile also sets the default fill and stroke of its documents (VectorCraft's own rule). When the profile's Default +Graphic Style differs from the shipped one (white fill, 1 pt black stroke, with the shipped colors converted to the +document's color mode), `file.new` resets new art to that style's fills, strokes and effects, at full opacity and not +linked to the style, and `paint.default` (Default Fill and Stroke) gives the defaults and the selected art the same +look; type still gets a black fill and no stroke. With the shipped style, `file.new` leaves the fill and stroke as they +were. For example, to start with no fill and a 0.25 pt red stroke: edit the profile with `file.newProfiles.edit`, draw a +path with that fill and stroke, select it, run `graphicStyle.redefine {name: "Default Graphic Style"}`, delete the +path and save. + A built-in preset names its category's profile in `file.newPresets` (`profile`). Saved and Recent presets keep the profile of the preset they were made from. `file.new {profile: "Print"}` picks a profile for any settings, and `profile: null` starts with the defaults. A document made without a preset starts with the defaults. +A profile also sets the default font of its documents: new type starts in [Normal Character Style], so when the profile +redefines that style (`charStyle.setAttrs {name: "[Normal Character Style]", attrs: {font_family, font_style, size}}` in +the document `file.newProfiles.edit` opens, then save), type made in the profile's documents takes its font, style, size +and fill. A `font`, `style`, `size` or `color` given to `text.create` still wins +([Change the default font](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/change-the-default-font-in-illustrator.html)). + The profiles are `.vectorcraft` files named after their category in the `New Document Profiles` folder next to the preferences (VectorCraft's own place and form). A category without a file has the shipped profile, which holds the defaults. Runs without preferences (`VECTORCRAFT_NO_PREFS`) and the web build have no folder, so every document starts @@ -8221,10 +8743,15 @@ the document; so does `object.expand`. ``` Placing a text file (`.txt`) sets it as area type: `file.place {path | name+dataBase64, text?: {characterSet?: -"unicode" | "ansi", platform?: "windows" | "mac", removeLineReturns?, removeParagraphReturns?, replaceSpaces?: n}}` +"unicode" | "ansi" | "shiftJis" | "gb2312" | "chineseBig5" | "cyrillic" | "gb18030" | "greek" | "turkish" | "baltic" | +"centralEuropean", platform?: "windows" | "mac", removeLineReturns?, removeParagraphReturns?, replaceSpaces?: n}}` (Text Import Options). Unicode reads UTF-8, or UTF-16 with a byte-order mark; ANSI reads Windows-1252 (Mac Roman on -`mac`). Unicode reads a file without a byte-order mark as UTF-16 by the rule `dataset.import` uses: at least half of -its two-byte units hold a NUL byte, in the byte order that reads a line break, or for a file with one line, big-endian +`mac`). The other sets use the WHATWG Encoding Standard's decoders: `shiftJis` Shift_JIS, `gb2312` GBK, `chineseBig5` +Big5, `cyrillic` windows-1251 (x-mac-cyrillic on `mac`), `gb18030` gb18030, and `greek`, `turkish`, `baltic` and +`centralEuropean` windows-1253, 1254, 1257 and 1250 on both platforms. They read a byte-order mark as ordinary bytes +and a malformed sequence as U+FFFD. An unknown set, or an option of the wrong type (`characterSet: 3`, +`removeLineReturns: "yes"`), is an error, and nothing is placed. Unicode reads a file without a byte-order mark as +UTF-16 by the rule `dataset.import` uses: at least half of its two-byte units hold a NUL byte, in the byte order that reads a line break, or for a file with one line, big-endian when more of its units start with a NUL byte than end with one, and little-endian otherwise. Any other file is read as UTF-8, else as the platform's 8-bit set: one with fewer NUL bytes, one with an odd length, one where both byte orders read a line break, and one that isn't valid UTF-16 in that order or holds a NUL character. `removeLineReturns` joins @@ -8302,7 +8829,9 @@ area). For a caller with read roots, the list leaves out `image/svg+xml`, and th (a one-page PDF, the page the objects' visual bounds) and `clipboard.exportPng {scale?}` (cropped to the objects, transparent around them). As in `document.export`, the PDF's and the PNG's replies list their notes in `warnings` (type written in the fallback font…; the PNG's also say when an image couldn't be decoded). After Copy or Cut the app -shows the first note of the PDF and PNG it offers in the status bar. +shows the first note of the PDF and PNG it offers in the status bar and how many there are, and hovering the message lists +them all, unless another message has replaced the Copy or Cut's while the formats were made. A Copy or Cut without +notes clears the notes message that an earlier Copy or Cut left. The `clipboard.export*` replies still list every note. What other apps copied goes into the clipboard with `clipboard.importSvg`, `clipboard.importPdf {dataBase64, page?, password?, editingData?}` (the page's objects; with `editingData: true` the data is a `.ai` or `.ait` file, and every @@ -8444,6 +8973,18 @@ every object in the layers each time the list is read. A `dcsTransparency` that returns `{id, onCanvas: false, owner}`, and the panel says the link has no place on the canvas. `links.embed {ids?}` keeps linked files' pixels in the document (an image whose file is missing stays linked: relink it first); `links.unembed {id, path}` writes an embedded image to a file (another extension converts it) and links to it, and without `path` returns `{name, dataBase64}`. +`ids` of one image works as `id` does. `links.unembed {ids?, folder}` writes each embedded image of `ids` (or of +`id`; default: the selected embedded images) to a new +file in `folder`, in the format it is stored in (as PNG when that format is not one of VectorCraft's raster file formats), and links each image to its file, keeping its bounds, in one undo +step; undo does not remove the files. A file is named after its image, with each character a file name can't hold +(`/ \ : * ? " < > |` and control characters) as `_` and `Image` when nothing is left; when the name is taken it is +`Name 2.png` … `Name 99.png`, and a file already in the folder is never replaced. Linked images among `ids` are left +as they are and listed in `skipped`. It returns `{unembedded: [{id, path}], skipped}`. When an image can't be written, +the files the call wrote are removed and the document does not change. A folder outside the automation write roots, +`id` given with `ids`, `path` given with `folder`, `ids` of more or fewer than one image without `folder`, an id given twice, and `ids` with +no embedded image are errors. The Links +panel menu's Unembed… with several embedded images selected asks for one folder and runs this form (on the web it +downloads each image instead and links none). `links.placementOptions {ids?, preserve?: transforms|bounds|fileDimensions|fit|fill, align?: topLeft…bottomRight, clip?}` decides how a relinked or updated file takes an image's place (default `bounds`: stretched into the old bounds; `clip` puts it in a clip group of the old bounds when it is larger). The UI commands `links.editOriginal` and @@ -8462,6 +9003,7 @@ malformed `ids`, or nothing to copy is an error, and the clipboard is left as it {"name":"run_command","arguments":{"command":"links.list","params":{"show":"missing"}}} {"name":"run_command","arguments":{"command":"links.placementOptions","params":{"ids":[12],"preserve":"fit","align":"top"}}} {"name":"run_command","arguments":{"command":"links.unembed","params":{"id":14,"path":"/tmp/logo.png"}}} +{"name":"run_command","arguments":{"command":"links.unembed","params":{"ids":[14,15],"folder":"/tmp/images"}}} ``` ## Package and Document Info @@ -8491,7 +9033,14 @@ file name, null for a built-in face; `embedding` is `allowed`, `editing`, `previ face is found), `imageObjects` (`[{name, width, height, linked, file}]`: the image objects in the order the linkedImages and embeddedImages categories list them, with the file a linked image's row shows and null for an embedded one), `document.unitId` (the document's units as Preferences › Units names them, such as `millimeters`, beside -the English `document.units`), `brushNames` (the brushes the art's strokes use, each once, hidden strokes, strokes at an opacity of 0, strokes with no +the English `document.units`), `document.transparency` (`{gridSize, gridColors, gridColorsName, simulatePaper, +flattenerPreset}`: File › Document Setup's transparency settings, the grid's size (`small`, `medium` or `large`), its +two colors as `#rrggbb`, their preset's name or `Custom`, Simulate Colored Paper and the flattener preset, which the +document category lists as Grid Size, Grid Colors (two custom colors by their values), Simulate Colored Paper and +Flattener Preset), `document.selectedArtboards` (`[{index, name, width, height, x, y}]`: while the Artboard tool is the +current tool, the artboards it has selected, in artboard order and in the document's units, with `x` and `y` those of +the top-left corner measured from the ruler origin of the tool's active artboard; the document category lists each +after the artboards as Artboard, Width, Height, X and Y; empty with any other tool), `brushNames` (the brushes the art's strokes use, each once, hidden strokes, strokes at an opacity of 0, strokes with no paint or width, guides, paths with no segment, type that draws no characters, a group's or layer's own strokes, a compound path member's own strokes and an image's strokes without a shape left out; with `selectionOnly`, the brushes the selected objects' strokes use), `brushes` (`[{name, type}]`: those brushes with their types, `calligraphic`, `scatter`, `art`, @@ -8661,8 +9210,9 @@ Colorized grayscale and 1-bit images use their process or spot ink; the flattene PostScript has no transparency: it is flattened first with `flattenerPreset` (`high`, `medium` (default), `low` or a saved preset, see `flattener.presets.list`) and `flattener: {…}` options over it (those of -`object.flattenTransparency`); a warning says so. `previewFormat` adds a TIFF preview behind a binary header (`tiffColor` -(default), transparent unless `transparentPreview: false`, or 1-bit `tiffBw`; `none` writes plain PostScript), +`object.flattenTransparency`); a warning says so. EPS Options' Custom… button sets every `flattener` option. +`previewFormat` adds a TIFF preview behind a binary header (`tiffColor` (default), transparent unless +`transparentPreview: false`, or 1-bit `tiffBw`; `none` writes plain PostScript), `thumbnails` a PNG thumbnail in comments, and the native document always rides along in the trailer's comments (with linked images whole when `includeLinkedFiles`), so a later EPS import can reopen the file as it was. Export for Screens doesn't write EPS. @@ -9018,7 +9568,7 @@ File → Export → Save for Web (Legacy) writes optimised web images: `document …}` renders the artboard (`clipToArtboard`, the default; `artboard` picks one) or the visible art and the slices, at `width`, `height` or `percent`, and encodes it with the format's settings: for GIF and PNG-8 `reduction`, `colors`, `dither`, `ditherAmount`, `transparency`, `matte`, `interlaced`, `webSnap`, `lossy` (GIF) and `colorTable {locked, -transparent, webShift, sort}`; for JPEG `quality`, `progressive`, `optimized`, `embedProfile` and `matte`; for PNG-24 +transparent, webShift, sort, deleted, customPalette}`; for JPEG `quality`, `progressive`, `optimized`, `embedProfile` and `matte`; for PNG-24 `transparency`, `matte` and `interlaced`. `metadata` (none, copyright, contact, all) writes File Info as PNG text or a GIF/JPEG comment; `convertToSrgb` marks PNGs as sRGB. `` is the name of `path` without its extension, or without `path` the document's title with the characters Windows does not allow in a file name as `-` and a `-` after @@ -9035,6 +9585,25 @@ file size), `seconds` to download at `kbps` (default 56.6), the size, and for pa `source` (the colour the reduction made), so a colour keeps its edits when it is web-shifted or snapped. `slice: n` previews one slice; `image: true` adds the file; `warnings` holds the export's warnings. +Delete Color is `colorTable.deleted: ["#rrggbb"…]`, by `source`. The deleted colors leave the table and the file, and +their pixels take the nearest color left, with the current reduction's color distance and dither; the preview and the +file agree. A deleted color also leaves `locked`, `transparent` and `webShift`. A color the table does not hold is +ignored. Deleting every opaque color is an error, and the settings, preview and files do not change; the transparent +entry of transparent pixels cannot be deleted. `colorTable.customPalette: ["#rrggbb"…]` is a fixed palette (a Custom +table) used instead of the reduction's own, at most `colors` entries with the transparent one included, so a color it +lacks is not made again; the dialog's Delete Color sets it to the table's colors on the first deletion. Both lists hold +at most 256 colors, and `#rrggbbaa` is refused. A `reduction` change without `colorTable` in the same params clears +both lists. JPEG and PNG-24 have no color table and do not read them. Presets and `webExport.settings` keep them. In +the dialog a click selects one color, Shift-click selects the colors between it and the last one clicked, and +Ctrl-click (Command-click on macOS) adds or removes one (`__colors` holds the selection, `__color` the last one +clicked). The trash button and Delete Color in the table's menu delete the selection in one edit, Restore Generated +Table in that menu clears `deleted` and `customPalette`, and the table reads Custom while either is set. Choosing +another reduction in the dialog also clears them. + +```json +{"name":"run_command","arguments":{"command":"document.exportForWeb.preview","params":{"format":"png8","colorTable":{"deleted":["#ff0000"],"customPalette":["#0000ff","#00ff00","#ff0000"]}}}} +``` + Optimize to File Size (the dialog's button under Preset) is `webExport.optimizeToFileSize {desiredK, startWith?, use?, slice?, …settings}`. It searches for settings whose files fit in `desiredK` K (1 K is 1024 bytes; above 0, at most 1048576) and returns them without writing a file or changing the remembered settings: `{targetBytes, achieved, @@ -9452,9 +10021,10 @@ layers are refused. - **pdfX1a** (PDF/X-1a:2001, written as PDF 1.3): CMYK, grey and spot colours only. Every colour and image is converted to `output.destination` (blank: the output intent's CMYK profile, else the working CMYK profile), untagged; an RGB destination or output intent is refused. Transparency is flattened before writing. -- **pdfX3** (PDF/X-3:2002, written as PDF 1.3): colours are tagged with ICC profiles; transparency is flattened. -- **pdfX4** (PDF/X-4:2010, PDF 1.6 at most): transparency and layers are kept, colours are tagged, and the XMP metadata - names the standard and has an `xmp:MetadataDate` equal to its `xmp:ModifyDate`. +- **pdfX3** (PDF/X-3:2002, written as PDF 1.3): colours are tagged with ICC profiles, except CMYK colors in the CMYK + output intent's profile, which are DeviceCMYK (see `output.profiles`); transparency is flattened. +- **pdfX4** (PDF/X-4:2010, PDF 1.6 at most): transparency and layers are kept, colours are tagged as in pdfX3, and the + XMP metadata names the standard and has an `xmp:MetadataDate` equal to its `xmp:ModifyDate`. Flattening uses `flattenerPreset` (default High Resolution, see PDF 1.3 above) on a copy (the document is untouched; a warning says so), and images with see-through pixels count as transparency. The written file is checked against @@ -9518,7 +10088,11 @@ stay square to it, as in the reference app. `object.distort` turns it as the war (see Free Distort on a turned bounding box). `object.rotate {angle, absolute: true}` turns the selection to an angle (the Transform and Properties panels' Rotate field), and `object.setBounds` measures width, height and the reference point along the turned box (x, y stay page coordinates). Objects turned together share the box. A new group starts -square to the page. `object.resetBoundingBox` squares the box again without moving the art. It also squares every +square to the page. `object.rotateBoundingBox {angle}` turns the selection's box by `angle` without moving the art +(`absolute: true` turns it to `angle`; the menu's Rotate Bounding Box… asks for the angle). Selected objects with +different angles get one shared angle, and the objects inside them keep their angle relative to them. A path of a +compound path selected on its own turns or squares only its own box. A box already at the angle adds no undo step. +`object.resetBoundingBox` squares the box again without moving the art. It also squares every object inside the selected ones: the children of groups, compound paths, clip groups, blends, envelopes, repeats and intertwines, and the art of linked opacity masks (an unlinked mask's art keeps its angle). Ungroup, Release Clipping Mask, Release Compound Path, Blend Expand, Release Envelope, Release Repeat, Release Intertwine and Release Opacity Mask @@ -9619,6 +10193,23 @@ Native files save it only when it is `rows`, so files from before it open by col {"name":"run_command","arguments":{"command":"text.areaOptions","params":{"rows":2,"columns":3,"flow":"rows"}}} ``` +### First baseline + +`text.areaOptions {firstBaseline: ascent|capHeight|xHeight|leading|emBoxHeight|fixed, firstBaselineMin?: pt}` (Area +Type Options › First Baseline and Min) sets how far below the top of the type area, inside the inset, the first line +of each row/column cell sits. `emBoxHeight` (Em Box Height) puts the top of the line's ideographic em box at that +top; on a line of several sizes the largest em box is used, and vertical type measures it from the frame's right +edge. The em box is the one leading measured from em box top to top uses: an ideograph's cell in the font's +vertical metrics, or 0.88 em above the baseline when the font has none (VectorCraft's own rule). With every kind but +`fixed`, `firstBaselineMin` is the least distance from the top to the first baseline; with `fixed` it is the +distance. Each threaded frame keeps its own setting. Native files and `.ai` files save `emBoxHeight` and open it again; other values are refused. The help +page describes the option: +https://helpx.adobe.com/illustrator/desktop/design-with-text/add-manage-text/add-margins-to-text-and-adjust-the-first-baseline.html + +```json +{"name":"run_command","arguments":{"command":"text.areaOptions","params":{"firstBaseline":"emBoxHeight","firstBaselineMin":6}}} +``` + ## Fitting area type: Auto Size, Shrink Text to Fit, overflow `text.areaOptions` (and `text.create`'s `area`, `text.createInPath` in area mode) take a `fit`: @@ -9803,7 +10394,7 @@ thread. When `effect.expandAppearance` keeps a frame as type in a group (type wi effects are shadows, outer glows or Crop Marks), the type stays in the thread in the frame's place. Object › Expand (`object.expand`) outlines type with these two commands. `object.flattenTransparency` takes each frame of threaded text that it outlines (`textToOutlines`) or turns into flat regions or an image out of its thread in the same way. -`symbol.new` (New Symbol) and `symbol.update` (Redefine Symbol) take each frame of threaded text in the selection out +`symbol.new` (New Symbol) and `symbol.update` (Redefine Symbol), without `keepArt: true`, take each frame of threaded text in the selection out of its thread in the same way, and the symbol's art holds a copy of the frame with the text it shows. When every frame of a thread goes into the symbol, the copy of the last frame keeps the text it has no room for. @@ -10490,6 +11081,25 @@ after Remove Threading or Release Selection, in a frame converted to point type, duplicated, copied in the Layers panel, or taken out of a symbol or a placed file). A symbol made of a thread keeps the numbers in the symbol's art. +`text.setFormat {startNumber: 1..999999999}` gives a numbered paragraph a number of its own, and +`text.setFormat {restartNumbering: true}` gives it 1. Both are VectorCraft's own. The number goes to the first numbered +paragraph the call touches: the first that holds text, or the first when none does, taking the type objects in the +order of `ids`. A threaded frame's first paragraph is passed over when it continues from the frame before. The +paragraph given the number shows it, and the numbered paragraphs after it at its level count on from it, +through the frames of threaded type. Deeper levels count from 1 after it, as after any list paragraph, and a paragraph in +no list still starts the count again. `restartNumbering: false` takes the number away from every paragraph the call +touches except such a continued first paragraph, and they count on from the paragraph before. `startNumber` is a whole number (`5` or `5.0`); 0, a negative +number, a fraction, a number past 999999999 and any other type are errors, and giving both keys is an error. A call +that touches no numbered paragraph, or that gives the number the paragraph already has, changes nothing and records no +undo step. A call that also puts paragraphs in a numbered list gives the number after the list is set. Return in a +paragraph with a number of its own does not give the number to the new paragraph; Return, or pasted text that starts +new paragraphs, at the start of its text moves the number with the text. Making the paragraph bulleted or taking it out of its list removes the number, and Convert to +Text writes the numbers the paragraphs showed. The list saves the number (`"start": 5`) only when it is set; a file's +number below 1 or past 999999999 opens as the nearest of them. A paragraph style made from the paragraph does not keep +the number, and a paragraph style's `list` with a `start` is an error (`unknown attribute`). A graph keeps one paragraph +style for every label of a kind, so a graph label loses its number when the graph is drawn again. The canvas and the formats +that write the marker (below) write the number the paragraph shows. + The canvas, EPS, PDF and Type › Create Outlines draw the marker. PDF writes the marker as text of its own, where the canvas draws it, and a PDF viewer selects, copies and finds its characters. Each of its glyphs stands for the marker character that the glyph's font maps to that glyph in its character map. Glyphs that an OpenType feature such as @@ -10510,11 +11120,14 @@ More Options at the end of the Paragraph panel's Bullets and Numbered List prese dialog (`bulletsAndNumbering`) on the paragraphs the Paragraph panel acts on, on that tab; without `tab` it opens on Numbers when the paragraphs are a numbered list and on Bullets otherwise. On both tabs the Level field, above the presets, holds the paragraphs' list level (1 to 9; 1 for paragraphs in no list). The Bullets tab has the five bullet -presets and the Numbers tab has None and the seven number styles. The Position group has Alignment (Left or Right), +presets and the Numbers tab has None and the seven number styles, then Start at, a box with a number from 1 to +999999999 (1 until one is typed). The box is on when the paragraphs have the same number of their own, off when none +has one, and blank when they differ; on, OK sends `startNumber` with the number, and off, it sends +`restartNumbering: false`, unless a preset makes the paragraphs bulleted or takes them out of their list. The Position group has Alignment (Left or Right), Left Indent and First Line Indent. The dialog opens with the values the Paragraph panel shows; where the paragraphs differ, no preset is picked and the field is blank. Its fields are `tab`, `list` (`none`, `bullet` or `number`: the kind of the preset picked), `bullet`, `number`, `listAlign`, `listLevel`, `leftIndent` and `firstLineIndent` (points), -and `ui.dialog.set` sets them, including those the dialog opened blank or without. The type shows the dialog's values while it is open. A preset picked for paragraphs that are in no list and have +`startAt` (true or false) and `startNumber`, and `ui.dialog.set` sets them, including those the dialog opened blank or without. The type shows the dialog's values while it is open. A preset picked for paragraphs that are in no list and have no indents fills in 18 pt and -18 pt, and None takes them out again while they are unchanged. OK runs `text.setFormat` with the values that changed, as one undo step, and Cancel puts the type back as it was. When a preset puts the paragraphs in a list, OK also sends the indents the dialog shows, and the paragraphs take them, 0 included. OK does not @@ -10575,6 +11188,8 @@ the paragraph's text now starts; when the text before `at` starts no list, nothi {"name":"run_command","arguments":{"command":"text.setFormat","params":{"number":"upperRoman"}}} {"name":"run_command","arguments":{"command":"text.setFormat","params":{"listAlign":"right"}}} {"name":"run_command","arguments":{"command":"text.setFormat","params":{"listLevel":2,"start":4,"end":4}}} +{"name":"run_command","arguments":{"command":"text.setFormat","params":{"startNumber":5,"start":4,"end":4}}} +{"name":"run_command","arguments":{"command":"text.setFormat","params":{"restartNumbering":true,"start":12,"end":12}}} {"name":"invoke_menu","arguments":{"command":"ui.bulletsAndNumbering","params":{"tab":"numbers"}}} {"name":"run_command","arguments":{"command":"text.convertListToText","params":{}}} ``` @@ -11314,6 +11929,10 @@ no file, and an import opens no document). A filter whose manifest asks for a he `plugin.inspect {path | dataBase64}` entry) needs a person's approval, and `plugin.install` refuses `allowHeavy: true` from a request. `plugin.run` runs it where it is called, so the call may take minutes; `notifications/cancelled` stops it. +The preference `pluginInstructionBudget` (`normal`, the default, or `large`; `prefs.set` refuses any other value) +sets the instructions every object filter run gets: Large gives a light filter 250 M instructions instead of 50 M, +plus 4,000 per input byte either way, with its 60 s time budget unchanged; a heavy filter keeps its own budget with +either value. The next `plugin.run` or plug-in command uses the value set ([plug-ins](plugins.md#instruction-budget-preference)). A plug-in whose manifest lists permissions (`permissions` in its `plugin.inspect` entry, with `needsApproval: true`) needs a person's approval too, and `plugin.install` refuses `grant: [permission]` from a request. With a desktop app connected, `ui.installPlugin` opens the approval dialog and returns `{pending: "pluginInstall"}`; `answer_dialog`, @@ -11406,6 +12025,7 @@ Disable and Continue can't save the plug-in it turns off, this launch skips it a {"name":"run_command","arguments":{"command":"plugin.setEnabled","params":{"id":"org.example.wobble","enabled":true}}} {"name":"run_command","arguments":{"command":"plugin.install","params":{"path":"/plugins/desaturate.wasm"}}} {"name":"run_command","arguments":{"command":"plugin.run","params":{"id":"org.vectorcraft.example.desaturate","params":{"amount":60}}}} +{"name":"run_command","arguments":{"command":"prefs.set","params":{"key":"pluginInstructionBudget","value":"large"}}} {"name":"run_command","arguments":{"command":"effect.apply","params":{"effect":"plugin.org.example.wobble","params":{"size":4}}}} {"name":"run_command","arguments":{"command":"document.open","params":{"path":"/tmp/plot.hpgl","importer":"plugin.org.example.hpgl"}}} {"name":"run_command","arguments":{"command":"plugin.org.example.tidy.grow","params":{"by":3}}} @@ -11546,10 +12166,23 @@ intensity), and the Symbolism tools one brush. Interaction state (pins, a refere desktop app, while the Artboard tool is in use, a change to its `selected` or `active` makes the artboard it then has active the active artboard (the navigator's and the Artboards panel's). +Every option given is checked before any is set. A key that the tool's `check_option` does not take (it is unknown +to that tool), a value of the wrong type, a number outside the tool's range, an unknown choice, a `key` without a +`value`, a `values` that is not an object or a `tool` that is not a tool id is an error result that names the tool and +the option, and nothing changes: no option, no saved preference and no undo step, also when another option given with +it is good. Parameters that are not an object are an error too. `{}`, or no parameters, reads the options and sets +nothing. The ranges are VectorCraft's own (for example the Smooth tool's `fidelity` takes 0.05 to 100, the Pencil's +0.01 to 100); a refused value in a Tool Options dialog keeps the dialog open. The Live Paint tools' `width` and the +Shape Builder's `gapLength` are set to the nearest end of their range when a number outside it is given, as their +sections above say. + ```json {"name":"run_command","arguments":{"command":"tool.setOption","params":{"tool":"twirl","values":{"width":60,"rate":90}}}} +{"name":"run_command","arguments":{"command":"tool.setOption","params":{"tool":"smooth","key":"fidelity","value":-3}}} ``` +The second call returns the error ``tool `smooth`: `fidelity` must be a number from 0.05 to 100``. + The Pencil's, the Paintbrush's and the Smooth tool's `fidelity` is in screen pixels: the tools send `path.freehand` and `path.smoothRegion` the option divided by the zoom, so a stroke keeps as many points and a Smooth drag smooths as much at any zoom. The Smooth tool's `fidelity` (0.05 to 100 px, 2.5 by default) is also the one an Alt smoothing drag with @@ -12002,7 +12635,9 @@ EPS files hold its drawn steps, as they do for every blend: With the Blend tool active, `tool.select {tool: "blend"}` finishes the blend, as a click on the tool's button or W does: it drops the object clicked first and stops the next click adding to the blend just made. The document and the -selection stay as they are. Choosing any other tool that is already active leaves its work as it is. +selection stay as they are. With the Pen active, `tool.select {tool: "pen"}` ends the path being drawn as Escape does, +and so do P and a click on the Pen's button: the path stays open and selected (a path inside a compound path leaves +the compound path selected), and the next click starts a new path. Choosing any other tool that is already active leaves its work as it is. A blend's spine is the straight lines between its key centres until it is edited. `object.blend.info` lists it (`spine.anchors`, `keyAnchors`: the point each key sits on). `object.blend.spine.addAnchor {x, y}` adds a point where @@ -12626,6 +13261,18 @@ Commands: drawn, and the path's fills stay on it, below its dashes (a path without fills goes). A compound path's dashes are plain paths with its appearance. Paths without a dashed stroke stay as they are, and it is an error if none has one. The dashes are selected; more than 100,000 (or a pattern too fine to draw) is refused. → `{ids, dashes}`. +- `addon.pathtools.bridge {radius?, keepOriginals?, ids?}` joins two circles (`ids`, default: the selection; paths + whose outline is a circle, not hidden or locked) into one closed outline, as one undo step (Object › Plug-ins › Path + Precision Tools › Smooth Bridge…). The outline goes around each circle on its side away from the other and along two + concave arcs, one on each side of the line through the centers, each touching both circles from outside, so every + anchor is smooth. `radius` is the arcs' radius as a percentage of the smaller circle's radius (1 to 1,000, 100 by + default): a larger radius makes a wider, gentler bridge. Overlapping and touching circles are joined at every radius. + One circle inside the other is an error, and so are circles too far apart for the radius: the arcs would not reach + both circles, or would cross before they do. The error suggests a larger radius only when one up to 1,000 would + bridge the circles. The outline replaces the two circles, painted as the upper one (a plain + path), unless `keepOriginals` is true: then it goes directly above the upper circle, painted as it, and the circles + stay. The outline is selected. → `{id}`. Smooth Bridge… opens a dialog (`ui.menuDialog {command}`, kind + `smoothBridge`) with a Radius field in percent, Keep Originals and Preview. - `addon.pathtools.tangentCircle {ids?, radius?, circle?}` draws the circles that touch two paths or compound paths and have `radius` (0.01 to 1,000,000 pt, needed with two), or that touch three (which set the radius themselves, so `radius` is then an error), as one undo step (Object › Plug-ins › Path Precision Tools › Tangent Circle…). `ids` @@ -13336,10 +13983,10 @@ there is no step. → `{symbols: [name…], ids: [instance id…], skipped: [{la ## Packaging Tools add-on Packaging Tools is a built-in add-on for the dielines of boxes and other folded packaging. Its commands are -`addon.packaging.setRole`, `addon.packaging.roles`, `addon.packaging.setRoleSwatch` and `addon.packaging.check`. In the -desktop app, Object › Plug-ins › Packaging Tools › Fold Lines opens the Fold Lines panel, Make Cut Line, Make Crease Line, -Make Partial Cut Line and Make Perforation Line run `addon.packaging.setRole` on the selection, and Check Fold Lines runs -`addon.packaging.check`. +`addon.packaging.setRole`, `addon.packaging.roles`, `addon.packaging.setRoleSwatch`, `addon.packaging.check` and +`addon.packaging.fold`. In the desktop app, Object › Plug-ins › Packaging Tools › Fold Lines opens the Fold Lines panel, +Make Cut Line, Make Crease Line, Make Partial Cut Line and Make Perforation Line run `addon.packaging.setRole` on the +selection, Check Fold Lines runs `addon.packaging.check`, and Fold Preview runs `ui.foldPreview`. ### Fold line roles @@ -13435,6 +14082,54 @@ The list is shown until the document changes. {"name":"run_command","arguments":{"command":"addon.packaging.check","params":{"tolerance":0.5,"select":true}}} ``` +### Fold Preview + +`addon.packaging.fold` (`{ids?, base?: [x, y], amount?: 1, tolerance?: 0.1}`) folds a blank into its 3D shape. It reads +the fold lines as `addon.packaging.check` does, and folds the blank that holds the base panel: the panel under `base`, or +the largest panel of all the blanks. The base panel stays in place. Every other panel turns about the hinges that join it +to the base, each by its angle times `amount` (0 is flat, 1 is folded): a Crease or a Perforation folds 90° away from +the printed side, so the print ends up outside, and a Partial Cut folds 90° toward it. A hinge that closes a loop of +panels is not turned about; `gap` says how far apart its two placements end up when every hinge is folded all the way, +whatever `amount` is, and it `closes` when that is within `tolerance` or 0.5% of its length. A panel that no chain of +hinges joins to the base stays flat where it is. `amount` must be from 0 to 1 and `base` a point in a panel; anything +else is an error. The command does not change the document. + +Result: `{ok, blank, blanks, base, panels: [{outline, frame: {x, y, z, origin}, parent, depth}], hinges: [{a, b, +angle, kind, closes, gap}], collisions: [[a, b]], issues}`. `outline` is the panel's SVG path data in document +coordinates. `frame` gives where the flat blank's x and y directions, its printed side and its origin end up, in points, +with x to the right, y up and z toward the printed side of the flat blank. `kind` is `tree` for the hinges the panels +turn about and `closing` for the others. `collisions` lists the panels that pass through each other; panels stacked in +one plane, such as the top flaps of a closed box, are not listed. Without a blank (`ok` false), `blank` and `base` are +null and the lists are empty; `issues` are those of `addon.packaging.check`. + +The Fold Preview window (Object › Plug-ins › Packaging Tools › Fold Preview, or the Fold Lines panel's Fold Preview +button) shows the blank that the document's shown fold lines make, folded, with the document's printed art on the +outside of each panel and the board's inside color on the back. The print leaves out the fold lines, unless Show Fold +Lines is on, and the layers that do not print. Under the view, the Fold slider sets the amount and the Zoom slider the +zoom; a status line gives the panels and hinges and says when a joint does not close, when two panels pass through each +other, when other blanks are not shown and when the fold lines have an error. Dragging in the view turns it, a +Shift-drag keeps to one axis, a middle-drag or a Space-drag moves it, the wheel zooms, a double-click on a panel makes it +the base, and the arrow keys turn the view by 5° when it has the keyboard focus. The view is drawn at the display's +pixel density up to 2,097,152 pixels (2,048 × 1,024) and 4,096 pixels along a side, and at a lower density past either, +and the print is a raster whose longest side is 2,048 pixels, rendered again when the document changes. + +`ui.foldPreview` (`{amount?, view?: front|back|left|right|top|bottom|threeQuarter, rotateX?, rotateY?, zoom?, +perspective?, inside?, showFoldLines?, base?}`) sets the window, shows it and draws it again. A second run leaves the +window open. `rotateX` (-180 to 180) tips the top toward the viewer and `rotateY` (-180 to 180) turns the right side +toward the viewer, in degrees; `zoom` is 0.1 to 8, where 1 fits the folded blank; `perspective` is the field of view, 0 to +160 degrees, 0 for none; `inside` is the name of a swatch with a plain color, or else `#rrggbb`, or `""` for white; `base` is a point in a panel +of the document's blanks, or null for the largest panel. With perspective, the zoom of 1 keeps the eye at least twice +the folded blank's radius from its middle. A value of the wrong kind or out of range is an error and sets nothing. +VectorCraft's own defaults are a Three-Quarter view (`rotateX` 25, `rotateY` 35), no perspective, a white inside and the +fold lines hidden. Saved settings out of range are brought into range when the window is drawn. Result: the window's +settings, and `frame`: the last frame's `{width, height}` in pixels and how long the fold and the drawing took (`foldMs`, +`drawMs`), or null before the first frame. The view is folded and drawn again only when the document, the settings or +the window's size change. + +```json +{"name":"run_command","arguments":{"command":"ui.foldPreview","params":{"amount":0.5,"view":"threeQuarter","perspective":30}}} +``` + ## Image Tools add-on Image Tools is a built-in add-on for placed images: its commands are `addon.image.removeBackground`, @@ -13606,6 +14301,45 @@ Path Options' Preview does (#5360). {"name":"run_command","arguments":{"command":"addon.type.releasePath","params":{"mode":"path","keepOriginal":true}}} ``` +## Unit Converter add-on + +Unit Converter is a built-in add-on that shows one length in every unit at once (#5528): its commands are +`addon.units.convert` and `addon.units.selectionSize`, and in the desktop app it lives in Object › Plug-ins › Unit +Converter and in its panel (`window.panel {panel: "unitConverter"}`). Neither command changes the document. + +`addon.units.convert {value, unit?}` reads `value` as a number field reads it: a number, or text with a unit suffix and +`+ - * /` arithmetic (`"10mm"`, `"1in/2"`, `"2p6"`, `"1080/2 px"`, `"3cm*50%"`, `"13q"`), a decimal comma read as a point +(`"0,5 mm"`) and a single number with a thousands comma (`"1,000 mm"`) refused, in at most 1024 bytes with at most 128 `+ - * /` signs. A +number without a suffix is in `unit` (a unit's name, suffix or key: `points`, `picas`, `inches`, `millimeters`, +`centimeters`, `pixels`, `feetInches`, `meters`, `yards`, `feet`, `q`, `ha`; default `points`); a suffix in the text +takes precedence over `unit`. It works without an open document. The command fails when `value` is missing, does not +read, or is not finite in every unit, and when `unit` is not a unit. Result: `{points, units: [{unit, label, number, +text}]}`: the length in points, then one row per unit of Preferences › Units › East Asian Type (pt, picas, in, mm, cm, +px, ft & in, m, yd, ft, Q, Ha) in that order, with the unit's key, its label, the number without its suffix and the +text with it, rounded as the number fields round them (3 decimals in pt, px, picas, Q and Ha, 4 in the others). Pixels +are points. + +`addon.units.selectionSize {}` gives the selection's width and height as the Transform panel shows them: the bounding +box (rotated with rotated objects), the visual bounds with Use Preview Bounds, or the box around the selected anchor +points with Direct Selection. It fails with nothing selected. Result: `{width, height}`, each as +`addon.units.convert` gives a length. + +The panel has one field per unit. A value typed in any field updates the others as it is typed, and text that does not +read leaves them as they were. Each field's copy button puts its value on the clipboard, with the unit when Copy with +Units is on. From Selection reads the selection's size (`addon.units.selectionSize`), and Width or Height picks which +of the two the fields show; the size read is dropped when the document, its selection, Use Preview Bounds or Measure +Type by Glyph Bounds changes, and the fields keep the length they show. Apply sets that side of the selection to the length with `object.setBounds`, as the Transform +panel's W or H field does: from its reference point (a symbol instance's registration point with Use Registration Point +for Symbol on), with the other side scaled too under Constrain Width and Height Proportions, and with the panel menu's +Transform Object Only, Transform Pattern Only or Transform Both. It is one undo step, and none when the size is already +that length. + +```json +{"name":"run_command","arguments":{"command":"addon.units.convert","params":{"value":"10mm"}}} +{"name":"run_command","arguments":{"command":"addon.units.convert","params":{"value":2.5,"unit":"in"}}} +{"name":"run_command","arguments":{"command":"addon.units.selectionSize","params":{}}} +``` + ## Save location errors A save refused by the filesystem with PermissionDenied or ReadOnlyFilesystem returns diff --git a/docs/plugins.md b/docs/plugins.md index 2702e4fe7b..344e3b7c00 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -126,7 +126,7 @@ defaults): | Module size | 32 MiB | rejected | | Linear memory | 512 MiB per instance (input and parameters: at most half) | `memory.grow` returns -1; oversized input or initial memory fails | | Output | 64 MiB of JSON | `Limit("output size")` | -| Instructions (fuel) | 50 M per call + 4,000 per input byte for `vc_run`; a [heavy filter](#heavy-filters) 1 G + 4,000 per byte; an export or import 10 G + 4,000 per byte | `Limit("instruction budget")` | +| Instructions (fuel) | 50 M per call + 4,000 per input byte for `vc_run`; an object filter with the [Large instruction budget](#instruction-budget-preference) 250 M + 4,000 per byte; a [heavy filter](#heavy-filters) 1 G + 4,000 per byte; an export or import 10 G + 4,000 per byte | `Limit("instruction budget")` | | Wall clock | 60 s per filter run, 5 s per live-effect run, 300 s per heavy filter run, export or import (checked every 20 M instructions; the web build reads the page's `performance.now()`) | `Limit("time budget")` | | Import input | 128 MiB of the file (`vectorcraft_plugins::import::MAX_INPUT_BYTES`) | the file doesn't open; a larger file named by `path` is not read past that | | Call depth | 1,024 frames | trap | @@ -136,6 +136,22 @@ An export runs where the export runs: with Background Export on, on the export's plug-in between two of those 20 M-instruction slices; nothing is written then. An import stops the same way when the open it runs in is cancelled, and nothing opens then. +### Instruction budget preference + +Preferences › Plug-ins & Scratch Disks › Plug-in Instruction Budget (`pluginInstructionBudget`, VectorCraft's own +setting) sets the instructions each object filter run gets, from the app, `plugin.run`, a plug-in's commands, scripts +and MCP alike: + +- **Normal** (`normal`, the default): the limits in the table above, 50 M + 4,000 per input byte. +- **Large** (`large`): 250 M + 4,000 per input byte (`vectorcraft_plugins::LARGE_FUEL`, 5 times Normal). The 60 s time + budget, the memory, output and call depth limits stay as they are. + +A [heavy filter](#heavy-filters) keeps its 1 G and 300 s with either choice. Live effects, exporters and importers keep +their own budgets. A change applies to the next run of every installed filter, without installing it again. Cancel and +the time budget stop a run between two 20 M-instruction slices with either choice. `prefs.set {key: +"pluginInstructionBudget", value}` takes `normal` or `large` (or the labels Normal and Large) and refuses any other +value; a saved preferences file with another value reads as Normal. + ### Live effects while a document opens While the app draws a document on screen, the live-effect runs of its first view share a 2,000 ms budget diff --git a/docs/roadmap.md b/docs/roadmap.md index fe7bee3000..3f6c1741ba 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,9 +1,11 @@ # Roadmap: milestones and what's next -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-17 · **Change:** minor (PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; M1: Layers panel Alt-drag shows the copy cursor, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: M7: Check Spelling modal dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); previously: Tech Circuit brush library, G5; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously minor: M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (PDF export writes the document language as the catalog's `/Lang`, #3644; M1: an Alt-drag in the Layers panel copies a row above or below its own place, #8237; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; M1: Layers panel Alt-drag shows the copy cursor, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: M7: Check Spelling modal dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); previously: Tech Circuit brush library, G5; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously minor: M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) > > Oversized artboard import update (2026-11-12): Explicit editing-data import retains a single artboard beyond a capped 14,400 pt PDF page (#6865). > +> Selection update (2026-11-11): path and compound-path interiors follow enabled non-None fill rows, including lower fills beneath a top None row (#6625). Hidden-only interiors miss; zero-opacity fills remain selectable. Cap/join follow-up (2026-11-12): hidden-fill and no-fill stroke hits must respect cap and join geometry; focused cap/join CPU regressions passed. Scores and estimates unchanged. +> > Vector Halftone preview update (2026-11-10): temporary dot selection marks are hidden, and the bounding box stays available (#6369). > > **Eraser fill update (2026-11-11):** filled open paths without a visible painted stroke retain fill outside the sweep or Alt-drag marquee (#6582); stroked paths retain main behavior; scores and estimates unchanged. @@ -59,6 +61,7 @@ M7 type: Touch Type moves a right-to-left character along its line and up from i | Date | Change | Summary | |---|---|---| +| 2026-11-18 | minor | M14: PDF export writes the document language (Document Setup) as the catalog's `/Lang` (#3644). Scores and estimates unchanged. | | 2026-11-13 | minor | Graphic Styles: in a panel made taller the list fills the space above the footer instead of stopping at 220 pt (#2992; `the_list_fills_a_tall_panel_above_its_footer` in `crates/ui-egui/src/panels/graphic_styles.rs`). Scores and estimates unchanged. | | 2026-11-13 | minor | PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke instead of being left out, adding no text (#6971; `empty_actual_text_keeps_the_glyphs_art` in `crates/pdf/src/tests/actual_text.rs`). Scores and estimates unchanged. | | 2026-11-13 | minor | Library panels (swatch, Color Book, brush, symbol and graphic style libraries): in a panel made taller the list fills the space above the footer instead of scrolling inside 220 or 280 pt (#2992; `the_list_fills_a_tall_panel_above_its_footer` in `crates/ui-egui/src/panels/library_panel/tests.rs`). Scores and estimates unchanged. | @@ -160,7 +163,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | # | Milestone | Status | Est. remaining, one agent (h) | |---|---|---|---| | M0 | Skeleton + vertical slice | ✅ done | — | -| M1 | Selection, transform, layers, MCP (common command tools, strict keys, session resources and version-aware result hints) | ✅ mostly done (document-tab artwork drag with lossless resource transfer and one target Undo; malformed MCP app replies discard the connection without replay, #1761; bounded control socket waits and connection-slot recovery, #1726; bounded synthetic control input, #1709; no-op anchor Align keeps Undo, Redo and saved state (#1180 follow-up); transform reference point snaps to anchors/centres; rotated objects keep a rotated bounding box and their angle; Free Transform, Scale and Reflect along a rotated box pending; the Transform fields take one Tab each, the W/H link after them) | 4–6 | +| M1 | Selection, transform, layers, MCP (common command tools, strict keys, session resources and version-aware result hints) | ✅ mostly done (path and compound-path interior selection follows enabled fill rows (#6625); hidden-fill and no-fill stroke cap/join CPU regressions passed; document-tab artwork drag with lossless resource transfer and one target Undo; malformed MCP app replies discard the connection without replay, #1761; bounded control socket waits and connection-slot recovery, #1726; bounded synthetic control input, #1709; no-op anchor Align keeps Undo, Redo and saved state (#1180 follow-up); transform reference point snaps to anchors/centres; rotated objects keep a rotated bounding box and their angle; Free Transform, Scale and Reflect along a rotated box pending; the Transform fields take one Tab each, the W/H link after them) | 4–6 | | M2 | Drawing tools + smart guides | ✅ mostly done (Eraser preserves fill outside fixed and varied tip sweeps and Alt-drag marquees on fill-only open paths and keeps their compound holes; clipping masks retain surviving contours or empty geometry in the same node; ordinary Group/Layer paints and evaluated gradient placements are preserved when the stored paint reproduces their appearance; hidden Rasterize and Along/Across stroke rows do not block visible gradients; replacement-art effects, plug-ins/Rasterize, along/across-stroke gradients and placements that cannot be reproduced keep their existing fitting; stroked open paths retain main behavior (#6582); #3380 deletion creates independent selected path pieces and keeps bounds-fitted gradients in place; endpoint highlighting remains open; Polygon/Star exact-size count persistence, with repeated-drag, tool-switch and Cancel regression coverage; Curvature point markers without direction handles (#1236, in part); Direct Selection segment click/Delete preserves neighboring edges, #1278; Flare, Reshape, Live Corners widget dragging and per-corner radii and kinds landed, on any path's corners; Shaper rough-shape recognition and orientation steps, the remaining Pen modifier nuances; Shaper Groups with editable sources and separate fill/stroke edits landed; custom ruler origin with drag preview, active-artboard reset, relative X/Y fields and native round-trip (#1212); construction widget/refinements pending); a shape just drawn moves by its centre point and turns from the zone outside a corner with its tool still active (#5477); Tangent and straight-segment perpendicular snapping use saved Smart Guides Geometric Guides preferences and Control bar quick access (#2537), including the existing Snap to Glyph and Alignment Guides toggles (#6164); no View submenu; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123) | 12–18 | | M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper copies transformed character dimensions (#6404) and styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel (its spectrum grows with a resized panel, #8005), Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416; native Lab entry and swatch libraries in the picker, Assign-row menus, #8031/#4028); gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit; finite-arithmetic follow-up regressions and full CI passed ([Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area))), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform gradients in SVG/PDF, mixed spot/process gradients in SVG and PDF gradients mixing a spot color with RGB or Lab stops export as stops or process colors; PDF export writes dithered gradient fills with spot stops, and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, as images in process colors; confirm the Scale Strokes & Effects default; Recolor model selection is available through the engine and MCP only (#2520); the dialog retains its existing controls; Library panels' lists (swatch, Color Book, brush, symbol and graphic style libraries) fill a taller panel above its footer (#2992; scores and estimates unchanged); Graphic Styles list fills a taller panel above its footer (#2992; scores and estimates unchanged); Swatches list fills a taller panel above its footer (#1638; `the_list_fills_a_tall_panel_above_its_footer`; scores and estimates unchanged); | 4–8 | | M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300; estimates unchanged); PDF import: type filled and stroked by one text-showing operator comes in as one filled and stroked type object (#8015; not yet for type filled and stroked at less than full opacity, or a `TJ` whose kerning starts a new line part way through, which still come in as a filled object and a stroked one; estimates unchanged); PDF import: stroked type keeps the file's line cap, line join and miter limit (#7741; estimates unchanged); Rename artboards in Export for Screens (#7275); Explicit editing-data import keeps oversized capped-page artboards (#6865; estimates unchanged); Save refusal continuation (#6146): ordinary Save offers Save As; unchanged format keeps options, changed format opens its Save options; cancellation/automation isolation; focused UI regressions passed, native acceptance pending; PDF authored ActualText preserved once in editable import (#6165; first-glyph line/style, bounded input; estimates unchanged); PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. `.ai`/EPS type from the text document keeps its paragraphs' tab stops (#6147); `.ai`/EPS type from the text document keeps auto leading per line, its hyphenation options, and may show more of the last lines the file sets in an area frame of its own, when growing the frame by its lines' deepest descent plus 0.05 pt shows them (#6137); ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), shared guarded PDF writer and windowed reader ([pdf-backend.md](pdf-backend.md)), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out (EPS legacy mesh corners, vector opacity masks and raster page comparison verified; closed SPLINE flags round-trip and circular paths export as native CIRCLE/ARC, #1299), EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, TIFF in Export for Screens and Asset Export, clipboard flavours, File Info; AF.1–AF.4 add Affinity import (native layers, artboards, vectors, text and images from Affinity 1–3 files; the embedded preview only as a warned fallback; AF.4 expands current `.af` fixtures and every-board round-trip validation); EPS Save and Save As keep an opened EPS as EPS with its page frame and complete editable VectorCraft document (2026-10-26; G9 import fidelity unchanged). Left: DWG (use DXF), PSD placement as layers, overprint read back from PDF, Affinity export, polish; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke, adding no text (#6971; scores and estimates unchanged); | 3–6 (existing scope; Affinity export unestimated) | @@ -173,7 +176,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View, middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | | M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color, Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369); Live Paint Bucket fills faces crossed in one drag (#6373) | 6–10 | | M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; the script document model and batch work remain | 18–27 | -| M14 | 1.0 polish (preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all, #6659); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset , UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307); Swatches item context menus tested in all five views and rendered layouts inspected; Linux full CI passed, Windows engine baseline limitations documented (G12) | 18–28 | +| M14 | 1.0 polish (preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all, #6659); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset , UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646) and give the document language as the catalog's `/Lang` (#3644); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307); Swatches item context menus tested in all five views and rendered layouts inspected; Linux full CI passed, Windows engine baseline limitations documented (G12) | 18–28 | | — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed) | ⬜ (new ruler-guide Alt orientation implemented; existing-guide Escape cancellation regression-tested; broader pass remains) | 60–90 | | — | Hardening at scale (big-file corpus, fuzzing, cross-platform + browser QA) | 🟡 PngSuite integrity and bounded fetching verified (#1729); real-world corpus/manual QA remain | 50–80 | | M14 follow-up | Color Picker layout (#2008) | ✅ Compact controls, centered header, stacked actions, aligned fields and screen sampling; narrow windows scroll vertically | Included above | @@ -217,6 +220,7 @@ not take the artwork yet. Overflow-menu drag remains separate. Scores and hours |---|---|---| | 2026-11-17 | minor | PDF import (#8300): a glyph filled only (text rendering mode 0) right after one filled and stroked (mode 2) joined the stroked run and came in stroked too: `2 Tr (B) Tj 0 Tr (C) Tj` came in as `BC` stroked throughout. A glyph filled only now joins only a run drawn alike, so it starts a run of its own, filled only, in the same type object, and takes a stroke only when the file draws one over it (the #8015 matching); a word filled whole then stroked whole, and fill and stroke rendering glyph by glyph, still come in as one run filled and stroked. Tests: `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked`, `glyphs_filled_and_stroked_one_by_one_stay_one_run`; scores and estimates unchanged. | | 2026-11-17 | minor | PDF import (#8015 follow-up): type filled and stroked at less than full opacity is no longer joined into one type object, since the file composites the fill and the stroke apiece, darker where they overlap, while one object's opacity applies to both together; it stays a filled object and a stroked one, as a fill and stroke at different opacities already did. An upright glyph (vertical type) filled and stroked is no longer kept as an outline for a line that comes in as its outlines, as glyphs filled only weren't, so such a line can't lose them. The #8015 entries now say what is left: translucent type filled and stroked, and a `TJ` whose kerning starts a new line part way through, still come in as two objects. Tests: `translucent_fill_and_stroke_text_stays_two_objects`, `a_vertical_line_with_one_glyph_filled_and_stroked_keeps_every_glyph_filled`; scores and estimates unchanged. | +| 2026-11-16 | minor | M1: an Alt-drag in the Layers panel copies a row above or below its own place (`layer.move` with `copy` and that row as the target), so the top layer dragged up, the bottom layer dragged down and a document's only layer are copied (#8237). Scores and estimates unchanged. | | 2026-11-16 | minor | PDF import: fill and stroke rendering (text rendering modes 2 and 6) draws all the glyphs of a text-showing operator (`Tj`, `TJ`, `'`, `"`) filled, then the same glyphs stroked, so a word shown at once came in as two type objects: a stroke-only copy over a fill-only one. Each stroke is now matched, in order, to the glyph filled with the same placement (where, how large, how wide, slanted and turned) in the same font with the same text on the line, and only that glyph takes the stroke, so the word comes in as one type object, filled and stroked; glyphs stroked with another join part way through still split into runs of their own, and stroked type over no filled glyph (modes 1 and 5) stays stroke only (#8015; `a_word_filled_then_stroked_imports_as_one_filled_and_stroked_type` in `crates/pdf/src/tests/textstroke.rs`, `a_vertical_column_filled_then_stroked_is_one_filled_and_stroked_type` in `crates/pdf/src/tests/text_placement.rs`). Scores and estimates unchanged. | | 2026-11-16 | minor | M1: rows or the selected-art square dragged over the Layers panel's list show the copy cursor while Alt is held, as the drop then copies, and the grabbing hand otherwise (#8217). Scores and estimates unchanged. | | 2026-11-16 | minor | Gradient panel: the strip under the ramp, where a click adds a stop, shows the white arrow with a plus on Windows and X11, where the system copy cursor showed as the plain arrow (#8241). Scores and estimates unchanged. | @@ -235,11 +239,13 @@ not take the artwork yet. Overflow-menu drag remains separate. Scores and hours | 2026-11-12 | minor | M14: numeric fields keep the caret when a focus click is released more than 1 pt from its press; a tap within 1 pt still selects all (#6659, follow-up to #1326); estimates unchanged. | | 2026-11-12 | minor | M12: Live Paint Bucket fills faces crossed in one drag (#6373). Scores and estimates unchanged. | | 2026-11-12 | minor | Save refusal follow-up (#6146): changed format opens its Save options; unchanged format retains original options. Focused UI regressions passed, including the format-change case that failed before the fix; native panel acceptance pending. Scores and estimates unchanged. | +| 2026-11-12 | minor | #6625 cap/join follow-up: hidden-fill and no-fill stroke hits must respect their cap/join geometry; focused CPU regressions passed. Existing fill-stack evidence, scores and estimates unchanged. | | 2026-11-11 | minor | Eyedropper copies effective character dimensions between transformed text objects (#6404); scores and estimates unchanged. | | 2026-11-11 | minor | Ordinary Save to a location refusing writes offers Save As (#6146); cancellation preserves the original path and modified state; automation receives READ_ONLY_LOCATION. Scores and estimates unchanged. Validation pending. | | 2026-11-11 | minor | M10/G5: Energy Beams built-in brush library; MCP docs catch-up; estimates unchanged | | 2026-11-11 | minor | M10/G5: Skill Icons built-in symbol library; MCP docs catch-up; estimates unchanged | | 2026-11-11 | minor | Eraser: fixed and varied tips and the Alt-drag marquee cut fill-only open contours and compound holes as areas; stroked open paths retain main behavior (#6582). Scores and estimates unchanged. | +| 2026-11-11 | minor | #6625: path and compound-path interior hits follow enabled non-None fill rows, including lower fills beneath a top None row; hidden-only interiors miss; zero-opacity fills remain selectable. Scores and estimates unchanged. | | 2026-11-10 | minor | M10/G5: Status Effects built-in graphic style library; MCP docs catch-up for UI Frames and Map Markers; estimates unchanged | | 2026-11-10 | minor | M10/G5: Inventory Icons built-in symbol library (Sword, Shield, Potion, Key, Gem); estimates unchanged | | 2026-11-10 | minor | M7: the Edit Custom Dictionary dialog (#4936); the Check Spelling dialog remains; scores and estimates unchanged. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0ebebfa2c5..c83c1fc4e0 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-17 · **Change:** minor (Twist: a strongly twisted path joins its pieces without kinks, #7069; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; Layers panel: Alt over the list shows the copy cursor while rows or the selection square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Properties panel: the Character section shows the font of the Type tool's selection, not the first run's (#8189); scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter, so a top object saved with its sides' curves in pieces draws as its `.ai` drawn art, #7097; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (PDF export writes the document language as the catalog's `/Lang`, #3644; Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Twist: a strongly twisted path joins its pieces without kinks, #7069; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; Layers panel: Alt over the list shows the copy cursor while rows or the selection square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Properties panel: the Character section shows the font of the Type tool's selection, not the first run's (#8189); scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter, so a top object saved with its sides' curves in pieces draws as its `.ai` drawn art, #7097; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > @@ -10,6 +10,8 @@ > > Live Paint Bucket update (2026-11-12): one drag fills the faces crossed in the same group (#6373). > +> Selection update (2026-11-11): path and compound-path interiors follow enabled non-None fill rows, including lower fills beneath a top None row (#6625). Hidden-only interiors miss; zero-opacity fills remain selectable. Cap/join follow-up (2026-11-12): hidden-fill and no-fill stroke hits must respect cap and join geometry; focused cap/join CPU regressions passed. Scores and estimates unchanged. +> > Vector Halftone preview update (2026-11-10): temporary dot selection marks are hidden, and the bounding box stays available (#6369). > > **Eraser fill update (2026-11-11):** filled open paths without a visible painted stroke retain fill outside the sweep or Alt-drag marquee (#6582); stroked paths retain main behavior; scores and estimates unchanged. @@ -63,6 +65,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-18 | minor | Hardening: PDF export writes the document language (Document Setup) as the catalog's `/Lang` and XMP `dc:language` (#3644). Scores and estimates unchanged. | | 2026-11-17 | minor | Distort & Transform › Twist: handles follow the rotation's derivative, so a strongly twisted path is a smooth spiral instead of pieces meeting at kinks (#7069; `twist_joins_its_pieces_smoothly` in `crates/effects/src/tests.rs`). Scores and estimates unchanged. | | 2026-11-17 | minor | PDF import (#8300): a glyph filled only (text rendering mode 0) right after one filled and stroked (mode 2) joined the stroked run and came in stroked too: `2 Tr (B) Tj 0 Tr (C) Tj` came in as `BC` stroked throughout. A glyph filled only now joins only a run drawn alike, so it starts a run of its own, filled only, in the same type object, and takes a stroke only when the file draws one over it (the #8015 matching); a word filled whole then stroked whole, and fill and stroke rendering glyph by glyph, still come in as one run filled and stroked. Tests: `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked`, `glyphs_filled_and_stroked_one_by_one_stay_one_run`; scores and estimates unchanged. | | 2026-11-17 | minor | PDF import (#8015 follow-up): type filled and stroked at less than full opacity is no longer joined into one type object, since the file composites the fill and the stroke apiece, darker where they overlap, while one object's opacity applies to both together; it stays a filled object and a stroked one, as a fill and stroke at different opacities already did. An upright glyph (vertical type) filled and stroked is no longer kept as an outline for a line that comes in as its outlines, as glyphs filled only weren't, so such a line can't lose them. The #8015 entries now say what is left: translucent type filled and stroked, and a `TJ` whose kerning starts a new line part way through, still come in as two objects. Tests: `translucent_fill_and_stroke_text_stays_two_objects`, `a_vertical_line_with_one_glyph_filled_and_stroked_keeps_every_glyph_filled`; scores and estimates unchanged. | @@ -253,7 +256,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Area | Weight | Done | Main gaps | One agent (h) | Kind | |---|---:|---:|---|---:|---| -| Selection, transform & align tools | 6 | 85% | Direct Selection segment click/Delete corrected (#1278); deletion splits an ordinary contour into selected sibling objects with bounds-fitted gradients kept in place (#3380, deletion only; `crates/engine/tests/it/delete_path_pieces.rs`); open-path anchor Delete keeps gaps; Select › Start Global Edit finds the paths, compound paths and symbol instances of the selected object's shape (Appearance, Size and artboard options) and gives an edit of one to all of them in proportion, as one undo step (#3521), and on a group the groups like it, an edit inside one reaching the same object in the others (#4939), and a Shift-click on a highlighted match leaves it out; the Align panel menu's Align to Glyph Bounds › Point Text and Area Text measure type by its glyphs' ink for Align and Distribute (#4231); remaining: Free Transform/Scale/Reflect along a rotated box, Global Edit of rotated copies, transform nuances (no-op anchor Align history regression-tested, #1180 follow-up) | 4–6 | estimated; Global Edit regression-tested (`crates/engine/src/tests/globaledit.rs`; Quick Action, menu label and Escape in `panels::properties::tests::start_global_edit_quick_action_and_escape`) | +| Selection, transform & align tools | 6 | 85% | Direct Selection segment click/Delete corrected (#1278); deletion splits an ordinary contour into selected sibling objects with bounds-fitted gradients kept in place (#3380, deletion only; `crates/engine/tests/it/delete_path_pieces.rs`); open-path anchor Delete keeps gaps; Select › Start Global Edit finds the paths, compound paths and symbol instances of the selected object's shape (Appearance, Size and artboard options) and gives an edit of one to all of them in proportion, as one undo step (#3521), and on a group the groups like it, an edit inside one reaching the same object in the others (#4939), and a Shift-click on a highlighted match leaves it out; the Align panel menu's Align to Glyph Bounds › Point Text and Area Text measure type by its glyphs' ink for Align and Distribute (#4231); remaining: Free Transform/Scale/Reflect along a rotated box, Global Edit of rotated copies, transform nuances (no-op anchor Align history regression-tested, #1180 follow-up) | 4–6 | estimated; fill-stack selection regression-tested (`crates/engine/tests/path_fill_hits.rs`, #6625); cap/join follow-up CPU regressions passed; Global Edit regression-tested (`crates/engine/src/tests/globaledit.rs`; Quick Action, menu label and Escape in `panels::properties::tests::start_global_edit_quick_action_and_escape`) | | Drawing tools (Pen, Curvature, Pencil, shapes, Shaper) | 7 | 85% | Shaper construction widget, Pencil/Pen nuances, Blob Brush options, Touch Type, Dimension tool; see [ui-parity.md](ui-parity.md) | 8–13 | estimated; Curvature point display regression-tested (#1236, in part); Polygon/Star exact-size count persistence regression-covered; Live Corners' Relative rounding done (#3091), score unchanged; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123), score and hours unchanged; the Pen, Smart Pen and Curvature tool show the measurement readout with the rubber band off (#7043), score, gaps and hours unchanged; Eraser preserves fill-only open-path area outside fixed and varied tip sweeps and Alt-drag marquees, including compound holes; clipping masks keep their remaining contours and empty-mask role; ordinary Group/Layer paints and evaluated gradient placements are preserved when the stored paint reproduces their appearance; replacement-art effects, plug-ins/Rasterize, along/across-stroke gradients and placements that cannot be reproduced keep their existing fitting; stroked open paths retain main behavior and result structure (#6582; `crates/engine/tests/eraser_open_fill.rs`), score and hours unchanged | | Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 80% | Shape Builder on the reporter's file (#937: art past 4,096 segments is cut by lines again; unconfirmed on the file itself); gap detection shares Live Paint’s finder, with a 72 pt custom cap and the existing options; Live Paint Gap Options | 4–8 | estimated; Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog (lowered from 86%: open issues); compound attributes regression-tested (#1197); single-result source names survive SVG export/import (#1293), with [SVG ID semantics](https://www.w3.org/TR/SVG2/struct.html#IDAttribute) and original-shape tests; Simplify component selection and preview regression-tested (#1272); Simplify of a Direct Selection part of a path regression-tested (`tests/simplify_part.rs`); Divide open-cutting-path geometry and appearance regression-tested (#1307); the Shape Builder's edge-source grid is bounded in memory and files a segment once per cell (`planar.rs` test `rect_index_holds_a_bounded_number_of_references`); live compound shapes (Make, Alt-click, member Shape Modes, Release, Expand, saved and exported) regression-tested (#4522); Live Paint Bucket face drags, including narrow faces and one Undo, regression-tested (#6373) | | Colour, swatches, gradients, patterns, mesh, recolor | 7 | 92% | Picker Lab entry, picker libraries and Assign-row menus complete the deferred #4028 UI paths (#8031); scores and estimates unchanged; Eyedropper copies effective character dimensions across text transforms (#6404); 30.0's gradient additions are done (dither, perceptual blending, presets); freeform gradients in SVG/PDF, mixed spot/process gradients in SVG, PDF gradients mixing a spot color with RGB or Lab stops, and dithered spot gradient fills and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, which PDF export writes as images in process colors| 4–7 | estimated; Recolor model selection is available through the engine and MCP (#2520), and the dialog's color sliders (HSB, RGB, CMYK, Lab, Tint for a spot color) edit the selected row's new color in its mode, and the Edit tab's Global Adjust sliders (Saturation, Brightness, Temperature, Luminosity, -100% to 100%) change every recolored color at once (lowered from 96%: target moved); unpainted zero-width stroke restoration fixed (#1253), score and hours unchanged; Eyedropper source reads regression-tested (#1251); screen-bounded Recolor Edit chip list (#3416), score and hours unchanged; a point on a gradient mesh's outline locates on its edge on every side (#7006: `mesh_locate_takes_a_point_on_any_side_of_the_outline`, `mesh_add_line_exactly_on_the_edge_needs_no_tolerance`), score and hours unchanged; Color panel spectrum grows with the resized panel (#8005) | @@ -534,7 +537,7 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale) | Raster effects (Effect Gallery, Document Raster Effects Settings) | 4 | 35% | ~36 Photoshop-style filters (Artistic, Brush Strokes, Sketch, Stylize) and Texturizer's Load Texture (since done, see the area table above, as is the Effect Gallery, #2883); Document Raster Effects Settings, raster effects in PDF, the pixel-filter pipeline, Radial Blur, Smart Blur (Normal, Edge Only and Overlay Edge), Unsharp Mask, Glowing Edges, Distort (Diffuse Glow, Glass, Ocean Ripple), Pixelate (Color Halftone, Crystallize, Mezzotint, Pointillize), Texture (Craquelure, Grain, Mosaic Tiles, Patchwork, Stained Glass, Texturizer) and Video (De-Interlace, NTSC Colors) are done | 8–14 | | 3D and Materials | 4 | ~25% | Initial Revolve, Extrude & Bevel, Inflate and Rotate, with simple lighting and four original lighting presets; materials, shadows, ray tracing, Rotate (Classic), Map Art and more complete visibility remain | 25–45 | | Type advanced | 4 | 50% | CJK composition for vertical type (mojikumi beyond Line-end Punctuation Half Width — the other sets (and their paragraph-start bracket and indent rules), custom kinsoku sets (beyond Hard, Soft and None) and the Mojikumi Settings dialog —, manual tate-chu-yoko is done, its up/down settings remain; No Break is done), tab leaders, Touch Type, Retype; vertical point/area/path type and Type Orientation have initial support (beyond parity, not scored: inline symbols in text) | 20–28 | -| Type core | 9 | 80% | Middle Eastern features beyond bidi layout, Paragraph Direction, digit types and Kashidas (editable bidirectional SVG text, a split caret where directions meet; the Middle Eastern & South Asian composers are done, #4935, but `.ai`/EPS/PDF files carry no composer); paint-only harakat keep joining with conditional GDEF-mark colour ownership, but fonts without GDEF mark classes and some AAT/`morx` ligatures can still leave marks painted as their letters; Every-line Composer fidelity for justified and ragged text (available per object; mixed type sizes in a paragraph still break single-line in non-rectangular area type and with text wrap), Optical Margin Alignment, paragraph spacing limit for vertically justified area type, hidden characters, paragraph attributes in the Type tool's copy and paste (the characters keep their styles, the paragraphs take the destination's), mixed-value display in the Paragraph panel for a selection across differing paragraphs, partial selection of type-area anchors by marquee, optional font-size preservation during group scaling (scaled character controls fixed in #1034). Hyphenation and Justification options, Fractional Widths, System Layout, styled Type-range canvas Paste (#5636), and pattern hyphenation for eleven Indian languages with grapheme/cluster protection (#4947) are done; Sanskrit automatic patterns remain pending an allowlisted source | 14–19 | +| Type core | 9 | 80% | Middle Eastern features beyond bidi layout, Paragraph Direction, digit types and Kashidas (editable bidirectional SVG text, a split caret where directions meet; the Middle Eastern & South Asian composers are done, #4935, but `.ai`/EPS/PDF files carry no composer); paint-only harakat keep joining with conditional GDEF-mark colour ownership, but fonts without GDEF mark classes and some AAT/`morx` ligatures can still leave marks painted as their letters; Every-line Composer fidelity for justified and ragged text (available per object; mixed type sizes in a paragraph still break single-line in non-rectangular area type and with text wrap), Optical Margin Alignment, paragraph spacing limit for vertically justified area type, paragraph attributes in the Type tool's copy and paste (the characters keep their styles, the paragraphs take the destination's), mixed-value display in the Paragraph panel for a selection across differing paragraphs, partial selection of type-area anchors by marquee, optional font-size preservation during group scaling (scaled character controls fixed in #1034). Hyphenation and Justification options, Fractional Widths, System Layout, styled Type-range canvas Paste (#5636), and pattern hyphenation for eleven Indian languages with grapheme/cluster protection (#4947) are done; Sanskrit automatic patterns remain pending an allowlisted source | 14–19 | | Symbols, blends, envelopes, Repeat, perspective | 5 | 90% | further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons and Weather Icons are done), dynamic symbols' `.ai` round trip, envelope Anti-Alias/Preserve Shape output and warp point editing, brush interpolation in blends (M8 fidelity pass done); Symbol Options › Registration and Export Type and on-canvas dynamic part paint (gradient/pattern, opacity, blend) are done; symbol editing shows draggable 9-slice guides (#5280), while guides outside the artwork remain unsupported | 4–7 | | Image Trace, graphs, image tools | 3 | 72% | graph Column designs (Graph Design, Marker designs and series colours set with Group Selection are done), Create Object Mosaic, per-feature stroke/fill choice and varying widths in Image Trace's Create Strokes (Vector Halftone and the Image Trace View modes, Palette and Create Strokes are done) | 6–10 | | Layers, artboards, document setup | 5 | 82% | Layers panel: a confirmation before deleting layers that hold art, row menu commands beyond Collect for Export (now on every layer, sublayer, group and object row), menus on guide and blend spine rows, the Layer Options dialog for several rows with mixed values, Paste Remembers Layers for sublayers; artboard preset polish (artboard escape routing and document setup modal handoff done; Move Artwork for artboard X/Y edits, Rearrange All Artboards, Document Setup, New Document and the rest of the Layers panel are done) | 4–7 | @@ -549,7 +552,7 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale) | Libraries, Links, Package | 2 | 82% | the Libraries panel is local only (no cloud by design: libraries are files on this machine) and has no shared libraries, linked graphics or gradients and patterns as items yet; its graphics, colours and text styles (#745), its search, groups and library export/import as `.vclibrary` files (#926), a list that scrolls, with items and groups reordered by dragging and items dragged into and out of groups, art and swatches dragged in added where they are dropped, and items shown as icons or in a list with their names, are done; Links and Package are done; placed VectorCraft documents are done (linked by default, vectors in every output, previews, Break Link, Expand, Edit Original, refresh on save) | 2–3 | | **Feature parity** | **103** | **~75%** | | **~210–330** | | Interaction-fidelity pass (side by side with Illustrator: every tool modifier, cursor, dialog, Properties context) | | | | 60–90 | -| Hardening (big-file corpus, fuzzing, cross-platform and browser QA, accessibility, packaging) | | | Bounded control socket waits (#1726); PngSuite pinned-file integrity and download budgets verified (#1729); RPM runtime capabilities and glibc floor checked (#1275); titled PDF exports ask viewers to display the document title (#3646); real-distro installation/start-up QA pending | 50–80 | +| Hardening (big-file corpus, fuzzing, cross-platform and browser QA, accessibility, packaging) | | | Bounded control socket waits (#1726); PngSuite pinned-file integrity and download budgets verified (#1729); RPM runtime capabilities and glibc floor checked (#1275); titled PDF exports ask viewers to display the document title (#3646); PDF exports give the document language as the catalog's `/Lang` (#3644); real-distro installation/start-up QA pending | 50–80 | | **Full parity** | | **~56%** | | **~320–500** | _Inventories (2026-10-07):_ 13 menu items still stubbed (`todo(…)` in `crates/ui-egui/src/menus.rs`); every tool @@ -591,11 +594,14 @@ since 2026-10-01. ## Evidence: what ships today, by area - `object.setBounds` uses the same reference point for whole-number integer and floating-point values, including `0` and `0.0`. It rejects negative and fractional indices without changing geometry, selection, or undo history. An omitted or null reference uses the center, and whole-number references above 8 use point 8. Object and direct-anchor selections follow these rules (`tests::bboxrotate::set_bounds_whole_number_references_match_integer_references`, `set_bounds_rejects_invalid_references_without_changes`). +- Twist keeps boundary handles tangent to the rotation inside its outer circle. Regressions cover 90, 400, and -720 degree twists, unchanged boundary anchors, and a sampling midpoint that rounds to an endpoint at large coordinates (`twist_boundary_handles_follow_the_inward_tangent` and `a_midpoint_rounded_to_an_endpoint_keeps_the_handle_direction`). - **Recolor picker follow-up (#8031/#4028):** native Lab numeric entry, document/loaded-library swatches in the Color Picker, and Assign-row Pick from Swatches / Limit to Library menus. #4090 provided the double-click picker and #5113 the Assign sliders. Regression tests `native_lab_entry_in_color_picker` and `row_context_menu_pick_from_swatches_and_limit_to_library` exercise the fields and menu callbacks rather than writing their result state. Area score and hours unchanged. - **Save refusal (#6146):** ordinary File > Save to its own location offers Save As after a terminal permission/read-only refusal, suggesting the original name and format, preserving options for the unchanged format and opening the chosen format’s Save options on a change. Cancel keeps the failed-save state. Busy pickers, recovery-copy errors, other failures, explicit destinations and Close/Quit keep the existing dialog. Engine, UI and MCP regression cases are in `cmd/fileio/tests_readonly.rs`, `io/tests_read_only_save.rs` and MCP `tests/fileio.rs`; focused UI regressions passed; engine regression execution and native panel acceptance pending. Scores and hours unchanged. +**Selection fill eligibility (#6625):** Path and compound-path interiors use any enabled non-None fill row (#6625). A lower visible fill remains selectable beneath a top None row in the same object; hidden-only and true-None interiors miss. Zero-opacity fills remain selectable. Original CPU-render and document-hit regressions in `crates/engine/tests/path_fill_hits.rs` cover seven Path and five Compound cases, including stroke edges, geometric outlines, Outline/path-only modes and compound holes. Hidden-fill and no-fill stroked paths must respect butt, round and square caps and bevel, round and miter joins. Focused cap/join CPU regressions passed. Scores and estimates unchanged. + - **PDF authored replacement text (#6165):** `crates/pdf/src/tests/actual_text.rs` covers replacement once with suffix placement, PDF text-string decoding, empty and nested owners, sibling spans, page reset, multiple text-show operations, style/line changes, fill-and-stroke, reader windows and bounded input. Authored logical-order stretches are protected while adjacent ordinary text still undergoes reconstruction. The replacement takes its first placed glyph's style and line; its characters are not redistributed over later lines/styles. Exact mixed-direction paragraph layout is not claimed. No export changes; scores and hours stay at 75% / 10–20 h. - **PDF stroked type (#7741):** `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs` covers round, projecting and butt caps, round, bevel and miter joins and a miter limit of 3 on type stroked in rendering modes 1, 2, 5 and 6, shown as a word, a glyph at a time and under `ActualText`; glyphs stroked with another join as runs of their own; and a glyph filled and stroked after one stroked otherwise, which keeps the join of the glyph before it. Synthetic PDFs written in the test (standard Helvetica, not embedded); no fonts or fixtures added. The dash array is not yet carried to the characters. @@ -633,6 +639,7 @@ since 2026-10-01. **Drawing tools, Dimension tool second point without construction guides through a first point off the anchors:** By VectorCraft's own rule, with Smart Guides on, the second Linear point does not snap to the construction guides through a first point that is not on an anchor, so a click beside a segment straight below such a first point lands on the segment; after a first point picked on an anchor, the construction guides through it still apply. The second point still snaps to anchors, centers and alignment lines, and with Snap to Perpendicular or Snap to Tangent on, it lands where the line from the first point meets a segment square or grazes a curve. `a_point_on_a_guide_stays_on_the_guide`, `the_second_point_after_an_anchor_lands_on_construction_guides`, `the_second_point_lands_square_to_a_segment_or_grazing_a_curve` and `linear_picks_show_and_snap_to_smart_guides` cover it. **Drawing tools, Dimension tool points land on dimensions already drawn (#8063):** By VectorCraft's own rule, with Smart Guides or Snap to Point on, a Linear point that no anchor of the art within 8 pixels takes lands on the end of a visible, unlocked dimension's dimension line, or on the far end of its extension line, within 8 pixels, and a point that nothing else places lands on the closest point of such a line within 8 pixels, so at any zoom a dimension can start where another one ends. The end of an extension line next to the point it measures does not pull points away from that anchor. With Smart Guides and Anchor/Path Labels on, a point on an anchor or line end shows the "anchor" label and a point on a segment or line shows the "path" label. `linear_picks_land_on_anchors_paths_and_drawn_dimensions` and `an_anchor_beside_a_drawn_dimension_takes_the_point` cover it. **Drawing tools, Dimension tool dimensions selected with their art keep their lines and label:** Object › Expand, Object › Expand Appearance and Object › Path › Outline Stroke leave a dimension selected with art it measures, directly or in selected groups without fills, strokes or effects of their own, as it is and change only the other art; when the new art no longer fits its link, the dimension stays where it was, no longer linked, and undo links it again. `expand_leaves_a_dimension_selected_with_its_art_as_it_is`, `expand_appearance_leaves_a_dimension_selected_with_its_art_as_it_is`, `outline_stroke_leaves_a_dimension_selected_with_its_art_as_it_is`, `a_dimension_selected_with_art_that_has_nothing_to_expand_changes_nothing`, `a_group_effect_expanded_reaches_the_dimension_it_holds`, `expand_keeps_a_dimension_in_its_asset_and_its_variable_binding`, `a_dimension_keeps_no_link_to_the_art_expand_replaced`, `a_dimension_outlasts_the_art_outline_stroke_or_expand_appearance_replaced`, `a_dimension_outlasts_the_stroke_expand_outlined` and `expand_appearance_in_safe_mode_leaves_a_dimension_selected_with_its_art` cover it. +**Drawing tools, Dimension tool Arrow Style shows each arrowhead (#8049):** The Arrow Style dropdown in Dimension Tool Options and in the Properties panel's Dimension section draws each style's arrowhead at the end of a short line before its name, in the open list and in the closed field, using the Stroke panel's arrowhead previews. Filled, Open, Tick and None are the same four styles, saved as before. `arrow_style_shows_a_drawn_arrowhead` and `each_arrow_style_draws_its_stroke_arrowhead_at_both_ends` cover it. **Drawing tools, Line Segment from one curve onto a common tangent of another:** By VectorCraft's own rule, with Smart Guides and Snap to Tangent on, a Line Segment drag pressed anywhere on a convex closed path with curves and dragged to within the snapping tolerance of another such path lands on a common tangent of the two ([tangent lines to circles](https://en.wikipedia.org/wiki/Tangent_lines_to_circles)): both ends move to where the line touches the paths, the start sliding along the first path, and each end shows the "tangent" label when Anchor/Path Labels is on, with the line drawn as a guide when Alignment Guides is on. The line is the tangent whose touch point on the second path is nearest the pointer, so moving the pointer around the second path switches between the outer tangent and the one crossing between the paths. The start stays where it was pressed when Shift, Alt or Space is held, when an anchor, center or crossing lies nearer the pointer than the second path does, when the press snapped to an anchor, center or crossing off the first path, when Snap to Tangent is off, when Snap to Grid or pixel snapping places drawn points, or when either path bends inward somewhere or has more than 512 segments. `a_line_from_one_circle_to_another_lands_on_their_common_tangent`, `a_line_from_a_turned_ellipse_lands_on_its_tangent_with_a_circle`, `a_line_near_the_second_path_takes_the_tangent_touching_it_nearest`, `a_line_keeps_its_start_without_a_tangent_snap`, `a_line_to_a_crescent_or_from_an_anchor_beside_the_curve_keeps_its_start` and `a_line_segment_drag_draws_the_common_tangent_as_one_undo_step` cover it. **Live trace result bounds and selection highlights exclude the retained bitmap except in source-image views:** `live_trace_result_bounds_exclude_the_retained_bitmap_at_any_angle` checks every TraceView, geometric and visual bounds and rotated result bounds. `live_trace_selection_highlight_excludes_the_retained_source_rectangle` checks result highlights and the existing ordinary-group policy. Shared editing-child traversal also preserves Shaper handling. **Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards:** Shared existing preset definitions are reused; no external preset assets are added. Presets preserve each selected artboard's orientation, and orientation choices apply even when the active board already matches. Fit operations draft bounds until OK, affect only the active artboard and leave artwork in place. Regression coverage checks draft/Cancel, selected-set application, active-only fitting and Undo. @@ -643,6 +650,7 @@ since 2026-10-01. - **Clipped bottom-bar text (#6622):** A Help Bar hint wider than the window, such as the Dimension tool's hint in an 800-point window, ends in an ellipsis, as the status message does. In a narrow status bar the tool name ends in an ellipsis and leaves the status message its room. Resting the pointer on a clipped hint, tool name or message shows the full text in a tooltip that wraps within the window. Text that fits shows no tooltip, and screen readers receive the full text. Scores and estimates are unchanged. - **Notes of an open in the status bar:** After File › Open the status message names the first note that says reading the file left something out (the notes that make Save ask before writing over the file), else the first note, and counts them all. With several notes, resting the pointer on the message lists them in that order, as many as fit in the window and at most 30, then how many more. Screen readers receive the list after the message. Scores and estimates are unchanged. - **Notes of a save or an export in the status bar:** After Save, Save As, Save a Copy, Save as Template, Save a Timestamped Copy, Save as PDF, Export As, Export Selection, Export for Screens, Asset Export, Save for Web, Preview in Browser, Save for Office Documents, Text Export Options, a print to a file or the CSS Properties panel's export, the status message names the first note and counts them all. With several notes, resting the pointer on the message lists them in the order the reply gives them (a save's notes start with what the format loses), as it lists an open's notes. Scores and estimates are unchanged. +- **Notes of a Copy, a Cut or an Image Trace in the status bar:** After Copy or Cut (also of artboards and of text in the Type tool) writes its formats to the system clipboard, and after Image Trace's Make or Make and Expand, the status message names the first note and counts them all. With several notes, resting the pointer on the message lists them in the order they were made, as it lists a save's notes. A message shown while the clipboard formats were being made stays in place of the Copy's or Cut's notes. A Copy, Cut or trace without notes clears the notes message that an earlier one left, and leaves any other message. A trace that makes no paths shows its first note without the count. Scores and estimates are unchanged. - **What a save or an export loses, named first:** Each writer marks its notes as a loss (something of the document the file leaves out or writes differently) or a note on the options (an option it didn't apply or applied another way while the art reaches the file as it looks, or something an option turns off). The replies of the save and export commands list the losses first, each kind in the order given, across every file an export writes. The status message after a save or an export then names a loss when there is one: a WebP export of type in a font that isn't installed, given an option WebP doesn't read (`interlaced`), names the fallback-font note instead of the note on that option. A print to a file and the print preview list theirs the same way: art outside the imageable area, type in a fallback font and transparency flattened for PostScript come before notes such as a fixed flatness that isn't written or copies per sheet that don't fit. Scores and estimates are unchanged. - **Canvas review follow-up:** Cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission. Controlled-worker regression checks oversized width and height, high DPI and the render transform without allocating oversized images. Scores and estimates are unchanged. @@ -683,6 +691,7 @@ since 2026-10-01. - **EPS writes a repeated freeform gradient's image once:** a freeform gradient whose image samples the same on more than one fill (copies of a shape moved with their points, or one shape in a symbol's instances) has its samples written once in the setup, as a repeated image's are, and a fill whose image differs (other colors, another size) gets its own. A freeform fill drawn once is written where it is drawn, as before, and a fill whose placement cannot be drawn, or that arrives when the page is already at the 256 MB limit, is no longer sampled first (eps `tests::a_freeform_gradients_image_drawn_twice_writes_its_samples_once`, `tests::freeform_gradients_sampled_differently_dont_share_an_image`, `tests::a_field_taken_back_at_the_page_limit_leaves_no_image_behind`). Scores and hours unchanged. - **EPS releases the images of art left out at the page limit:** art taken back because it passes the 256 MB limit on the page no longer keeps the encoded samples of the placed images, colorized images and freeform fills it drew, and an image whose first placement does not fit under the limit is not kept after it is encoded. Later placements of that image are left out with the same warning without encoding it again while it still does not fit; once art taken back leaves room, it is encoded again and written where it is drawn. The page the EPS file draws is the same as before; a repeated image or field written after art taken back can take a lower resource number in the setup (eps `tests::a_rolled_back_node_frees_its_image_codes`, `tests::a_rolled_back_image_does_not_pin_an_earlier_field_code`, `tests::an_image_rejected_by_the_page_limit_keeps_no_unused_code`, `tests::an_image_rejected_by_the_page_limit_is_encoded_once`, `tests::an_image_rejected_in_art_taken_back_is_encoded_again_when_it_fits`). Scores and hours unchanged. - **PDF writes a warped image once:** with downsampling on, the pieces of an image bent by a Warp effect are resampled for the widest and the highest size any piece places the image at, so every piece paints one image XObject (a colorized image: one colorized image and its soft mask), instead of one image for each size a piece is placed at. Another placement of the same image is still resampled for its own size. Without downsampling, a colorized image and a CMYK image with a grayscale image mask on its grid are decoded and encoded once for all the sizes they are placed at (pdf `tests::compression::a_warped_image_is_written_once_for_all_its_pieces`, `tests::colorize::a_colorized_warped_image_is_written_once_for_all_its_pieces`, `export::images::tests::colorized_and_grid_masked_images_are_made_once_for_every_size_without_downsampling`). Scores and hours unchanged. +- **PDF import reads a Type 3 font's glyph procedures once:** a Type 3 font that many pages or forms list, each in a font dictionary of its own, has its glyph procedures checked for glyphs that set their own color once for the document, when the font is first noted, instead of again on every page and form. The pages open as before (pdf `tests::import_fidelity::a_type3_font_on_every_page_has_its_glyph_procedures_read_once`). Scores and hours unchanged. - **Distort Appearance with Transform effect options:** with Envelope Options › Distort Appearance on, a path whose Transform effect has Scale Strokes & Effects or Transform Patterns on, or copies it with a gradient, is bent as the same per-copy art it draws and expands as outside the envelope: each copy's own stroke weight, dashes, pattern placement and gradient (effects `bake::tests`). Scores and hours unchanged. - **Fitted gradients turn with the Transform effect:** a gradient fitted to the object (not placed with the Gradient tool) turns, reflects and stretches with the object when its Transform effect rotates, reflects or scales it unevenly, as Object › Transform already does: the gradient is fixed to its fit on the geometry the effect takes, then follows the effect and the effects after it as a placed gradient does. Under moves and even scales it draws as a refit does, and a Transform effect that scales the object to nothing across leaves it fitted, with Scale Strokes & Effects or Transform Patterns on too, and on each copy. This holds on the canvas and in Object › Expand of the fill, for an object's own effects, a fill's or stroke's own, and a group's, where the gradients fitted to its paths, to its own fill, to the groups inside it and to its images' and symbol instances' own fills each fix to their own object's fit. Existing documents with such a Transform effect on fitted-gradient art draw differently: before, the gradient refit to the turned outline. The Gradient tool still shows a fitted gradient's vector at its unturned fit. How gradients follow the effect is VectorCraft's own rule; what the effect does to the object is described in [Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html) (effects `bake::tests::a_fitted_gradient_turns_reflects_and_stretches_with_a_transform_effect`, `bake::tests::a_transform_effect_that_scales_to_nothing_leaves_a_fitted_gradient_fitted`, `group::tests::a_groups_transform_turns_the_gradients_fitted_to_its_members_and_its_own_fill`; render `objectfx::a_fitted_gradient_turns_and_reflects_with_its_transform_on_the_canvas`; engine `objexpand::a_fitted_gradient_turned_by_a_transform_expands_as_the_canvas_draws_it`). Scores and hours unchanged. - **Placed gradients follow Transform and Free Distort effects:** a gradient placed with the Gradient tool moves, turns and scales with the object when the object's Transform effect moves its outline, and each copy of the Transform effect takes it as many times as it takes the transform. Under Free Distort it moves and scales from the path's bounds before the effect to its bounds after it. This holds on the canvas, in export, in Expand Appearance, in Pathfinder and compound shapes, and in Object › Expand of the fill, for an object's own effects, a group's (the own fills of the group, of the groups inside it, of a symbol's art, and of the images and symbol instances it moves, included) and a fill's or stroke's own. A gradient on a path inside a group with a Transform effect now moves with the path (#2214 moved only the gradients of type), and so does a gradient on an image's or symbol instance's own fill. When a path keeps its shape because the effect would pass the geometry budget, the group's own gradients stay in place; a hidden path in a layer, which the layer's bounds leave out, does not hold them. A freeform gradient whose points were edited moves its points in the same way. How gradients follow each effect is VectorCraft's own rule; what each effect does to the object is described in [Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html) (effects `bake::tests::a_baked_transform_moves_a_placed_gradient_with_the_path`, `bake::tests::a_strokes_own_transform_and_free_distort_move_its_placed_gradient`, `bake::tests::a_fills_gradient_follows_the_effects_around_its_transform_with_options`, `bake::tests::baked_free_distort_moves_placed_gradients_from_the_bounds_to_the_distorted_bounds`, `group::tests::a_groups_transform_and_free_distort_move_the_gradients_placed_on_its_paths`, `group::tests::a_groups_transform_moves_the_gradient_of_its_own_fill`, `group::tests::a_nested_groups_own_gradient_follows_the_outer_groups_transform_and_free_distort`, `group::tests::a_groups_transform_moves_the_gradients_placed_on_an_images_own_fills`, `group::tests::shape_art_moves_gradients_with_a_transform_effect`, `group::tests::shape_art_moves_the_gradient_of_a_symbol_instances_art_with_its_transform`, `tests::art_past_the_budget_keeps_its_own_gradients_in_place`, `tests::a_hidden_path_past_the_budget_leaves_a_layers_gradients_free_to_move`, `tests::edited_freeform_points_follow_a_transform_effect_and_free_distort`; render `objectfx::a_paths_gradient_moves_with_its_transform_and_free_distort`; engine `objexpand::a_placed_gradient_moved_by_a_transform_or_free_distort_expands_as_the_canvas_draws_it`). Scores and hours unchanged. @@ -698,6 +707,7 @@ since 2026-10-01. - **Cut of picked anchors (#6361):** Edit › Cut removes direct-selected anchors from their path and from a compound path's member, with the segments attached to them, as Clear does. Picked segments still lose only those segments. When a path also has a picked segment, Cut removes and copies only its picked segments and ignores its picked anchors, on every contour, as Clear does; an anchor left without a surviving segment is removed with them. Regression tests: `cut_*_anchors_*` and `cut_of_an_anchor_with_a_segment_on_another_contour_leaves_the_source_as_clear_does` in `crates/engine/tests/it/copy_direct_selection.rs`. - **Escape in Selection tool drags:** Escape during a Selection tool move or Alt-drag copy, a bounding-box scale or rotation, a marquee, or a corner widget, pie widget or bracket drag cancels it: the art returns to its state at the press, no copy is left, no undo step is added, the release does nothing, and the tool stays chosen. This is VectorCraft's own behavior. Regression tests: `escape_cancels_*` in `select/tests.rs` and `pie.rs`, and `escape_cancels_a_selection_tool_move_copy_scale_or_rotation` in `tests/selectescape.rs`. - **Large Shift-marquee selections and Select › Inverse:** `select.toggle` and `select.add` with many ids (a Shift-drag marquee sends them together) go through the selection once instead of once per id, and Select › Inverse looks each object up in a set of the selected ones. The resulting selection, its order and the reply are the same as before. With 50,000 objects the selection step of toggling every object off took 528 to 655 ms before and 2.5 to 4.6 ms after in 7 runs, wall clock on a machine that was running other builds (`cargo run --release -p vectorcraft-engine --example selection_bench`). Regression tests: `add_all_does_what_adding_each_does` and `toggle_all_does_what_toggling_each_does` in `crates/doc/src/selection/tests.rs`, and `toggle_and_add_handle_each_listed_id_in_order` in `crates/engine/tests/it/selection_commands.rs`. +- **Shift-click in the Layers panel's selection column on a large layer:** `layer.selectAll {id, add: true}` checks whether the row's art is all selected with a set of the selected objects, and removes or adds that art in one pass instead of once per object. The resulting selection, its order, the reply and the highlighted rows are the same as before. On a layer of 50,000 objects the whole command took a median of 733 ms before and 6.9 ms after when all of the layer's art was selected, and 369 ms before and 24 ms after when every other object was, in 7 runs each, wall clock on Linux while other builds were running (`cargo run --release -p vectorcraft-engine --example layer_select_bench`). Regression test: `a_shift_click_in_the_selection_column_matches_adding_or_removing_each_id` in `crates/engine/src/tests/layers.rs`. - **Selection passes through raster effects:** clicks with the Selection, Direct Selection and Group Selection tools (Group Selection's repeated click included), the Selection tool's pointer and marquee, Direct Selection's marquee, pointer and anchor highlight, and Group Selection's marquee (E for enclosed objects included) leave out the area that a drop shadow, a glow, a blur or another raster effect paints beyond an object. A click on a shadow selects the object under it, or nothing over an empty canvas, a repeated Group Selection click there adds the groups of the object under it, and a press on the shadow of a selected object does not move it ([the help page](https://helpx.adobe.com/illustrator/using/selecting-objects.html)). Over a shadow, Direct Selection highlights only the anchors of the object under it, and Group Selection keeps its own pointer and highlights no anchor, as it does everywhere (VectorCraft's own rule). No setting changes this. This covers paths, groups, type, symbol instances and images. Regression tests: `crates/engine/src/tests/select_effects.rs`. - **Symbol instances are selected where their art draws past their box:** a click or a marquee selects a symbol instance where a clipping path in its art, moved or reshaped by its live geometry effects, shows the art past the instance's box, as it selects a group of the same art; a click also selects it where a stroke in its art paints past the box ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/select-objects.html)). The rest is VectorCraft's own rule: inside the box the instance is selected as before; in Outline view and below a layer whose Preview is off only the box counts; hidden art and the area a raster effect paints are left out. This covers instances in groups, nested in other symbols' art, moved and scaled. Regression tests: `a_symbol_instance_is_hit_where_a_moved_clipping_path_in_its_art_shows_the_art` and `a_symbol_instance_is_hit_on_the_stroke_of_its_art_past_its_box` in `crates/doc/src/hit/tests.rs`. - **Selection follows geometry effects:** a click or a marquee with the selection tools selects a path or compound path where its live geometry effects (Transform, Offset Path, Roughen, Zig Zag and the other effects that reshape a path, on the object or on its fills and strokes) draw it, the copies a Transform effect makes included, and not where its own geometry no longer paints. The members of a group or layer whose own geometry effects move or reshape them are selected where they are drawn, at the depth each tool selects, and a locked member there lets the click through to what is below and is listed there in the Unlock submenu. A group's own fills and strokes are clicked where they paint its members, and a clipping path inside such a group is taken on its drawn outline before the art it clips. A compound path keeps its holes, Object Selection by Path Only takes the drawn outline and not its fill, and stacking order is kept. The selection tools select objects by clicking or by a marquee ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/select-objects.html)), and the effects leave the art they reshape editable ([the help page](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/apply-and-modify-effects.html)); where clicks land on the reshaped art is VectorCraft's own rule. In Outline view clicks and marquees use the plain paths, and in a layer with Preview off they take outlines only. The area a raster effect paints is still left out. Regression tests: `a_*_shifted_art_*`, `a_click_hits_a_paths_copy_and_evaluates_its_art_once_until_it_changes`, `a_groups_own_effect_moves_where_its_members_are_hit`, `a_layers_own_effect_moves_where_its_art_is_hit`, `a_preview_off_sublayer_of_an_effected_layer_is_clicked_in_outline`, `a_painted_group_around_an_effected_symbols_instance_is_hit_where_its_art_is_drawn`, `an_intertwine_group_in_a_layers_drawn_art_is_hit_in_its_woven_order`, `a_click_in_a_plain_group_evaluates_only_its_member_with_effects`, `a_clip_groups_own_effect_moves_where_its_mask_outline_is_hit`, `an_isolated_clip_group_with_its_own_effect_is_marqueed_by_its_members_own_geometry` and `a_clip_groups_art_is_hit_when_its_drawn_art_holds_only_the_clipping_path` in `crates/doc/src/hit/tests.rs`, and `a_click_and_a_marquee_select_art_where_its_transform_effect_draws_it`, `a_click_selects_a_group_where_its_own_fill_paints_a_moved_member`, `a_marquee_takes_an_inner_groups_own_fill_inside_a_painted_group` and `a_marquee_takes_a_groups_own_fill_inside_a_painted_layer` in `crates/engine/src/tests/select_effects.rs`. @@ -729,6 +739,7 @@ since 2026-10-01. - **Effects in the art's bounds:** Export with Use Artboards off, Fit to Artwork Bounds, and the other exports of the whole art (EPS without artboards, Export for Screens' Full Document, Save for Web (Legacy) with Clip to Artboard off) measure each visible object as the export crops above do. The drop shadows and other effects of groups, layers, type and images are inside the image or the artboard. A Shaper group without effects of its own is measured by the art it shows, and the hidden members of a group with a drop shadow, a glow or another raster effect do not count unless it is a Shaper group or also has a geometry, Pathfinder, Crop Marks or 3D effect or a visible effect on its own fill or stroke. The SVG of an artboard keeps an object whose effects alone reach the artboard. Tests measure a group, type and an image with a drop shadow, export a group and type with Use Artboards off and fit an artboard to them. - **EPS Save with Use Artboards:** Save As › EPS Options show Use Artboards with All or Range, for a separate file per artboard ([saving in EPS](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/save-artwork-in-eps-format.html)), unchecked by default (the scripting reference's EPS save options list `saveMultipleArtboards` with a default of false, [scripting reference](https://web.archive.org/web/20160803105056/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20JavaScript%20Scripting%20Reference.pdf)). Unchecked, Save writes one file whose bounding box fits all the visible art, as Export does, without the artboards' background colors; when no art shows, the page is the first artboard in its color. An opened EPS saved back this way loses its page margins. Checked with two or more chosen artboards, the file at the path is the central file of the visible art and each artboard is also written to `_.eps` beside it. Checked with one chosen artboard, VectorCraft writes that artboard as the page of the file at the path alone (the behavior Save had since #4293). Evidence: `cmd::fileio::tests_artboard_fill::eps_save_draws_the_color_on_an_artboard_page`, `tests::save::eps_save_without_use_artboards_fits_the_box_to_art_past_the_artboard`, `tests::save::opened_eps_saves_to_its_own_file_around_its_art_or_on_its_page`, `tests::save::eps_save_with_use_artboards_writes_the_central_file_and_one_per_artboard`, `dialogs::save_options::tests::eps_save_as_shows_use_artboards_off_and_writes_the_art_or_the_artboard`. +- **EPS Options custom flattener settings:** the help page describes flattening an EPS's transparency with a preset or with custom options, adjusted through Custom ([saving in EPS](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/save-artwork-in-eps-format.html)). EPS Options now has Custom… beside the flattener Preset. It opens Custom Transparency Flattener Options on the settings the export would use: the raster/vector balance, both resolutions, the text and stroke outline switches, Clip Complex Regions and Anti-alias Rasters. OK goes back to EPS Options with the preset shown as [Custom], the export flattens with those settings, and the next EPS Options start from them; choosing a preset drops them, and Cancel goes back to EPS Options unchanged. Preserve Alpha Transparency stays off, and overprints are kept only with Overprints set to Preserve. The [Custom] label, the remembering, the Cancel behavior, Anti-alias Rasters and the ranges (balance 0 to 100, resolutions 1 to 2400 ppi) are VectorCraft's own. Evidence: `dialogs::tests_eps::custom_flattener_options_start_from_the_preset_and_cancel_goes_back_unchanged`, `custom_flattener_options_are_exported_and_remembered_until_a_preset_is_chosen`, `bad_custom_flattener_options_keep_the_dialog_open`. - **Raster export backgrounds (#6125):** a raster export draws its background under the finished art, and blend modes read only the art below them, as on the canvas. An Outer Glow in Screen mode on the bare page shows in a PNG on white and in a JPEG. Flatten Transparency puts its white under the finished art the same way. Evidence: `tests::file::a_screen_outer_glow_is_in_raster_exports`, `tests::objectfx::a_screen_outer_glow_on_the_bare_page_shows_on_a_background`, `tests::knockout::page_knockout_and_isolated_blending`, `tests::knockout::no_blend_mode_reads_the_background`, `tests::cmykflatten::every_blend_mode_flattens_to_the_canvas_pixels_in_cmyk`. @@ -768,6 +779,7 @@ since 2026-10-01. - **Justification… on type on a path:** each paragraph's Desired Word Spacing, Letter Spacing and Glyph Scaling set its glyphs on type on a path as on point and area type, so the text after a wider gap starts further along the path, alignment and overflow use the spaced length, and a list marker keeps its width. Minimum and Maximum are not used on a path, and vertical type is not glyph scaled. SVG export writes such type as outlines with a warning. Tests `tests::justify::type_on_a_path_takes_desired_spacing_and_scaling`, `type_on_a_path_is_aligned_and_fitted_at_desired_spacing`, `vertical_type_and_list_markers_on_a_path_are_not_glyph_scaled` and the SVG test `text_layout::justification_spacing_on_a_path_is_outlined`. Public reference: the help page (). - **Letter spacing and Full Justify between shaped clusters:** Desired Letter Spacing on any line, the letter spacing range of a justified line, and Single Word Justification's Full Justify add space only between shaped clusters, in horizontal, right-to-left and vertical type, so a combining mark stays on its letter and a Devanagari syllable's glyphs stay together. They add no space next to a zero-width format control (a soft hyphen, a bidi mark, embedding, override or isolate, a zero-width space, a joiner or non-joiner, a word joiner, a variation selector, a tag, the byte order mark), so a word wrapped in an override still reaches both edges of a justified line, and a Kinsoku push-in counts no gap at one either. A zero-width space is a line break opportunity but not a word separator ([CSS Text Level 3](https://www.w3.org/TR/css-text-3/#word-separator) does not list it), so a justified line gives it no share of its room. Desired Letter Spacing between the letters on either side of a zero-width space goes after the zero-width space, so a line that breaks there ends at its last letter, and the line breaker does not measure a gap after it. A line that Full Justify spreads and that ends in a drawn hyphen puts the same gap between its last letter and the hyphen. The cluster boundary is VectorCraft's own rule, based on the typographic character unit of [CSS Text Level 3](https://www.w3.org/TR/css-text-3/#typographic-character-unit). Tests `tests::justify::single_word_full_justify_keeps_combining_mark_with_base`, `desired_and_fitted_letter_spacing_skip_shaped_cluster`, `rtl_single_word_cluster_gap_follows_drawn_order`, `vertical_single_word_cluster_gap_follows_drawn_order`, `single_word_full_justify_keeps_conjunct_cluster`, `desired_letter_spacing_skips_bidi_format_controls`, `letter_spacing_and_full_justify_skip_joiners_and_soft_hyphens`, `format_controls_are_the_zero_width_default_ignorables`, `zero_width_space_takes_no_word_space_room`, `desired_letter_spacing_ends_a_line_broken_at_a_zero_width_space_without_a_gap`, `single_word_full_justify_spreads_up_to_the_drawn_hyphen` and `layout::wrapping_tests::kinsoku_shori_type_counts_no_gap_at_a_format_control`. Public reference: the help page (). - **Justified lines with tabs:** a tab is not a word space, so a justified area type line no longer gives it a share of its room that no glyph draws. On a justified line with a tab, the text up to the last tab keeps its spacing, each tab keeps its stop and its leader stays in its gap, and the text after the last tab takes the room (word spaces first, then letter spacing, glyph scaling and the gaps between its letters), so the line ends on the far edge. A tab separates two words, so Single Word Justification does not align a word-tab-word line. Right-to-left lines take the text drawn after the last tab drawn, and vertical lines work down the column. Spreading the room after the last tab is VectorCraft's own rule. Tests `tests::justify::a_justified_line_with_a_tab_spreads_the_text_after_it_to_the_edge`, `a_justified_tab_keeps_its_leader_inside_its_gap`, `a_justified_word_tab_word_line_reaches_the_edge`, `the_last_line_with_a_tab_fills_the_measure_only_with_justify_all`, `a_justified_line_takes_its_room_after_its_last_tab`, `a_justified_vertical_line_with_a_tab_reaches_the_end_of_its_column`, `a_justified_right_to_left_line_with_a_tab_spans_its_measure` and `justified_point_type_with_a_tab_keeps_its_width`. Public reference: the help pages (, ). +- **Show Hidden Characters marks every character that prints no ink:** [the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/insert-white-space-and-break-characters.html) lists the characters that Type › Show Hidden Characters makes visible: paragraph returns, forced line breaks, tabs, spaces, nonbreaking spaces, discretionary hyphens and the end of the text. Besides the dot over a space, ¶ at a paragraph's end and # at the story's end, the canvas draws an arrow across each tab's advance to its stop, a ring over a nonbreaking space (U+00A0) and a smaller one over a narrow nonbreaking space (U+202F), a short tick over the spaces of a set width (U+2000 to U+200A, U+205F, U+3000), ¬ at a discretionary hyphen (U+00AD) whether or not the line breaks there, and a bent arrow after a line that a forced line break (U+2028) ends, which gets no ¶. The marks follow the baseline of vertical type and of type on a path, ¶ goes at the left end of a right-to-left line, and type on a path gets # after its last character when the path shows all of its text. The shapes of the marks, and marking U+202F and the spaces of a set width, are VectorCraft's own rules. The marks are drawn only on the canvas and are not saved or exported. Tests: `canvas::tests::hidden_characters_mark_tabs_nonbreaking_spaces_and_discretionary_hyphens`, `hidden_characters_mark_forced_line_breaks`, `hidden_characters_mark_a_discretionary_hyphen_at_a_break_once`, `hidden_characters_follow_vertical_type`, `hidden_characters_end_a_right_to_left_line_at_its_left`, `hidden_characters_mark_type_on_a_path` and `show_hidden_characters_draws_every_kind_of_mark`. - **The text style panel menus' Duplicate and Delete:** in the Character Styles and Paragraph Styles panel menus, Duplicate highlights the copy, as Create New Style highlights the new style, and Delete leaves no style highlighted, as the Delete button does, so Duplicate, Clear Overrides, Redefine and Style Options are disabled until another style is clicked. A highlighted style that is renamed in Style Options or deleted by a command is no longer highlighted either. The tests `panels::text_styles::tests::panel_menu_duplicate_and_delete_update_the_highlighted_style` and `a_highlighted_style_that_is_no_longer_listed_is_not_highlighted` cover this. Public reference: [Character and paragraph styles](https://web.archive.org/web/20261015081534/https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). - **Names of new styles and symbols:** `charStyle.new` and `paraStyle.new` trim the white space around the name they are given, as `charStyle.rename` and `paraStyle.rename` do, and refuse a name that is then empty; Duplicate names its copy from the trimmed name. `symbol.new` and `symbol.duplicate` trim the name as Symbol Options does, and `library.use` adds a library's text style under its trimmed name. Public reference: [Character and paragraph styles](https://web.archive.org/web/20260825113735/https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). - **Naming a new text style first:** Alt-click on New in the Character Styles or Paragraph Styles panel opens New Character Style or New Paragraph Style (`ui.newCharStyle`, `ui.newParaStyle`) with the name a plain click's style gets; OK makes the style from the text selected when the dialog opened, and Cancel adds none. Tests `panels::text_styles::tests::alt_clicking_new_character_style_asks_for_its_name` and `alt_clicking_new_paragraph_style_asks_for_its_name`. Public reference: [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html), which lists Alt-click for opening panel options and names Actions, Brushes, Swatches and Symbols as exceptions. @@ -775,6 +787,7 @@ since 2026-10-01. - **Tab stop drag guide:** while a stop is dragged on the Tabs panel's ruler, the canvas draws a line through the text whose stops the ruler shows, where the stop would land: across the frame cell the paragraph starts in for area type, measured from where the frame lets the paragraph's first line start (the cell's edge inside the inset, or past a text wrap object), and across the paragraph's lines from the type's origin for point type. It turns with rotated type and runs across the columns of vertical type. In a Ctrl-drag (Command on macOS) it follows the grabbed stop. No line is drawn while a release would delete the stop, and the line goes on release, on Escape, when no button is down, and when the panel is closed. It is not a document object and records no undo step. Its extent, color and these rules are VectorCraft's own. A stop drag whose release the ruler does not get also ends then, as a marker drag already did. Tests `panels::tabs::tests::dragging_a_stop_draws_a_guide_through_the_text`, `a_command_drag_guide_follows_the_grabbed_stop`, `the_stop_guide_ends_with_the_drag`, `the_stop_guide_follows_rotated_point_and_vertical_type` and `the_stop_guide_starts_where_a_wrap_object_lets_the_line_start`. Public reference: [Manage tab stops](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/manage-tab-stops.html), which describes a guide shown through the selected text during a tab stop move. - **Tabs indent markers on threaded frames:** when a marker drag gives the paragraphs of a threaded story values of their own, the Tabs panel sends one `text.setFormat {paragraphIndents}` with an entry for each paragraph of the story, whatever order the frames were selected in with the Selection tool, so the story flows through its frames again once rather than once for each paragraph, and a drag that changes no paragraph runs nothing; a paragraph that runs on from one frame into the next gets one entry, after Type tool Select All too. A selected story is one text: with the Selection tool, a marker drag on any of its frames sets every paragraph of the story, in its locked and hidden frames too. Tests `panels::tabs::tests::indent_markers_on_selected_threaded_frames_follow_the_story_and_set_a_split_paragraph_once`, `indent_markers_over_many_threaded_paragraphs_send_one_format_command`, `indent_markers_after_select_all_list_a_split_paragraph_once`, `indent_markers_on_some_threaded_frames_list_the_whole_story_once`, `indent_markers_on_one_threaded_frame_set_its_locked_and_hidden_frames`, `cmd::threads::tests::paragraph_indents_flow_a_threaded_story_once_as_one_command_per_paragraph_would`, `paragraph_indents_over_thousands_of_paragraphs_flow_the_story_once` and `paragraph_indents_check_every_entry_and_skip_a_change_that_changes_nothing`, and `cmd::typecmd::area_tests::set_format_refuses_a_param_of_the_wrong_type`. Public reference: [Indent text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/indent-text.html). - **Width Point Edit:** Shift-double-click enables Adjust Adjoining Width Points; plain double-click and direct opening retain the default. Tool dispatch and headless dialog tests cover neighboring widths, Undo/Redo and Cancel. Public reference: [Variable-width strokes](https://helpx.adobe.com/illustrator/using/stroke-object.html). +- **Width Point Edit on a discontinuous point:** opening the dialog on either half shows both sets of side widths, Incoming and Outgoing, each with Side 1, Side 2, Total Width and its own link; OK sets both halves in one `stroke.widthPoint.set` and one undo step, and Delete removes both. Single Width Only keeps the incoming or the outgoing widths as one continuous point. With Adjust Adjoining Width Points, the nearest point before follows the incoming change and the nearest point after follows the outgoing change; the group layout and that rule are VectorCraft's own. Tests `dialogs::width_point::tests::either_half_of_a_discontinuous_point_shows_both_sets_of_side_widths`, `ok_sets_both_halves_of_a_discontinuous_point_in_one_step`, `delete_removes_both_halves_of_a_discontinuous_point`, `single_width_only_keeps_the_chosen_half_as_one_point` and `a_compound_member_edits_both_halves_of_its_owners_point`, and `tests::widthpoints::paired_set_*` and `single_width_only_leaves_one_continuous_point`. Public references: [Apply stroke on an object](https://helpx.adobe.com/illustrator/using/stroke-object.html), which describes editing the widths before and after a discontinuous point in that dialog, and an [archived user guide, p. 161](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=167), which describes keeping either the incoming or the outgoing width to leave one continuous point. Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a feature lands. - **New ruler guides (G1):** Alt swaps orientation while dragging from either ruler, following the [public shortcut reference](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html). Preview, snapping and final placement use the current axis. Tool and egui event tests exercise both rulers, modifier changes, cancellation and one-step Undo/Redo; existing-guide Alt-copy and ruler-origin gestures are unchanged. @@ -783,6 +796,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Width-point finite-arithmetic follow-up (G1/M3):** Adjoining adjustments avoid intermediate overflow; non-finite normalized or resulting factors are rejected before committing. Engine regressions in `tests/widthpoints.rs` cover finite extremes, small nonzero results, atomic rejection, Undo/Redo and native save/reopen. Historical focused validation on the `a3357121` integration observed 2 expected RED failures with 11 passing controls, then all 13 tests passing with the repair; none were ignored. All three added regressions passed in current full CI. A full CI retry on the five-unit combined source at `a0671777` passed all seven stages with 6,613 test outcomes on 2026-10-14. An earlier full-CI run on the identical source panicked in the randomized `ai_mutated_save_never_panics` test; the cause remains unresolved. This five-fix batch does not claim to repair that failure. Scores and hours unchanged. - **Width-point creation (G1):** double-click a stroked segment with the Width tool to open Width Point Edit using sampled side widths. OK creates the point and optionally adjusts adjoining widths in one undo step. Cancel or Delete discards a prospective point without changing the document or redo history. Command and pointer tests cover profiles, compound paths, adjoining adjustment, existing-point editing and Undo/Redo. Message-catalog checks and full CI passed; the original capture verifies opening and Cancel, and the dialog layout was reviewed (2026-10-13: 28 focused Width tests, all seven cargo xtask ci stages, and a headless opening/Cancel capture with original PNG review). [Variable-width strokes](https://helpx.adobe.com/illustrator/using/stroke-object.html). - **Escape deselects width points:** with the Width tool, Escape deselects the selected width points, on the key the reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists for deselecting a width point. The path, its widths and the undo history do not change. With no width point selected, Escape does what it does with the other tools, such as leaving isolation mode. +- **Width profiles on brushed strokes:** brush art does not follow a stroke's width profile, so while every stroke the list edits draws with a brush, the Profile list in the Stroke panel, the Properties panel and the Control bar is dimmed and says why when hovered (VectorCraft's own rule while brushes ignore width profiles; art and pattern brushes that follow one are still missing). It opens no list while every one of those strokes is uniform, and only Uniform, which removes the profiles, while one has a profile. The Flip Along and Flip Across buttons beside it are off. The strokes are the ones `stroke.set` edits: the active Appearance stroke row in each selected object that has an equal row and the top stroke in the others, else a selected group's or compound shape's own stroke, else the objects' strokes. Images and symbol instances, which take no stroke from the list, do not count. A selection where some of them have no brush, or an object has no stroke, keeps the full list. The Width tool adds, edits and deletes no width points on a brushed stroke, and a press or a double-click on one says why in the status bar; without Shift it deselects the width points of other strokes, and the cursor over a brushed stroke offers no edit. A plain stroke under a selected brushed one stays reachable. Width points selected before their stroke took a brush show no handles, and Delete, Backspace and Escape act as if none were selected. Tests: `panels::tests_strokedepth::{dropdown_is_dimmed_while_the_brush_keeps_its_size, the_active_stroke_row_decides_whether_the_dropdown_is_dimmed, a_groups_own_brushed_stroke_dims_the_dropdown, selecting_another_object_without_an_edit_updates_the_dimming, flip_buttons_leave_a_brushed_strokes_profile_alone, mixed_selection_dims_the_dropdown_only_when_every_stroke_has_a_brush, the_hover_text_is_the_width_tools_status_message}`, `panels::properties::tests::the_width_profile_of_a_brushed_stroke_offers_only_uniform`, `tests::appearance::{brushed_strokes_profiled_reads_the_strokes_stroke_set_edits, brushed_strokes_profiled_reads_a_compound_shapes_own_stroke, brushed_strokes_profiled_reads_a_targeted_layers_active_stroke_row, brushed_strokes_profiled_leaves_out_symbol_instances, brushed_strokes_profiled_falls_back_to_the_top_stroke_where_the_active_row_has_no_match}`, `tests::widthtool::the_width_tool_says_why_it_leaves_a_brushed_compound_path_alone`, `distort::width::tests::{brushed_stroke_is_left_alone_with_a_reason, delete_leaves_the_width_points_of_a_brushed_stroke, a_press_on_a_brushed_stroke_deselects_and_its_cursor_offers_no_edit, shift_on_a_brushed_stroke_keeps_the_selected_width_points, a_plain_stroke_under_a_selected_brushed_one_stays_reachable, a_brush_applied_under_a_still_pointer_takes_away_the_hover, a_brush_added_to_the_library_is_seen_at_the_next_revision}`. - **Smooth widths between width points (#5714):** a variable-width stroke changes width along a smooth curve from one width point to the next, where it used to run in a straight line and turn a corner at each point. The public description is that the path "gradually gets wider or narrower from one point to the next" in "a flowing, continuous curve", and that stacked points make a sharp break ([Peachpit, Expressive Strokes](https://www.peachpit.com/articles/article.aspx?p=2979069)); the exact curve is not documented, so each side follows a monotone cubic (Fritsch–Carlson): no kink at a point, flat where a point is wider or narrower than both neighbours, never past the points either side, points on one line kept on it. The outline samples straight runs between width points closely enough to follow the curve to the drawing tolerance (at most 64 samples per span and 4,096 per piece). Presets with a middle point (Lens, Pinch, Teardrop, Wave) look softer; two-point tapers are unchanged. Tests: `appearance::profile::tests::{widths_run_smoothly_through_width_points, widths_never_pass_the_points_either_side, a_step_ends_the_curve_on_each_side, widest_covers_every_width_along_the_profile}`, `stroke::width::tests::{a_straight_run_follows_the_curve_between_width_points, samples_between_width_points_are_capped}`. - **Stroke gradients where a variable-width stroke meets itself (#5960):** with a gradient along or across a stroke that has a width profile, where the stroke crosses itself the later part paints over the earlier one only where the two overlap, and a narrow part running close beside a wide one leaves its edge alone. Each slice of the gradient reaches as far as the stroke is wide where it sits (for a dashed stroke, as wide as it gets within the reach of a cap or dot, found in one pass along the path, so a densely flattened path costs no more per point), where it used to reach as far as the stroke is wide anywhere and paint a square of its colour over the wider part. Strokes without a profile are unchanged. Tests: `stroke::tests_gradient::a_narrow_pass_over_a_wide_one_paints_only_where_they_overlap`, `a_narrow_pass_beside_a_wide_one_leaves_its_edge_alone`, `a_densely_flattened_dashed_pass_beside_a_wide_one_leaves_its_edge_alone` and `widest_ahead_is_the_widest_within_the_window`, with the existing coverage tests (joins, caps, arrowheads, profiles, dashes, aligned strokes). - **Width strokes zoomed out (#995):** a stroke with a width profile keeps its shape while the view zooms out. The canvas keeps a hairline visible (at least half a device pixel); for a profiled stroke it is the profile's widest point that gets that minimum, not the weight, so a 1 pt stroke with a 6x width point is no longer drawn twice as thick at 25% zoom than at 100%. Plain strokes are unchanged. Test: `render::tests::widthzoom`. @@ -795,6 +809,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Fade Region Outside Artboard:** Artboard Options' Global checkboxes Fade Region Outside Artboard and Update While Dragging ([user guide, Artboard options](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf)) are application preferences (`fadeRegionOutsideArtboard`, `artboardUpdateWhileDragging`), both on by default. While the Artboard tool is active the canvas draws everything outside the artboards, the pasteboard and the art on it, with each color channel at 60% of its value (VectorCraft's own amount), or only outside the box around all the artboards when crossing artboards would leave more than 4,096 rectangles in view; with Update While Dragging off it draws as usual during an artboard move or resize. Presentation Mode, exports and print do not change. Regression tests: `canvas::tests` (`the_artboard_tool_fades_the_pasteboard`, `presentation_mode_draws_no_fade`, `the_fade_darkens_art_on_the_pasteboard_and_not_on_the_artboard`, `outside_rects_cover_the_bounds_minus_the_boards`, `outside_rects_of_a_row_of_boards_stay_few`, `the_fade_of_crossing_boards_stays_bounded`, `update_while_dragging_keeps_or_drops_the_fade_during_an_artboard_drag`, `the_pasteboard_fade_leaves_exports_unchanged`), `dialogs/tests.rs` (`artboard_options_global_checkboxes_set_the_preferences`, `artboard_options_error_leaves_the_global_preferences_unchanged`). - **Saved views (G7):** View › New View… and Edit Views… ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html): up to 25 views per document, saved with it, renamed or deleted in Edit Views, chosen from the bottom of the View menu). Each view keeps the zoom, centre and rotation; the View menu lists all 25 (`view.goto1`–`view.goto25`), and Edit Views… lists them to rename or delete, applied together as one undo step. A file's views are checked when it opens (at most 25, unique names up to 255 characters, a finite centre and a positive zoom). Tests: `saved_views_round_trip_and_from_a_file_are_tidied` (`crates/format/tests/prop_format.rs`), `crates/engine/src/cmd/views.rs`, `crates/ui-egui/src/dialogs/edit_views.rs` and `every_saved_view_is_listed_at_the_bottom_of_the_view_menu` (`crates/ui-egui/src/menus.rs`). - **Window › Arrange › Tile (G7):** Tile (`window.arrange.tile`) shows every open document at once, edge to edge in the document area ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)), one pane each in a grid of as many columns as the square root of the number of documents, rounded up, each fitted to its pane. The current document's pane is the canvas; the other panes draw their documents with their artboards, guides and selected objects, and a press in one makes its document the current one. Consolidate All Windows (`window.arrange.consolidateAllWindows`) shows one document under its tab again. The grid and when the two items are enabled (Tile with two documents or more, Consolidate All Windows while they are tiled) are VectorCraft's own. Tests: `crates/ui-egui/src/canvas/panes/tests.rs`. +- **Arrange Documents (G7):** the application bar's Arrange Documents button arranges the open documents in grid and tile layouts ([public source](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/workspace-overview.html)). Its menu, and Window › Arrange, have Consolidate All Windows, Tile (the grid), Tile All Vertically (side by side), Tile All Horizontally (stacked) and the 2-Up, 3-Up, 4-Up and 6-Up layouts, which show that many documents and leave the others under their tabs, the current one in the last pane (`window.arrange.tile {layout}`). The set of layouts and how each places the panes are VectorCraft's own. Tests: `crates/ui-egui/src/canvas/panes/tests.rs`. - **Window › Arrange › Float in Window, Float All in Windows and Cascade (G7):** documents float in windows of their own, out of the tab strip ([public source](https://helpx.adobe.com/illustrator/using/customizing-workspace.html)). Float in Window (`window.arrange.floatInWindow`) floats the current document, Float All in Windows (`window.arrange.floatAllInWindows`) every tabbed one, and Cascade (`window.arrange.cascade`) floats every document and stacks the windows from the upper left to the lower right ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)). On the desktop each window is an OS window; on the web and on Wayland it is a window inside the app's window. The window of the current document holds the canvas; the others draw their documents as Tile's panes do, and a press in one makes its document the current one. Closing a window closes its document, asking to save unsaved changes. Consolidate All Windows brings every document back under the tabs, and Tile brings them back into its grid. The cascade's 30 pt step, the windows' size and when the items are enabled (Cascade with two documents or more, Float in Window for a tabbed current document, Float All in Windows while a document is tabbed, Consolidate All Windows while documents are tiled or floating) are VectorCraft's own. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. - **Dragging a document tab out and a document window back (G7):** a document tab dragged more than 24 pt above or below the tab strip floats its document in a window under the pointer, and a document window dragged onto the tab strip goes back under the tabs ([public source](https://helpx.adobe.com/illustrator/using/customizing-workspace.html)). A window inside the app's window is dragged by its title bar; an OS window by the document's tab at its top, and the window follows the pointer. The 24 pt distance and the tab at the top of an OS window are VectorCraft's own. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. - **Reordering document tabs (G7, #5663):** a document tab dragged along the tab strip moves its document among the others ([public source](https://helpx.adobe.com/illustrator/using/customizing-workspace.html)); a line marks the gap it goes in. The current document stays current, each document keeps its own zoom, centre and artboard, the views Window › New Window opened move with their document, and Window › Next/Previous Document follow the new order. `document.move` (`{from?, to}`) does the same from MCP, the control channel and recordings. `crates/ui-egui/src/tests/tab_reorder.rs`, `crates/engine/src/tests/document_move.rs`. @@ -808,20 +823,25 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Preferences › General describes its settings:** the line under the Preferences fields shows a sentence for each of the 32 General settings, Enable Contextual Task Bar included, when the pointer is over the setting's row or its control has the keyboard focus, and a screen reader gets the same sentence. The sentences are VectorCraft's own and state what the app does with each setting. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Preferences › Selection & Anchor Display describes its settings:** the line under the Preferences fields shows a sentence for each of the 14 Selection & Anchor Display settings, from Tolerance to the Curvature Tool rubber band, on hover and on keyboard focus, and a screen reader gets the same sentence. The Snap to Point sentence states that the Smart Guides Snapping Tolerance applies while Smart Guides is on. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Preferences › Guides & Grid describes its settings:** the line under the Preferences fields shows a sentence for each of the 12 Guides & Grid settings, from Snap to Grid to Pattern Editing's Tile Edge Color, on hover and on keyboard focus, and a screen reader gets the same sentence. The Show Pixel Grid sentence states that the pixel grid shows from 600% zoom. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. -- **Preferences › Smart Guides describes its settings:** the line under the Preferences fields shows a sentence for the Smart Guides box and for each of the 14 Smart Guides settings, from Color to Snap to Perpendicular, on hover and on keyboard focus, and a screen reader gets the same sentence. The sentences state VectorCraft's own behavior: Pixel Preview turns Smart Guides off and Snap to Grid snaps instead; with Alignment Guides off, art still lines up without the line; Object Highlighting outlines only an unselected object while a selection tool is not dragging; Snapping Tolerance is a distance on screen at every zoom; Snap to Last Location does not return a copy. Units, General, Selection & Anchor Display, Guides & Grid and Smart Guides have sentences, and the other categories leave the line empty. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. +- **Preferences › Smart Guides describes its settings:** the line under the Preferences fields shows a sentence for the Smart Guides box and for each of the 14 Smart Guides settings, from Color to Snap to Perpendicular, on hover and on keyboard focus, and a screen reader gets the same sentence. The sentences state VectorCraft's own behavior: Pixel Preview turns Smart Guides off and Snap to Grid snaps instead; with Alignment Guides off, art still lines up without the line; Object Highlighting outlines only an unselected object while a selection tool is not dragging; Snapping Tolerance is a distance on screen at every zoom; Snap to Last Location does not return a copy. Units, General, Selection & Anchor Display, Guides & Grid, Smart Guides and Type have sentences, and the other categories leave the line empty. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. +- **Preferences › Type describes its settings:** the same line shows a sentence for each of the 23 Type settings, from Size/Leading to Measure Type by Glyph Bounds, when the pointer is over the setting's row or its control has the keyboard focus, and a screen reader gets the same sentence. Each sentence is VectorCraft's own and states what the app does with the setting: for example, which keys step by each increment, which panels show the East Asian and Indic options, and that the two pink highlights show only on screen. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Window › New Window (G7, #4116):** New Window (`window.newWindow`) opens another view of the current document ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html) describes showing one document in several windows at once), with its own zoom, center, rotation, artboard and Outline or Preview, as a tab of its own; an edit in one view shows in every view. Tile, Cascade, Float in Window, Float All in Windows and Consolidate All Windows arrange each view as they arrange a document, and Next and Previous Document step through the views. Closing a view leaves the document open; closing its last view closes the document, asking to save it first. The view's number after the name in its tab ("Name:2", while the document has more than one view) is VectorCraft's own. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. - **Document Setup modal handoff:** Document Setup → Edit Artboards applies valid settings, closes the dialog and activates the Artboard tool. Pointer-click tests cover successful handoff, invalid settings, OK, Cancel and Undo in `dialogs/document_setup.rs`. +- **Document Setup › Transparency grid color boxes:** a click on either color box beside Grid Colors opens the Color Picker on that color, as [the help page](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/view-transparency-in-artworks.html) describes choosing a custom color for each of the grid's two alternating squares. The picker's OK sets only that color in the dialog, Grid Colors then names the pair (Custom unless it matches one of VectorCraft's presets), and Document Setup's OK applies it in one undo step; the picker's Cancel leaves both colors as they were. With the keyboard on a box, Enter or Space opens the picker. The keyboard handling and staging the color until Document Setup's OK are VectorCraft's own. Tests: `a_grid_color_box_opens_the_color_picker_and_its_ok_sets_that_color` and the other grid color tests in `dialogs/document_setup.rs`. - **Document Setup › Color:** a Color tab shows the document color mode (RGB Color or CMYK Color), a Convert to CMYK or Convert to RGB box for a mode change (cleared: the colors keep their numbers), and the RGB and CMYK profiles assigned to the document, with a working-space entry for none. OK runs `edit.assignProfile` and then `file.documentColorMode` with the dialog's other changes in one `command.batch`, and the document's changes are one undo step. An unchanged Color tab adds no color commands, and Cancel, or OK with nothing changed, records no undo step. A Color tab field with a value of the wrong kind is an error, and the dialog stays open. The tab is VectorCraft's own layout; File › Document Color Mode and Edit › Assign Profile… stay as they are. Tests in `dialogs/document_setup.rs`. - **Assign Profile's three choices:** the Assign rows of Edit › Assign Profile… (the Separations panel's Color Settings section) offer Don't Color Manage This Document, the working space of the document's color mode (Working RGB or Working CMYK, with its name) and Profile with the other profiles of that kind, as [Assign or remove a color profile](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=150) lists them. They act on the profile of the document's color mode: an RGB document's RGB profile, a CMYK document's CMYK profile; the other model's profile stays as it is (VectorCraft's own rule; Document Setup › Color sets both). Picking the working space assigns its profile, which stays when the working space changes later. A choice the document already has runs nothing. Tests in `panels/separations.rs`. - **Canvas through the display's profile on Windows and X11:** Preferences › Performance › Use Monitor Profile for Canvas (on by default) converts the canvas's art, artboard paper and transparency grid from sRGB into the ICC profile of the display that shows most of the main window, after any proof, as the help page describes the monitor's profile translating the document's colors for the monitor ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=151)). Windows gives the display's default profile, and a display with Advanced Color on is left to Windows ([Microsoft Learn](https://learn.microsoft.com/en-us/windows/win32/wcs/advanced-color-icc-profiles)); X11 gives colord's profile for the output or the `_ICC_PROFILE` property. macOS converts the window itself, and a Wayland session stays sRGB. `ui.inspect` reports `displayProfile`. Tests in `color/src/cms/display.rs`, `ui-egui/src/display_profile.rs` and `canvas::tests::the_canvas_is_drawn_through_the_display_profile_while_the_preference_is_on`. +- **Refresh Monitor Profile:** Edit › Refresh Monitor Profile (`view.refreshMonitorProfile`), VectorCraft's own command, reads the display's profile again on the next frame instead of waiting up to 10 seconds, so a profile installed or changed while the app runs is used without a restart; a request made while a reading runs starts when it ends, and the command is off while Use Monitor Profile for Canvas is off. `ui.inspect`'s `displayProfile.readRequested` reports a request that hasn't started. Tests `display_profile::tests::a_requested_reading_starts_on_the_next_frame_past_both_intervals`, `a_request_made_while_a_reading_runs_waits_for_it_to_end`, `a_request_is_dropped_when_the_preference_goes_off` (desktop app) and `menus::tests::refresh_monitor_profile_asks_for_a_reading_of_the_display_profile`. - **Translucent art blended before the display profile:** with Use Monitor Profile for Canvas converting, translucent art and the anti-aliased edges of art over an artboard's paper, a colored artboard or the transparency grid are blended with it in sRGB and the blend is converted, so the monitor's profile translates the document's colors as they are composited ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=151)). The frame rendered whole, the part an edit renders again, the render worker's frame, the pan fill and the other windows' panes do the same; over the pasteboard and in Outline the art is converted on its own, and with no profile to convert into nothing changes. Tests `display_profile::tests::translucent_pixels_over_the_paper_are_blended_before_they_are_converted`, `the_transparency_grid_is_blended_cell_by_cell`, `the_backdrop_is_found_through_the_view` and `canvas::tests::translucent_art_over_the_paper_is_blended_before_the_display_profile`. - **Out-of-gamut warning after a profile change:** the out-of-gamut warning and its closest-color correction in the Color panel and Color Picker ([the help page](https://helpx.adobe.com/illustrator/using/adjusting-colors.html)) check the color against the document's assigned CMYK profile, else the working CMYK space, and update when Edit › Assign Profile… or Edit › Color Settings… changes that space or a loaded profile changes, without a change of color. Which CMYK space the warning uses is VectorCraft's own rule. Tests: `gamut_warning_follows_a_profile_change` and `gamut_warning_follows_a_profile_loaded_again` in `dialogs/color_picker/tests.rs`. +- **Swatch Options and New Swatch color warnings:** both dialogs show the out-of-gamut triangle and the out-of-web-color cube under the color, each with its correction beside it, and a click on the icon or the correction shifts the color to the closest printable or web-safe color ([the archived user guide](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=236), Swatch options; [the help page](https://helpx.adobe.com/illustrator/using/adjusting-colors.html)). The icons in the Color panel and the Color Picker correct the color too. VectorCraft's own rules: the triangle shows in RGB, HSB and Lab and the cube in every mode but Web Safe RGB, both can show at once, a web correction of a Grayscale, Lab or CMYK color is edited in RGB, a gamut correction keeps the CMYK equivalent and is edited in CMYK, and a correction keeps the name, the color type and Global and changes the dialog's fields only, so OK records one undo step. Tests: `swatch_options_shows_and_corrects_both_warnings` and `swatch_warnings_follow_the_mode` in `dialogs/swatch_options.rs`, `a_warning_corrects_the_new_colour_only_until_ok` in `dialogs/new_swatch.rs`. - **Assign Profile and the working spaces:** Edit › Assign Profile… tags the document and leaves the working spaces of Edit › Color Settings… as they are, in Color Settings, the Separations panel and the settings saved for the next start. Colors show and convert through the profiles assigned; a change in Color Settings keeps the profiles the document in front is assigned in use, and removing an assigned profile in use puts the working space back in its place. The profiles in use follow the document in front: a new, opened or reverted document, a switch to another tab, a close, Undo and Redo of Assign Profile, a failed batch, each step of a batch, Export All Open and the update of placed documents put that document's profiles in use, and the working spaces where it is assigned none or no document is open. With Window › Arrange › Tile or floating document windows, each document behind the front one draws its art, paper and transparency grid through its own assigned profiles, and loading or removing a profile redraws the documents assigned it; placed documents inside it still draw through the front document's profiles. How documents behind the front one draw is VectorCraft's own rule. View › Proof Setup › Working CMYK simulates the working CMYK space of Color Settings in Proof Colors and Separations Preview, also in a document assigned another CMYK profile. Public references: [Changing the color profile for a document and About color working spaces](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=150) and [Soft-proof presets](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=134). Tests in `engine/tests/color_settings.rs`. - **Color management policies:** Edit › Color Settings… (the Separations panel's Color Settings section and `edit.colorSettings`) has an RGB and a CMYK policy: Off, Preserve Embedded Profiles and Convert to Working Space, and Preserve Numbers for CMYK. When a document tagged with a profile other than the working space is opened, reverted or opened as a template, the policy keeps the profile, takes it off with the color numbers kept, or converts that model's colors into the working space, with black point compensation as Color Settings set it, and takes it off. The policies are kept in `Color Settings.json`. Preserve Embedded Profiles as the default for both, and the per-model policy for a document tagged with both an RGB and a CMYK profile, are VectorCraft's own rules; placed images and the Profile Mismatches and Missing Profiles prompts are not covered. Public reference: [Color management policy options](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=157). Tests in `engine/tests/color_settings.rs`, `color/src/cms/tests.rs` and `color/src/cms/tests_icc.rs`. - **New Document's units:** the dialog opens in Preferences › Units › General, also on a Recent entry made in other units (an entry in pixels, or a saved preset in the units it was saved in, keeps its units), so File › New and New Without Dialog make documents in the General unit. Units chosen in the Units menu stay when another tab or preset is chosen and when a card is clicked or double-clicked; without such a choice, clicking another Recent or Saved card brings back the units that card was made in (#7944). These are VectorCraft's own rules. Tests: `the_dialog_opens_in_the_general_units_over_a_recent_entry`, `a_recent_saved_preset_keeps_its_units_and_name`, `units_chosen_in_the_menu_survive_tabs_and_presets` and `units_set_over_a_popup_stay_chosen` in `dialogs/new_document.rs`; `a_recent_card_keeps_the_units_chosen_in_the_menu` and `a_double_clicked_card_keeps_the_units_chosen_in_the_menu` in `panels/tests_units.rs`. - **New Document's More Settings and Save Preset:** More Settings opens a pop-up over New Document with only Number of Artboards, the artboard layout, Change to Right-to-Left Layout, Spacing and Columns; Done, Escape or a click outside closes it and keeps the values. Save Preset turns the top of Preset Details into a Save Document Preset heading with the preset's name, Cancel and Save, and hides the document's name, Close and Create until the preset is saved or canceled; nothing in that mode creates a document. Save Preset's default name is the first "Preset N" no saved preset has. VectorCraft's own layout. Harness tests in `dialogs/new_document.rs` cover both. - **New Document profiles:** each built-in category's presets start documents from that category's profile, a native document holding the starting swatches, graphic styles, brushes, symbols and other assets, the ruler and Document Setup options and the print settings ([Create a custom new document profile](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/start-a-new-file/create-a-custom-new-document-profile.html)). New Document's Manage Profiles pop-up opens a profile to edit and resets one to the shipped profile (`file.newProfiles`, `file.newProfiles.edit`, `file.newProfiles.reset`; `file.new {profile}`). The profiles live in VectorCraft's own `New Document Profiles` folder next to the preferences; a profile that cannot be read or is larger than 64 MiB leaves the defaults and is reported. Tests: `tests::newdoc::an_edited_profile_starts_the_documents_of_its_category`, `the_profile_follows_the_preset_access_and_reset`, `profile_errors_name_the_file_by_its_name_outside_the_read_roots`, `a_damaged_or_oversized_profile_leaves_the_defaults_and_is_reported`, `profile_names_are_checked_and_editing_needs_the_folder`, `dialogs::new_document::tests::manage_profiles_edits_and_resets_the_profiles`. +- **Default fill and stroke from a profile:** when a New Document profile's Default Graphic Style is redefined (for example no fill and a 0.25 pt red stroke), documents from that profile start new art with that style's fills, strokes and effects, and Default Fill and Stroke (`paint.default`, D) gives the defaults and the selection the same look in those documents (VectorCraft's own rule). Test: `tests::newdoc::a_redefined_default_graphic_style_in_a_profile_is_the_default_fill_and_stroke`. - **Control bar with the Artboard tool:** while the Artboard tool is in use, the Control bar shows the active artboard's controls in place of the object controls: Preset, Portrait and Landscape, New Artboard, Delete Artboard, the Name field, Artboard Options, Rearrange All Artboards, the Transform link, Move and Scale Artwork with Artboard and, while the bar has room, the reference point with X and Y, and W and H with the Constrain Width and Height Proportions link. Each runs the command its Properties or Transform panel counterpart runs (`artboard.setProps`, `artboard.new`, `artboard.delete`, `tool.options {tool: "artboard"}`), and the reference point is the one the Transform panel uses. In an 800-point window the controls up to the Transform link fit, Move and Scale Artwork with Artboard show as their boxes alone with their names in tooltips, and the link opens the Transform panel with the artboard's position and size. Pointer and key tests in `panels/artboards.rs` cover the controls, W about the reference point, the orientation and the name. Public reference: [Using multiple artboards](https://web.archive.org/web/20210925094818/https://helpx.adobe.com/illustrator/using/using-multiple-artboards.html) (archived copy). - **Names of new and renamed artboards, brushes and patterns:** `artboard.new` and `artboard.setProps` trim the white space around the name they are given, as the Artboards panel's rename does, and a blank name gives the artboard its default name, Artboard N for the Nth artboard. `brush.new`, `brush.duplicate`, `brush.options`, `object.pattern.make`, `object.pattern.saveCopy` and `pattern.options` trim the name as the Brush Options dialog and the Pattern Options panel do, and compare the trimmed name with the names there are; a blank name gives the name each command gives when there is none, and Brush Options and Pattern Options keep the name. Tests in `tests/panelcmds.rs`, `tests/brushsym.rs` and `tests/pattern.rs` cover each command. Public references: [Using multiple artboards](https://web.archive.org/web/20210925094818/https://helpx.adobe.com/illustrator/using/using-multiple-artboards.html), [Brushes](https://web.archive.org/web/20251018101754/https://helpx.adobe.com/illustrator/using/brushes.html) and [Create and edit patterns](https://web.archive.org/web/20211031180358/https://helpx.adobe.com/illustrator/using/create-edit-patterns.html) (archived copies). - **Repeated brush names in a file:** a document or brush library file whose brushes repeat a name opens with the first brush of that name as stored and each later one numbered, as "Name 2", "Name 3" and so on, skipping names the file already has. Strokes that name the brush keep drawing the first one, and `brush.list`, `brush.options`, `brush.delete`, `brush.library` and the Brushes panel then reach each brush by its own name. This numbering is VectorCraft's own rule. Tests in `crates/brush/src/tests.rs`, `tests/brushsym.rs` and `tests/brushlib.rs` cover it. @@ -846,6 +866,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Parameter schemas:** a command can carry a machine-readable parameter schema (the new `vectorcraft-apischema` crate): each parameter's type, range, unit, whether it is required, its default, whether null counts as left out, and the API levels it was added and deprecated at. `engine.commands` lists the schema in the shape of a JSON Schema 2020-12 object schema, a test keeps the command's `params` text equal to the text the schema writes, and a new call has the params checked against it before the command runs (batch steps before the first step), with an error naming the parameter and no change to the document (a value nested past the schema's 16 levels is such a parameter error, and only a schema that is wrong in itself is an internal error); saved steps keep a key the schema does not name, and their values are checked. The View commands `view.capsLock`, `view.saved.new`, `view.saved.edit`, `view.saved.list`, `view.transparencyGrid` and `view.snapToGlyph.options` have schemas. The schemas belong to API level 1 (`vectorcraft_engine::schemas::API_VERSION`), and a test fails when a schema changes without a new level. Tests: `crates/apischema/src/tests.rs` (with `conformance.rs`, a separate check of the JSON form against the JSON Schema 2020-12 rules), `schemas::tests` and `cmd::views::tests::each_view_command_refuses_a_bad_value_naming_the_parameter` in `vectorcraft-engine`. - **Input schemas in the command listings:** `engine.commands` and the MCP tools `command_list` and `list_commands` give each command with a parameter schema an `inputSchema` next to `schema`: the same schema with the root `type` `"object"`, the form an MCP tool's input schema takes ([MCP schema reference](https://modelcontextprotocol.io/specification/2026-07-28/schema)). A command without a schema lists neither, and `brief` leaves out both schemas with the `params` text. Tests: `schemas::tests::engine_commands_list_an_input_schema_with_an_object_root` and `schemas::tests::an_input_schema_keeps_deprecation` in `vectorcraft-engine`, and `tests::conventions::command_listings_carry_input_schemas` in `vectorcraft-mcp`, which check every listed input schema against the JSON Schema 2020-12 rules. - **Command API reference:** `engine.apiReference` returns a Markdown reference written from the parameter schemas when it is asked for, and MCP serves the same text as the resource `vectorcraft://commands/reference` (`text/markdown; charset=utf-8`). Each command that has a schema gets a section in registry order with its label, menu path, API levels, what it writes, summary and return, and a table of its parameters (type, range with its ends marked included or not, unit, default, required, levels and description; members of objects as dotted rows). Commands without a schema, plug-in commands included, are left out. Schema text is escaped so it stays plain text in its table cell, the same build always returns the same bytes, and a reference past 1 MiB is an error rather than a cut-short text. The command's own schema raised the API level to 2. This is a VectorCraft documentation feature; no score changes. Tests: `cmd::apiref::tests` and `schemas::tests` in `vectorcraft-engine`, `resources::tests` in `vectorcraft-mcp`. +- **Tool option errors:** `tool.setOption` checks every option it is given before it sets any: an option the tool doesn't have, a value of the wrong type, a number outside the tool's range or an unknown choice is an error naming the tool and the option (``tool `smooth`: `fidelity` must be a number from 0.05 to 100``), and no option, saved preference or undo step changes; `{}` only reads. Most ranges are the ones each tool's setter clamped to; the Arc tool's `lengthX` and `lengthY` take more than 0 up to 1e6 and the Line tool's `length` 0 to 1e6, where a negative length was taken as its absolute value. The Live Paint tools' `width` and the Shape Builder's `gapLength` are still set to the nearest end of their range. A Tool Options dialog with a refused value stays open. This is VectorCraft's own rule; no score changes. Tests: `option_check::tests` in `vectorcraft-tools`, `tests::toolsettings` in `vectorcraft-engine`, `tests::liquify` in `vectorcraft-mcp`, `dialogs::freehand::tests::a_refused_fidelity_keeps_the_dialog_open`. - **Automation:** - Variables: Update Data Set writes what the art holds into the active data set for the variables that data set holds, and keeps the data set's value for a text, image or graph variable whose objects are locked or inside a locked layer or group; `dataset.update {all: true}` also adds the other variables that the art reports a value for. - Variables: `dataset.select`, `dataset.next` and `dataset.prev` rewrite type and apply the other values on hidden objects and in hidden layers and groups, which stay hidden unless a visibility value shows them, so a layer shown later holds the selected data set's text; objects that are locked or in a locked layer or group are skipped, except by a visibility value. @@ -859,6 +880,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Batch…: Override Save and Override Export name each file with the extension of the format the step writes, however the step spells the format (`.svg` and `SVG` give `.svg`, `png8` gives `.png`), in `action.batch`. - Batch…: Override Export writes the files of an Export for Screens or Export Assets step into a folder for each source file or data set inside the destination folder, under the names the export gives them (`action.batch`). The folder and file names drop trailing periods and spaces (`a..svg` gives `a`). When two source files would get the same name that way (compared without case), or a later file's folder or file would take the name of an output an earlier file wrote, of a source file in the destination folder or, for data sets, of a file already there, Batch adds `-2`, `-3`… to the later one's name. - Batch…: when a step fails on a file or data set, the error names the step by its place in the action's steps, from 1, counting the Open steps the batch skips (`action.batch`). This numbering is VectorCraft's own rule. Tests `cmd::fileio::action_batch::tests::{a_folder_batch_error_names_the_step_in_the_commands_sent, a_recorded_open_that_fails_is_the_first_step, a_data_set_batch_error_names_the_step_in_the_commands_sent, a_redirected_export_that_fails_keeps_its_place, a_source_that_does_not_open_names_no_step}`. + - Batch…: a step refused before any file opens (no command, a command the engine does not have, params its command refuses, a nested batch or `prefs.import`) is named the same way, by its place from 1 and its command id (`action.batch`). Tests `cmd::fileio::action_batch::tests::{a_refused_step_is_named_by_its_place_from_1, the_parameter_check_names_the_refused_step, steps_with_ids_that_are_not_engine_commands_are_refused}`. - Actions panel menu: Save Actions… writes the current action set with all its actions to a file, and Load Actions… adds the set from such a file to the panel ([Manage a set of actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/manage-a-set-of-actions.html); `ui.actionSet.save`, `ui.actionSet.load`). The file is VectorCraft's own action set file (`.vcactions`); a loaded set named like one in the panel gets the next free number. - Actions panel menu: Load Actions… keeps a step whose command this build or its installed plug-ins do not have, and reports each one when the set loads: the `ui.actionSet.load` answer lists the action, step and command id (`unknownCommands`, `unknownCount`), and the status bar names the first and the count. An action with such a step included does not play, and the error names the step and its id before any step runs; an excluded one does not stop it. These are VectorCraft's own rules. Tests `panels::actions::tests::{load_actions_reports_steps_with_unknown_commands, load_actions_bounds_what_it_reports_of_unknown_commands, an_action_with_an_unknown_command_does_not_play}`. - Actions panel menu: Save Actions… does not write a set with a step that sets a folder preference (the Fonts, Plug-ins, Templates and Recovery folders and the two scratch disks) to a folder, and names the action and the preference instead; an empty folder and the scratch disk choices Startup and None save. Export Preferences leaves out both scratch disks, and `ui.inspect` under automation read roots leaves such a folder outside them out of recorded steps. These are VectorCraft's own rules (`ui.actionSet.save`, `prefs.export`). @@ -876,11 +898,13 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Actions panel: the panel menu's Insert Stop… opens Record Stop, with a Message box and Allow Continue, and adds a stop to the recording in progress, after the selected command, or at the end of the selected action ([Insert stops in actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/insert-stops-in-actions.html); `ui.action.insertStop`). A playing action waits at the stop and shows the message so the user can do a manual task, and Play Current Selection plays the rest ([Illustrator CS5 help](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=459); `ui.action.continue`). With Allow Continue, the message box also has Continue. VectorCraft's own rules, which the pages do not cover: an empty message still waits, Stop Playing/Recording ends the playback and keeps the steps already played, the rest plays on the document active then, a stop waits at every playback speed, at Accelerated the steps between two stops are one undo step, Batch… refuses an action with an included stop, and Delete Selection on a selected step deletes that step, a stop or a command, without asking (`ui.action.deleteStep`). - Actions panel: the panel menu's Insert Menu Item… adds a menu command to the recording in progress, after the selected step, or at the end of the selected action, without running it, and playback runs it as the menu does ([Insert non-recordable tasks into actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/insert-non-recordable-tasks-into-actions.html); `ui.action.insertMenuItem`). The dialog's Find box picks the one item that matches the words typed, and a click on a listed item picks it. VectorCraft's own rules, which the page does not cover: items that open a dialog, Image Trace's Make and Make and Expand, Pattern's Make and Edit Pattern, and the File, Window and Help menu items are not listed, and an action holds at most 10,000 steps and its set file at most 8 MiB, for stops too. - Actions panel: Insert Menu Item… also lists the Object › Align items and the View menu commands that act on the window rather than the document (Outline, Pixel Preview, Trim View, Presentation Mode, Screen Mode, zoom, fit, Rotate View, and the show, hide and snap items), which the help page names among the commands that cannot be recorded ([Insert non-recordable tasks into actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/insert-non-recordable-tasks-into-actions.html); [Align and distribute objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/align-and-distribute-objects.html); `ui.action.insertMenuItem`, `ui.action.play`). VectorCraft's own rules, which the pages do not cover: an Align step keeps the Align To choice of its insertion, and one that aligns to the key object stops the playback when there is no key; a View menu step plays in its place at every speed and adds no undo step, so at Accelerated the steps on each side of it are one undo step each; Batch… refuses an action with one; and a set file with one is version 6. Tests `panels::actions::tests::{an_inserted_view_item_plays_in_its_place_at_accelerated, an_inserted_view_item_plays_step_by_step_and_with_pauses, an_inserted_view_item_plays_up_to_a_stop, a_view_step_played_while_recording_is_recorded, a_saved_view_step_survives_as_version_6, an_inserted_align_item_keeps_the_align_to_of_its_insertion, an_align_step_to_the_key_object_fails_without_a_key}`. + - Actions panel: the error of a played step that fails names the step by its place in the expanded action, 1 for the first step, counting excluded steps and stops, at every playback speed and after a stop (`ui.action.play`, `ui.action.continue`). A failing step of a recorded batch is named by the batch's place and its own command. The numbering is VectorCraft's own rule. Tests `panels::actions::tests::{an_error_after_a_view_item_names_the_step_in_the_action, a_failing_view_item_names_the_step_in_the_action, an_error_counts_excluded_steps, an_error_in_a_recorded_batch_names_the_batch_step, an_error_of_the_whole_batch_names_no_step, a_paced_error_names_the_step_in_the_action, an_error_after_a_stop_names_the_step_in_the_action}`. - Actions panel: with a path selected, the panel menu's Insert Select Path adds a step that selects that path to the recording in progress, after the selected step, or at the end of the selected action, without changing the selection ([Insert non-recordable tasks into actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/insert-non-recordable-tasks-into-actions.html); `ui.action.insertSelectPath`, `select.storedPath`). VectorCraft's own rules, which the page does not cover: the selection must be one whole path or compound path that can be selected, the step stores the path's id and a fingerprint of its anchors, and playback selects the path only while it is still there unchanged and can be selected, else the step is an error and the selection stays; the row reads Select Path, and a set file with the step is version 5. - Actions panel: the panel menu's Select Object… opens Set Selection, where the note typed names the objects to select, and adds a step to the recording in progress, after the selected step, or at the end of the selected action; playback selects the objects whose Attributes note matches it, and the steps after it act on them ([Insert non-recordable tasks into actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/insert-non-recordable-tasks-into-actions.html); `ui.action.insertSelectObject`, `select.byNote`). VectorCraft's own rules, which the page does not cover: the note matches anywhere and in any letter case unless Case Sensitive or Whole Word is checked, hidden and locked objects are left out, the objects found replace the selection, a step that finds none stops the playback with an error, and the note is at most 1,024 bytes. Action sets with the step save as version 4. - Actions panel: Delete Selection deletes the selected action set with its actions and keeps the other sets ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html); `ui.actionSet.delete`). VectorCraft's own rules, which the overview does not cover: deleting a set asks first, Shift-click on a set's name selects a range of sets to delete together, the panel menu's Delete does the same, and Default Actions and the last set can be deleted. Undo does not bring a deleted set back. - Actions panel: the panel menu's Duplicate copies the selected action, else the current action set with all its actions ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html); `ui.actionSet.duplicate`). VectorCraft's own rules, which the overview does not cover: the copy goes right after the original, is named after it with " copy" added and is selected. - Actions panel: the panel menu's Reset Actions asks first; OK replaces the sets in the panel with the default set, and Append adds the default set after them ([the help page](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/manage-a-set-of-actions.html); `ui.actionSet.reset`). VectorCraft's own rules, which the page does not cover: the default set is VectorCraft's own Default Actions set; after OK it is current and selected, and no action or step is selected; Append names its copy with the next free number (`Default Actions 2`) and keeps the current set; Cancel changes nothing; the item is off while an action records or plays, waiting at a stop included; Undo does not bring the old sets back. Tests `panels::actions::tests::{the_panel_menus_reset_actions_asks_first_and_is_off_while_an_action_runs, reset_replaces_every_set_with_the_built_in_set_and_clears_what_named_the_old_ones, reset_on_the_built_in_set_makes_it_current_then_changes_nothing, reset_append_adds_the_built_in_set_with_a_free_number_and_keeps_the_rest, reset_refuses_bad_params_and_a_running_action_and_changes_nothing}`, `dialogs::tests::reset_actions_ok_replaces_append_adds_and_cancel_keeps_the_sets`. + - Actions panel: the panel menu's Replace Actions… opens a file and puts the set it holds in place of every set in the panel ([the help page](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html); `ui.actionSet.replace`). VectorCraft's own rules, which the page does not cover: the file is read as Load Actions… reads it (`.vcactions` and `.aia`, with the same limits and reports); the built-in Default Actions set goes too; the file's set keeps its name and becomes current and selected, and no action or step is selected; a canceled pick, a file that can't be read or is refused (an empty one too) changes nothing; the item asks no question first and is off while an action records or plays, waiting at a stop included; Undo does not bring the old sets back. Tests `panels::actions::tests::{the_panel_menus_replace_actions_puts_the_files_set_in_place_of_every_set, replace_actions_clears_what_named_the_old_sets_and_reads_aia_files, replace_actions_refuses_bad_params_bad_files_and_a_running_action}`. - Batch… over data sets names each file after the document and the data set (`action.batch`). It writes `/`, `\`, `:`, `<`, `>`, `"`, `|`, `?`, `*` and control characters in the data set's name as `-`, and adds `-2`, `-3`… to a name an earlier data set used. - Batch… offers File + Number, File + Data Set Name, and Data Set Name for a Data Sets source. The dialog defaults to File + Number; `action.batch` without `datasetFileNaming` keeps File + Data Set Name. An output already in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix. [Batch options](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/batch-options.html). - The Batch dialog shows its data set File Name row only when Destination is Folder, and keeps the choice while another destination is picked. With None or Save and Close it does not send `datasetFileNaming`. @@ -895,6 +919,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Save for Web: Preview in Browser writes each preview's page and images to a folder of its own inside `VectorCraft Save for Web` in the system's temporary folder. A later preview, from the same app or another one running, does not overwrite an earlier one. Each preview first removes the preview folders there that are an hour old or older and, on Linux, macOS and FreeBSD, belong to the current user; it leaves other files and folders alone. The folders a preview makes there are open to their owner only on those systems. When `VectorCraft Save for Web` is a link or is not a folder, or on those systems belongs to another user or can be written by other users, the preview goes to a new folder of its own in the temporary folder, which a later preview removes once it is an hour old (`file.saveForWeb.browser`). - Save for Web: Optimize to File Size… opens rows for a desired file size in K, Start With (Current Settings, Auto Select GIF/JPEG) and, with slices, Use (Total of All Slices, Each Slice, Current Slice); OK takes the settings whose files fit and shows the size found, or says that no setting tried fits ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=395)). The search lowers JPEG quality or palette colors (GIF then lossy) and encodes at most 32 trial settings; Auto Select chooses GIF for transparent art or art of at most 256 colors and JPEG otherwise. The slices share one setting, so every Use choice changes all of them (`webExport.optimizeToFileSize`). Scores and estimates are unchanged. - Save for Web: while Alt (Option on macOS) is held, the dialog's Cancel button reads Reset, which puts the remembered settings back on the document's active artboard and leaves the dialog open (`ui.dialogReset`). + - Save for Web: the color table's trash button and Delete Color in its menu remove the selected GIF or PNG-8 colors, and their pixels take the nearest color left in the palette ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=404)). Click selects one color, Shift-click a range and Ctrl-click (Command-click on macOS) adds or removes one ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=398)). After the first deletion the table is a fixed Custom palette, so deleted colors stay out when the preview updates. These rules are VectorCraft's own: a deleted color is no longer locked, transparent or web-shifted; deleting every opaque color is refused; Restore Generated Table in the menu, or another reduction, goes back to the generated palette; presets and the remembered settings keep the edit (`colorTable.deleted`, `colorTable.customPalette`). Fixed palettes can also use all 256 entries when nothing is transparent. Scores and estimates are unchanged. - Export for Screens, Save for Web (slice images, and files named after the document's title) and the Libraries panel name files with the characters Windows does not allow written as `-` and with a `-` after a Windows device name such as `CON`, on every platform (`document.exportForScreens`, `document.exportForWeb`, `library.create`). - Variables (data merge): text, visibility and image variables bound to objects (an object may carry several), dataset rows applied in one undo step (`variable.*`, `dataset.*`) from a Variables panel and Window › Variables, with dialogs to define, bind and edit, Make Text/Visibility/Image Dynamic, Capture/Update Data Set, CSV import/export (`dataset.import` / `dataset.export`), and a row in italics when an edit leaves the art not matching it; an image dataset value is a file path and apply keeps the object's bounds; bindings let go of deleted art and locked art is left alone except by visibility values; every command, like the rest, is drivable over MCP and the CLI. - Export for Screens numbers distinct row files whose names collide, compared without case, as `-2`, `-3`… instead of leaving them out; identical rows still write one file. It puts row folders that differ only in case into one folder (`document.exportForScreens`). @@ -903,8 +928,10 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Graphs: the Graph Data window's Import Data reads a UTF-16 text file without a byte-order mark by the same rule as Import Data Sets…, instead of filling the cells with NUL characters. It reads a file cut short by one byte, or with an unpaired surrogate, as it reads one after a byte-order mark. - Graphs: in the Graph Data window, the pointer becomes a column-resize arrow over a column's right edge, and dragging the edge sets that column's width in whole digits, from 0 to 20 as Cell Style's Column Width allows. The columns after it move along. Cell Style's Column Width still sets every column, the dragged ones included ([Adjust decimal digits and column width](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/visualize-data/adjust-column-width.html)). - Variables: Import Data Sets… (`dataset.import`) defines the variables a file's header names that the document lacks, unbound. `#Shown` defines a visibility variable, `@Photo` defines an image variable, and a header without a prefix defines a text variable. A header that is a variable's exact name keeps naming it, and any other `%` header (graph data files) is refused. + - Variables: Import Data Sets… (`dataset.import`) reads `%` columns instead of refusing them: `%Sales` defines or names the graph variable `Sales`, and each cell is the path of a graph data file, read as the Graph Data window's Import Data reads one and kept as the data set's graph value. A relative path is taken from the CSV file's folder, or from `base`. A missing, unreadable or larger than 1 MB file fails the import with its line and column, and the document is left as it was (`crates/engine/src/tests/variables.rs`). - Variables: Load Variable Library… in the Variables panel menu (`variable.loadLibrary`) replaces the document's variables and data sets with a variable library's, read from its XML file, in one undo step: every data set is deleted, and every variable is deleted with its bindings and values, except a variable the library also declares with the same kind, which stays bound so the library's data sets change its objects (#4136); then the library's other variables are defined, unbound: text, visibility, image (linked file) and graph variables, and variables without a known `trait` as unknown. Its data sets take text values from each value's `p` elements, one paragraph each, visibility values from `true` or `false`, image values from a file's absolute path or `file:` URL, and graph values from a `data` element of series names and rows. - Variables: Save Variable Library… in the Variables panel menu (`variable.saveLibrary`) writes the document's variables of every kind and its data sets as a variable library's XML file, which Load Variable Library reads back with the same variables, kinds, data set names and values. + - Variables: opening an SVG whose variable data holds variables that aren't text warns about them by kind (Visibility, Linked File, Graph Data, or Unknown for a variable without a `trait`) with a count for each, and the status bar shows those kinds and the list in the interface language. Any other `trait` stays as the file writes it, in backticks, so a `trait` such as `Visibility` or one with a comma stays a single entry. This is VectorCraft's own rule. Regression tests: `svg_variable_data_warning_names_each_kind_left_out` in `crates/engine/src/tests/variables.rs`, `svg_variable_kinds_left_out_translate_in_every_complete_catalog` in `crates/ui-egui/src/i18n/tests.rs`. - Variables: Variable Options… in the Variables panel menu, or a double click on a variable, shows the variable's name and kind, and OK changes either or both in one undo step (`variable.rename {name, newName?, kind?}`), as the [Work with variables](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/work-with-variables.html) page describes. VectorCraft's own rule for a kind change: objects that can't hold the new kind are unbound, and the variable's values in every data set are dropped. - Variables: Import… in the Variables panel menu (`variable.import`) opens one file dialog for a data source and reads it by its extension: a CSV, TSV or TXT file as Import Data Sets… reads it, and an XML file as Load Variable Library… reads it. Other extensions are refused. - JSON-lines control channel with real egui pointer and keyboard injection. @@ -925,7 +952,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: `$.fileName` is a read-only name of the script file in use ([the help page](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/)). VectorCraft's own rules: it names the file of the code that reads it, so a function a file included with `#include` or run with `$.evalFile` defined, or one an earlier run of a named engine kept, gives its own file and not the calling file; code from a script given as `source`, and kept code whose place the engine dropped, gives an empty name, and code that `eval` or `Function` compiled gives the file being run. `crates/engine/src/tests/script_include.rs`, `crates/engine/src/tests/script_engines.rs`. - Scripts: a runtime error is shown at the line that was running ([the help page](https://extendscript.docsforadobe.dev/extendscript-toolkit/debugging-in-the-toolkit/)). VectorCraft's own rules: an error in code an earlier run of a named engine compiled, such as a function it defined, is reported at that code's file, line and column (the earlier run's script, a file it included or a file its `$.evalFile` ran), while the report and its console line keep the calling run's name; a script given as text is named by its run's name, and each engine keeps these places for 8 MiB of source maps, the oldest going first. An error in code whose place is gone, or in code that `eval` or `Function` compiled, is reported without a line and column, and the code still runs. `crates/engine/src/tests/script_engines.rs`. - Scripts: `$.line` is the line of the running script, counting from 1, and `$.stack` is the current stack trace ([the help page](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/)). VectorCraft's own rules: both count lines in the file the code is in (the script, a file it included, a file `$.evalFile` ran, or the file of an earlier run of the named engine), and `$.stack` writes each frame as `name@file:line`, outermost first; code that `eval` or `Function` compiled keeps its own line in `[eval]`, and code whose place the engine no longer keeps is at line 0 of `[unknown]`. `crates/engine/src/tests/script_include.rs`, `crates/engine/src/tests/script_engines.rs`, `crates/js/src/extension_tests.rs`. - - Scripts: `File` and `Folder` ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)) name files and folders by platform or URI path, with `name`, `fsName`, `absoluteURI`, `relativeURI`, `parent`, `Folder.current` and `encode`/`decode`, and read them: `exists`, `length`, the dates, `getFiles` with a mask or a function, and `open('r')` with `read`, `readln`, `readch`, `seek`, `tell` and `close`, decoding by byte order mark, `encoding`, UTF-8 or CP1252. VectorCraft's own rules: a script reads only in its own folder and below (and inside the automation read roots when they are set); any other path and a network or device path are refused before anything is looked up, and a link that leads out is refused as well (`false` or `null`, with `error` set); a file is read whole up to 8 MiB and a run reads up to 32 MiB; writing, the file dialogs and `execute` are not available yet. `crates/engine/src/tests/script_io.rs`. + - Scripts: `File` and `Folder` ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)) name files and folders by platform or URI path, with `name`, `fsName`, `absoluteURI`, `relativeURI`, `parent`, `Folder.current` and `encode`/`decode`, and read them: `exists`, `length`, the dates, `getFiles` with a mask or a function, and `open('r')` with `read`, `readln`, `readch`, `seek`, `tell` and `close`, decoding by byte order mark, `encoding`, UTF-8 or CP1252. VectorCraft's own rules: a script reads only in its own folder and below (and inside the automation read roots when they are set); any other path and a network or device path are refused before anything is looked up, and a link that leads out is refused as well (`false` or `null`, with `error` set); a file is read whole up to 8 MiB and a run reads up to 32 MiB; `execute` is not available. `crates/engine/src/tests/script_io.rs`. + - Scripts: `File` and `Folder` write ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)): `open('w')`, `open('e')` and `open('a')` with `write` and `writeln` by `lineFeed`, `copy`, `remove` (a folder only when empty), `rename`, `folder.create()`, the `length` and `readonly` setters, and `File.openDialog`, `File.saveDialog`, `Folder.selectDialog`, `openDlg`, `saveDlg` and `selectDlg`, with a `filter` of file types or a filter function and `multiSelect`. VectorCraft's own rules: a script writes only in `Folder.temp` (one for the run, deleted when it ends), its own `Folder.userData` next to the settings, and what a person allowed it in a file dialog, once or always; Always keeps the grant for that script file with that text by its SHA-256 and for the sources the run evaluated (`$.evalFile`, `eval`, `Function`), so a run that evaluates other code, or whose named engine holds other code, loses it first; `script.grants` lists the grants and `script.grants.revoke` removes them; the settings folder is kept out of every grant; the commands a script runs with `vc.run` read and write only in the same places and the open documents' own files; a run with nobody to ask gets `null` from the dialogs; a file is written at close or when the run ends, 8 MiB a file and 32 MiB a run, and named in `written`, also after a run that failed. `crates/engine/src/tests/script_io.rs`. - Scripts: `#strict on` (and `//@strict on`) runs the script with the checks the [`$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/) help page gives for `$.strict`: an assignment to a read-only property throws a `TypeError`, and so does a new property on an object that takes none. VectorCraft's own rules: a getter-only property counts as read-only, the objects that take no new properties are the non-extensible ones (`Object.preventExtensions`, `seal`, `freeze`, and the frozen `vc` and `$` objects), the last `#strict` line of the script and its includes sets the whole run, a file `$.evalFile` runs keeps its own line's checks for its code, and the rest of ES5 strict mode stays with `'use strict'`. Without the line, runs are unchanged. `crates/engine/src/tests/script_include.rs` (`strict_on_*`, `strict_mode_in_eval_file_is_scoped`), `crates/js/src/interp_tests.rs` (`strict_writes_are_separate_from_es5_strict`). - Scripts folder: File › Scripts lists the `.js` and `.jsx` files of the `Scripts` folder next to the preferences, each named after its file without the extension, with each subfolder as a submenu, above Check Script… and Other Script… (https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/install-and-run-scripts.html). VectorCraft's own rules: the folder is read again when the window becomes active and when the File menu opens (in the macOS menu bar, when any of its menus opens, and the new listing shows the next time the menu opens), links are not followed, and one read stops at 2,048 entries, 512 scripts, 128 subfolders, 4 levels or 250 ms. `script.listInstalled` returns the listing. `crates/engine/src/tests/script_folder.rs`, `crates/ui-egui/src/tests/scripts_menu.rs`. - Open Recent Files under `--automation-read-root`: the control channel's `ui.menu.list` and `file.recentFiles` leave out the recent files outside the read roots, the other rows keep their ids, and `file.openRecentN` for one outside them answers `no such recent file`, as an empty slot does. `crates/ui-egui/src/tests/automation.rs`. @@ -939,6 +967,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Linked images in SVG output under `--automation-read-root`: the same outputs, and `clipboard.exportSvg`, refuse an SVG or SVGZ that would name a linked image's file outside the read roots (`images: link`, an image whose pixels the document doesn't hold, or `preserveEditing`), before any file or folder is written, with an error that names no file or folder; Copy in a frame a request drives then puts no SVG on the system clipboard. Embedded pixels, a file inside the roots, a relative path that leads inside them and a URL are written as before, and the person at the keyboard exports every link as stored. The check covers the art drawn for placed documents and leaves out what the file leaves out: hidden art in symbols, patterns and graph designs, opacity masks in SVG Tiny 1.2, and objects drawn as images for effects SVG has no filter for. `crates/engine/src/tests/links.rs` (`confined_svg_output_refuses_a_linked_image_file_outside_the_read_roots`, `svg_output_names_linked_image_files_a_caller_may_read`, `confined_clipboard_svg_refuses_a_linked_image_file_outside_the_read_roots`, `confined_preserve_editing_svg_refuses_a_brush_library_entry_it_cannot_read`, `confined_svg_output_checks_only_the_linked_images_it_writes`, `confined_svg_output_writes_a_colorized_gray_image_without_its_file`, `confined_svg_output_checks_the_images_of_placed_documents`, `confined_svg_output_leaves_hidden_symbol_art_unchecked`, `confined_svg_tiny_output_leaves_opacity_mask_images_unchecked`, `confined_svg_output_checks_the_images_drawn_for_pixel_effects`), `crates/ui-egui/src/tests/automation.rs` (`control_svg_export_refuses_a_linked_image_file_outside_the_read_root`), `crates/ui-egui/src/dialogs/svg_options.rs` (`show_code_leaves_out_a_linked_image_file_outside_the_read_roots`). - Clipboard flavors under `--automation-read-root`: `clipboard.flavours` leaves out the SVG, and its markup as text, that `clipboard.exportSvg` refuses. `crates/engine/src/tests/links.rs` (`confined_clipboard_flavours_leave_out_a_withheld_svg`). - Preserve Editing SVG under `--automation-read-root`: the native document an SVG or SVGZ carries leaves out an Export for Screens folder outside the read roots, and keeps the other export settings and the art; the open document keeps the folder, and a folder inside the roots is kept. `crates/engine/src/tests/links.rs` (`confined_preserve_editing_svg_leaves_out_an_export_folder_outside_the_read_roots`). + - Native document output and linked images under `--automation-read-root`: the outputs that carry the native document (a native file or template, an EPS file, a `.ai` or `.ait` file of every artboard, a PDF of every artboard with Preserve Editing, also from `document.exportPdf`, the saves and Export for Screens rows) are refused, before any file or folder is written, with an error that names no file or folder, when that document names a linked image or placed file, a kept relative path or a data set's image outside the read roots, or holds a stored brush entry that does not read as a brush; files without the native document are written. Those documents, and the documents Package writes or rewrites, leave out an Export for Screens folder outside the read roots, and Package refuses a linked file it copies as it is whose native document keeps one; the open document keeps its links, data sets and folder. An Export for Screens row that writes one artboard is checked against that artboard's art, and each asset, layer or selected object writes its own native, `.ai` or EPS file. `crates/engine/src/tests/links.rs` (`confined_native_output_refuses_a_linked_image_file_outside_the_read_roots`, `confined_native_output_refuses_a_data_set_image_outside_the_read_roots`, `confined_native_output_leaves_out_an_export_folder_outside_the_read_roots`, `confined_screens_rows_check_the_artboard_each_file_holds`), `crates/engine/src/tests/package.rs` (`a_confined_package_refuses_a_linked_file_that_keeps_an_export_folder_outside_the_read_root`), `crates/engine/src/cmd/fileio/tests_screens.rs` (`each_piece_writes_its_own_native_document`). + - Exporter plug-ins and Package's unreadable linked files under `--automation-read-root`: an exporter plug-in's format, whose plug-in is given the native document's JSON, is refused before the plug-in runs when that document links a JavaScript file, a linked image or placed file or a data set's image outside the read roots, and the JSON leaves out an Export for Screens folder outside them; Package refuses, before anything is written, a linked native document, PDF, `.ai` or EPS file whose native document can't be read to check it (a PDF that needs a password to open, damaged editing data), and copies a PDF or EPS file without editing data. Errors name no file or folder, and the person at the keyboard exports and packages as before. `crates/engine/tests/plugin_export.rs` (`a_confined_exporter_is_refused_stored_paths_outside_the_read_roots`), `crates/engine/src/tests/package.rs` (`a_confined_package_refuses_a_linked_file_whose_editing_data_cannot_be_read`). - Linked-file and font-file searches under `--automation-read-root`: `links.findFiles` and `text.findFontFiles` replies, also later polls and stops of a search another client started, leave out the files found, a link's saved path and the folder searched outside the caller's read roots, and a failed search gives its reason without the path; `image.info` gives `link: null` for a linked file outside them; `text.addFontFiles` gives `folder: null` and the copies' file names when the Fonts folder is outside them. `crates/engine/src/tests/linkfiles.rs`, `crates/engine/src/tests/fontfiles.rs`, `crates/engine/tests/font_folder.rs`. - Swatch, brush, symbol and graphic style library lists under `--automation-read-root`: every library stays listed, the paths of library files and the user library folder outside the read roots are `null`, a library loaded from outside them is listed and found as `loaded/` and keeps that id for the session unless a library loaded later without a file shows that id itself, which moves it to the next free `loaded/ (N)`, and the app's own list is not changed. `crates/engine/src/tests/library_roots.rs`. - Preferences commands under `--automation-read-root`: `prefs.get`, `prefs.list`, `prefs.set` and `prefs.reset` show folder preferences outside the read roots as `null` and leave out an export preset's folder outside them, and the preferences are not changed. `crates/engine/src/tests/prefs_roots.rs`. @@ -946,6 +976,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Plug-in, recovery and script report replies under `--automation-read-root`: `plugin.list`, `plugin.info` and `plugin.safeMode` name the plug-in folder, failed files, plug-in sources and disabled plug-ins' files outside the read roots by file name or `null`, `file.recovery.*` leave out a document's original file and the recovery folder outside them, and `ui.inspect`'s `scriptReport` names files a run wrote outside them by file name. `crates/engine/src/tests/plugins.rs` (`plugin_list_leaves_out_paths_outside_the_read_root`), `crates/engine/src/tests/recovery.rs` (`recovery_replies_leave_out_paths_outside_the_read_root`), `crates/ui-egui/src/tests/automation.rs` (`ui_inspect_script_report_leaves_out_files_outside_the_read_root`). - Scripts: `alert`, `confirm` and `prompt` open dialogs during a run, each with a Stop button that ends the run and puts every document back. In the app the run waits at the call for the person's answer; a run over MCP or the command line takes its answers in order from `script.run`'s `answers`, and the report lists each dialog with its answer. `crates/engine/src/tests/script_dialogs.rs`, `crates/ui-egui/src/tests/script_dialogs.rs`. - Parameter keys: the engine refuses a key that a command's params description doesn't name before the command runs, in every build and for every caller, including the app's own calls, the commands a command runs and the steps of `command.batch` and `action.batch`. An action recorded by an older version still plays from the Actions panel and the Batch dialog (`Session::replay`). `crates/engine/tests/it/param_keys.rs`. + - Parameter key lookups: the engine reads the params description of each built-in command, with the descriptions its `…` entries name, once per process, and answers the key check and the `ids` and `id` questions of each later command from that reading. A plug-in command's description, and a description whose `…` entries name a plug-in command, are still read each time. The accepted keys, the answers and the error messages are the same. In a release build on a one-object document, `object.move` with `ids` and `dx` takes 48 µs of thread CPU time per command instead of 61 µs, and `select.set` with `ids` 2.3 µs instead of 3.2 µs (medians of 7 alternating runs of 20,000 commands in one process, measured while other builds were running; `tests::params_cache::bench_params_keys_once`). The time is saved per command, in scripts, batches and MCP or plug-in call loops, and does not grow with the size of the document. `crates/engine/src/tests/params_cache.rs` compares every built-in command's answers with those of a fresh parse. - Effect parameter types: `effect.apply`, `appearance.addEffect` and `effect.setParams` refuse an effect parameter of another type than the effect reads, for keys only the params text names too (the earlier 3D `perspective`, `lightAzimuth` and `lightElevation`, Scribble's `variation`, Outline Stroke's `width`, Gaussian Blur's `linear`), a Crop Marks `style` other than `roman` or `japanese`, and an installed plug-in effect's parameter of another type than its manifest gives it, in a `command.batch` step too, with the document and undo history unchanged; a replayed action still plays. `effect.setParams` checks the parameters against a Warp's new style, and refuses a `visible` that is not true or false, in a replayed action too. `crates/engine/src/tests/params.rs` (`an_effect_parameter_without_a_default_is_held_to_its_type`, `effect_commands_refuse_an_undefaulted_parameter_of_the_wrong_type`), `crates/engine/src/tests/plugins.rs` (`live_effect_plugins_reshape_editable_art_and_expand`), `crates/engine/src/cmd/effectcmd/tests.rs` (`set_params_refuses_a_visible_that_is_not_true_or_false`, `set_params_checks_the_effect_it_leaves`). - MCP server with 33 tools (drawing, text, effects, Pathfinder, transforms, graphs, text wrap, export, screenshots, undo/redo, UI inspect/screenshot aliases, any command), attached to the running app or headless. Headless and remote `command_list` include desktop `UI_COMMANDS` (`ui: true`); a UI-only id still needs `--connect` to run. Eight prompts (poster, icon-set, recolor, trace-and-style, export-set, check-spelling, variables-bind, path-tools). Effect ids are not command ids. Prefer a CLI built from the checkout when a release binary lags (#6460). `vectorcraft://commands/reference` serves the API reference. Tool descriptions and replies agree with the engine: format lists come from its format table, `save_file` says it keeps the document's own format, `inspect_document` reports the paint type's characters show, and selection exports report the encoder's warnings. `--automation-read-root` / `--automation-write-root` (on `vectorcraft-cli mcp` and on `vectorcraft --control`) confine the files commands read and write to chosen folders, links followed, with the flags PhotoCraft takes (#832); each flag may be given more than once, a path inside any of its folders being allowed (#3546, `file_access::tests::several_roots_of_a_kind_each_grant_their_access`, `cli::mcp_automation_roots_take_several_folders`). A long export can be cancelled (`notifications/cancelled` stops it at the next page or group and writes nothing), reports page progress to a client that sent a progress token, and does not make other requests wait: engine-free ones answer at once, the rest are refused as busy after two seconds (#2165, #2171, #2172). - MCP window captures from an app that does not send the image back go through a file in a new folder inside the system's temporary folder, which only the user can open on Unix, instead of a fixed name in the shared folder; the folder is removed after the read, also when the capture or the read fails (`tests::conventions::an_old_app_captures_the_window_in_a_new_private_folder`). @@ -990,6 +1021,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - A layer whose Layer Options › Print is off shows its name italic in the Layers panel, and while its row is dragged, as the reference application shows non-printing layers (#5739); a printing layer stays upright and ticking Print again restores the upright name (`panels::layers` test `a_layer_that_does_not_print_has_its_name_italic`). - In the Layers panel only the primary mouse button drags. A drag with the right or middle button on a row, a guide row, the selection square, the eye or lock column or a target circle moves, copies, hides, locks and transfers nothing and records no undo step, and a right-click still opens the row's menu (`panels::layers` test `only_the_primary_button_drags_rows_guides_art_columns_and_appearances`). - Rows or the selection square dragged over the Layers panel's list show the copy cursor while Alt is held, as the drop then copies, and the grabbing hand otherwise; the cursor follows Alt pressed or released mid-drag. The copy cursor is the panels' add cursor (#8241): on Windows and X11, which have no system copy cursor winit can show, the white arrow with a plus. Over the trash and New Layer, which delete or duplicate with or without Alt, the hand stays, and guide rows keep their own cursor (#8217; `panels::layers` tests `alt_shows_the_copy_cursor_while_rows_are_dragged` and `drag_cursor_shows_a_copy_only_where_the_drop_copies`). + - An Alt-drag in the Layers panel copies rows above or below one of their own rows (`layer.move` with `copy` and that row as the target), and the bottom layer Alt-dragged into the empty space under the list is copied below itself. So the top layer dragged up, the bottom layer dragged down and a document's only layer are copied, as any other row is. A move onto its own place, and a copy inside itself, still change nothing (#8237; `panels::layers` tests `alt_dragging_the_top_layer_up_or_the_bottom_layer_down_copies_it` and `a_lone_layer_alt_dragged_up_or_down_is_copied`; engine test `a_copy_goes_above_or_below_a_row_it_copies`). - Rows dragged in the Layers panel and held within 28 points of the list's top or bottom edge scroll a long list that way, faster nearer the edge (60 points a second at the band's inner side, 340 at the edge, at every frame rate), and keep scrolling while the pointer stays still, so a row out of view can take the drop (a move, or a copy with Alt); the Libraries panel's list scrolls by the same rule. In a list view shorter than 56 points each band is half the view, so a pointer in the top half scrolls up, one in the bottom half scrolls down, and a pointer just outside the view does not scroll it toward the far edge. A pointer beside the list, a drag of the eye or lock column and a release stop the scrolling, and scrolling changes nothing in the document. The band and speeds are VectorCraft's own (`panels::layers` tests `rows_held_near_the_bottom_or_top_edge_scroll_the_list_to_a_row_out_of_view`, `a_held_row_scrolls_the_list_as_far_in_the_same_time_at_any_frame_rate` and `the_list_scrolls_only_for_rows_held_over_it`; `panels` test `drag_scrolling_in_a_short_list_goes_toward_the_nearer_edge`). - The other panels' item drags start only with the primary mouse button too: swatches and color groups, brushes, symbols, graphic styles, library items and groups, character and paragraph styles, Appearance rows and its thumbnail, the Fill and Stroke squares, Recent Colors and the Gradient panel's thumbnail. A right or middle drag on one carries nothing, moves, copies, deletes and applies nothing and records no undo step; right-click menus and the Graphic Styles panel's held right-button preview stay as they were (`panels::swatches` test `only_a_primary_drag_moves_swatches_and_groups`, `panels::text_styles` test `only_a_primary_drag_carries_a_style_row`, `panels::tests_symbol_libraries` test `only_a_primary_drag_carries_a_library_symbol_out`, `panels::tests_effectedit` test `only_a_primary_drag_carries_the_thumbnail_or_a_row`). - Panels undock (#495): a dock tab, a panel icon or a popped-out panel's title dragged out of the dock floats that panel (in an OS window of its own on the desktop, #4135), and the strip right of the dock's tabs floats the whole tabbed group. A floating group moves by its title bar, a tab dragged out of it floats on its own, and dropped on another group's title bar or tabs it stacks with that group; dropped on a dock group's tabs, which light up under the pointer, its panels join that group, and on the group's upper or lower half they make a new group above or below it (`window.panel.dock {anchor, zone}`); dropped on the icon column they become icons there, the tabbed group's panels too (`window.panel.dock {icon: true}`); dropped anywhere else on the dock, which lights up, they go back where they live (the tabbed group or the icon column), as its × and the panel menus' Float Panel / Dock Panel do (`window.panel.float`, `window.panel.dock`). The Tools panel floats by its title bar and docks again on the window's left edge. Floating groups stack into sets: dropped on the upper or lower half of another group (a line shows where), a group joins it right above or below it, and the set's groups stack top to bottom, each showing one panel, moving together by the top group's title bar, whose × docks them all; a group dragged by its tab strip leaves the set (`window.panel.float {below, above}`). A double-click on a tab collapses a floating group to its tabs (`collapsed`), and a dock group too, a group below it moving up into the room; a second double-click, or a click on another of its tabs, expands it (`window.panel.collapse`, kept with the preferences and in saved workspaces). Sets dropped on the left edge of the icon column or of another dock column dock as dock columns (a multi-column dock, `window.panel.dock {column}`), whose groups stack, tab and tear out as a floating set's do, and whose top strip floats the column again. Floating panels, their sets and the Tools panel's position are kept with the preferences and in user workspaces, and clamped into a smaller window. Not done: panels in separate OS windows, reordering tabs by dragging, collapsing a set or dock column to icons, dock columns right of the default dock, resizing floating panels and the groups of a set. @@ -1002,12 +1034,13 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Window › Toolbars › Manage Toolbars… and Manage Toolbars… in the All Tools drawer's menu open a dialog that lists the toolbars made with New Toolbar: a new name typed for the selected toolbar renames it, + copies it with its tools (with none selected, + makes a blank toolbar), and the trash can deletes it. Each change shows under Window › Toolbars and stays in the workspace (; `window.toolbar.manage`, `window.toolbar.rename`, `window.toolbar.duplicate`, `window.toolbar.delete`; `manage_toolbars_renames_duplicates_and_deletes`). - A toolbar made with New Toolbar docks in a lane along the window's left or right edge when its title bar is dropped on that edge, or with Dock to Left and Dock to Right in the title bar's context menu. Toolbars docked at one edge stack from the top, each with its share of the lane's height, and the lane is as wide as its widest toolbar; a lane too short for its stack wraps it into more columns, up to half the window's width, and past that the toolbars show only their title bars, which the mouse wheel scrolls through when even they do not fit. Dragging the title bar out of the lane, or Float Toolbar, floats it again, and Escape during the drag puts it back. Hiding and renaming keep its place, and the workspace keeps it. New toolbars still start floating. The lanes and the stacking are VectorCraft's own rules (#1759; `window.toolbar.dock`, `window.toolbar.float`; `toolbars_dock_and_float_by_their_commands`, `docked_toolbars_stack_in_lanes_along_the_window_edges`, `a_title_bar_dropped_on_an_edge_docks_the_toolbar`). - The status bar shows the errors of the toolbars made with New Toolbar (a missing, empty, too long or taken name, the 64-toolbar limit, a `side` or `order` that `window.toolbar.dock` does not take, and New Toolbar's dialog and Manage Toolbars) in every language that translates every message, with the toolbar's name, the parameter key and the value given kept as they are; the error the command returns stays English (`custom_toolbar_command_errors_are_translated`). - - Window › Toolbars › Keep Tools Beside the Canvas, a VectorCraft layout option that is off by default, docks the Tools panel between left-side panels and the canvas instead of at the window's left edge; the canvas's left edge then also docks a floating Tools panel, and workspaces keep the setting. Scores are unchanged (`window.toolsBesideCanvas`; `docked_tools_keep_the_window_edge_unless_kept_beside_the_canvas`, `tools_redock_at_the_targets_of_the_chosen_placement`). + - Window › Toolbars › Keep Tools Beside the Canvas, a VectorCraft layout option that is off by default, docks the Tools panel between left-side panels and the canvas instead of at the window's left edge, and workspaces keep the setting. A floating Tools panel dropped on the canvas's left edge, right of panels docked on the left, docks there and turns the setting on, and one dropped on the window's left edge docks there and turns it off; with no panels docked on the left, a drop leaves the setting as it is (#7837). Scores are unchanged (`window.toolsBesideCanvas`; `docked_tools_keep_the_window_edge_unless_kept_beside_the_canvas`, `tools_dropped_on_a_left_edge_dock_there_and_the_setting_follows`, `tools_dropped_where_the_left_edges_overlap_keep_the_setting`, `tools_dropped_beside_a_collapsed_left_dock_follow_the_strip_dropped_on`). - Hindi (2026-11-06): Hindi (`hi`): 7,877-row machine-assisted catalog, zero/one singular plurals, desktop font fallback and optional Devanagari craft-fonts fallback; all 55 translation tests pass; native review and a web font remain; scores and estimates unchanged. [Terminology and limitations](localization-hi.md). - Gujarati (2026-11-14, #6613): `gu` has 4,673 catalog rows, zero/one singular plurals, installed desktop font fallback and support for optional `Gujr` craft-font faces. The original 4,286 rows remain unchanged; all 387 additions are contributor-reviewed and approved, with 11 wording corrections. Status/error messages remain partial; the pinned fonts and web startup list have no Gujarati face, so web selection remains unavailable until one is bundled. Current-head validation is recorded in the PR; scores and estimates unchanged. - Hindi wording (2026-11-13): rows outside the plug-in messages keep their English's meaning, quantities and clauses, and use the catalog's save, swatch, crop, resolution, path and type terms; a test checks those terms and the point unit in every row; native review remains; scores and estimates unchanged. - Hindi word senses (2026-11-13): 85 labels and messages use the interface sense of their English: Desired is वांछित and the range message keeps both comparisons, rulers are रूलर, text characters कैरेक्टर, vector points पॉइंट, fills फ़िल्स and High Contrast उच्च कंट्रास्ट; the glossary test rejects the unrelated senses in every row; native review remains; scores and estimates unchanged. - Hindi terms (2026-11-13): every row that names a variable (data merge, variable fonts and widths, environment variables) says वेरिएबल, and joining paths, anchor points, point type and lines says जोड़ें instead of शामिल हों, which stays for joining the community; a test checks both terms in every row; scores and estimates unchanged. + - Greek knockout term (2026-11-15): Page Knockout Group and Opacity & Mask Define Knockout Shape say διάτρηση, as Knockout Group does, instead of αποκοπή, which stays for clipping and cutting; a test checks the term in every row that names a knockout; scores and estimates unchanged. - Hindi messages its catalog lacked (2026-11-14): 116 status and error messages that the Hindi catalog did not translate, among them the image export, color profile, swatch exchange, color book, DXF, PDF knockout group, Revolve and 3D messages, have Hindi rows; the translations are VectorCraft's own and await native review; scores and estimates unchanged. - Hindi English words (2026-11-13): 264 rows no longer keep English words in their sentences, repeat a parameter's name in Hindi or garble them, among them "unknown align", which now names the alignment; lists of accepted values such as `(left|right|top|bottom)` stay as their English writes them; two tests check every row; native review remains; scores and estimates unchanged. - Message field names and values (2026-11-13): 49 status and error messages in the Hindi, Bulgarian, Danish, Indonesian, Dutch, Brazilian Portuguese, Swedish and Turkish catalogs keep the field names in brackets, such as `[subpath, anchor]`, and the values an `unknown` message lists, such as `(points, lines)`, as their English writes them; a test checks every catalog; scores and estimates unchanged. @@ -1018,11 +1051,15 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The Czech catalog (`crates/ui-egui/src/i18n/cs.tsv`) translates 114 status and error messages that no catalog had a row for: the 3D and Revolve limits, image export and encoding errors, color profiles, color books and swatch exchange files, binary DXF and DWG import, path operations, swatch, graphic style and action set libraries, and zip, script and regular expression errors. The untranslated report (`untranslated_report`) still lists 54 messages for every language: the 53 composite font, SVG filter, read root and graph design errors that open #7211, #7378 and #7405 translate, and `` `index` must be a whole number ``. See [localization-parity.md](localization-parity.md). - The History panel, Edit › Undo and Edit › Redo translate the names of the steps that apply or redefine a character or paragraph style and of the step that redefines a graphic style: each such step keeps its template (`Apply {name}`, `Redefine {name}`, `Redefine Graphic Style “{name}”`) and the style's name, every complete catalog has a row for each template, and the panel and the menu show the style's name as the document holds it, except the Normal styles' names, which they show in the interface language (`steps_named_after_a_style_list_the_template_around_the_name`, `undo_and_redo_name_a_style_step_around_the_style_name`). - 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. + - Polish labels and messages call drawn art and artwork *kompozycja*, the term the catalog's header sets, instead of *grafika* or *rysunek*. *Grafika* stays for what the English calls a graphic (graphic styles, library and 3D graphics, GPU graphics), and line art, the art brush and an artboard (*obszar kompozycji*) keep their own terms (`polish_rows_call_artwork_kompozycja`). - 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 untranslated-strings report reads a message written over two lines with a `\` at the end of the first as one line, the text the program shows, and the Georgian catalog's (`ka`) row for PDF export's warning about knockout groups with too many translucent elements matches that text (`message_scan_joins_a_literal_continued_on_the_next_line`, `untranslated_report`). - 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 `script.run`'s refusals of `answers` in every language that translates every message: a value that is not a list, more than 10,000 answers, more than 1 MiB, an answer at an index that is not an object, does not have exactly `kind` and `value`, has a `value` its kind of dialog does not take, holds a prompt's text longer than 16 KiB or has an unknown `kind`, and `answers` given to a run in the app. The index, the counts and the code names are shown as they are, and the command's error stays in English. The untranslated-strings report also lists the refusals of `script.run`'s parameters (`script_answers_errors_are_translated`, `message_scan_reads_script_run_param_refusals`). + - The status bar also translates `script.run`'s other refusals of its parameters in every language that translates every message: a `maxFuel` outside 1 to 100,000,000,000, `args` nested more than 64 levels deep (with the place in `args`), `args` that is not an object or is larger than 1 MiB, an empty `path`, a `source` given with `installed`, a `path` that does not name a .js or .jsx file, and neither or both of `path` and `source`. The code names, the place in `args`, the file suffixes and the limits are shown as they are, and the command's error stays in English (`script_run_param_errors_are_translated`). - 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`). + - Every complete-message catalog translates five more messages with literal braces through such a row: the composite font errors `each font must be {name, parts}` and `give fonts: [{name, parts}…]`, `select.font`'s `` `scope` must be "document", {artboards: [index, …]} or {layers: [id, …]} ``, the script regular expression error `numbers out of order in {} quantifier` and `the paint is not a freeform gradient (apply one with paint.editGradient {kind: "freeform"})`. Each translation keeps the braced example as written, and no catalog keeps the older rows with a placeholder in place of the braces, which also translated other text with the same start and end (`literal_brace_messages_have_exact_rows_in_complete_languages`). - 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 status bar also translates the errors the script interpreter's core throws (an unknown name, a property of `null` or `undefined`, a property that cannot be defined, assigned or deleted and the reason, a value that is not a function or a constructor, an invalid array length, an invalid assignment target), on their own and in the line for a failed run, in every language that translates every message. Names, property names (a value a message quotes in `'…'` is shown as written, like one in `"…"`, even when it matches a translated message), `null`, `undefined`, `in`, `instanceof` and the error's type (`TypeError`, `ReferenceError` and the others) are shown as they are, and a script that catches the error still reads its English message. An error about a property of `null` or `undefined` names a computed property whose name is not an object and is at most 256 units long, and otherwise says only that the script read or set a property, instead of naming an empty property (`script_interpreter_core_errors_are_translated`, `errors_about_null_and_undefined_name_the_property`, `message_scan_reads_script_interpreter_errors`). - 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. @@ -1047,16 +1084,18 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The History panel menu has Step Backward and Step Forward, which run Edit › Undo and Edit › Redo and are disabled when there is no step to undo or redo, and Set History Limit…, which opens Preferences at Performance, where History States is set. - The History panel menu's Clear History (`edit.clearHistory`) removes every step to undo and to redo and leaves the document as it is; it is not an undo step itself, and it is disabled when there is no step to clear. - The New Document from State button at the bottom of the History panel (`edit.newDocumentFromState`) makes a new document, which becomes active, from the state the panel has selected ([public source](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/undo-edits-and-manage-design-history.html)). VectorCraft's own rules: the new document takes the next Untitled-N name, is marked unsaved, has nothing selected and has no steps to undo or redo, and the source document and its steps stay as they are. - - The Transform panel menu's Transform Object Only, Transform Pattern Only and Transform Both (`transformPanelPatterns`) choose whether the fields, flips and menu flips of the Transform panel and the Properties panel's Transform section move the object and leave its pattern tiles, move the tiles alone, or both (until a choice they follow General › Transform Pattern Tiles, as before); Use Registration Point for Symbol (`useRegistrationPointForSymbol`) measures and transforms one selected symbol instance from its symbol's registration point, where the instance's flips, rotations and shears put it ([Transform panel overview](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/transform-panel-overview.html); `panels::transform::tests::the_menu_chooses_whether_the_object_its_pattern_or_both_transform`, `use_registration_point_for_symbol_measures_an_instance_from_its_registration_point`, `use_registration_point_for_symbol_follows_a_transformed_instance`, `tests_prefs::transform_panel_patterns_defaults_to_following_the_general_preference`). + - The Transform panel menu's Transform Object Only, Transform Pattern Only and Transform Both (`transformPanelPatterns`) choose whether the fields, flips and menu flips of the Transform panel and the Properties panel's Transform section, and the Control bar's inline X, Y, W and H, move the object and leave its pattern tiles, move the tiles alone, or both (until a choice they follow General › Transform Pattern Tiles, as before); Use Registration Point for Symbol (`useRegistrationPointForSymbol`) measures and transforms one selected symbol instance from its symbol's registration point, where the instance's flips, rotations and shears put it ([Transform panel overview](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/transform-panel-overview.html); `panels::transform::tests::the_menu_chooses_whether_the_object_its_pattern_or_both_transform`, `use_registration_point_for_symbol_measures_an_instance_from_its_registration_point`, `use_registration_point_for_symbol_follows_a_transformed_instance`, `tests_prefs::transform_panel_patterns_defaults_to_following_the_general_preference`). - The Transform panel's Align to Pixel Grid checkbox (`object.setPixelAligned`) gives paths and compound paths a pixel-aligned property, saved in the native file: their horizontal and vertical straight segments sit on whole points (half points under an odd centered stroke) with whole stroke weights, and every move, scale, rotation, reflection, Transform Each, Align move, Transform panel change, move of direct-selected anchors or of one anchor, move of a compound path's path on its own, artboard move, resize or copy that carries the art, Duplicate or paste that moves a copy, stroke edit and appearance edit that adds, removes, hides, repaints or reweighs a stroke snaps them again, while diagonal segments and curves keep their shape; a compound path made from an aligned path or compound path is aligned and snaps its paths with its own stroke; the box shows a dash for a mixed selection and is unavailable for type, images and groups ([Pixel-aligned property](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/pixel-preview-mode-for-web-graphics.html); `tests::pixelalign::turning_it_on_snaps_the_path_in_one_undo_step`, `it_stays_aligned_through_transforms`, `it_stays_aligned_when_its_artboard_moves`, `diagonal_segments_and_curves_keep_their_shape`, `type_and_images_cannot_be_aligned`, `the_property_is_saved_and_read_back`, `stroke_edits_keep_it_aligned`, `a_compound_path_of_aligned_paths_is_aligned`, `a_compound_path_of_an_aligned_compound_path_is_aligned`, `a_stroke_without_paint_snaps_to_whole_points`, `moving_direct_selected_anchors_keeps_it_aligned`, `moving_one_anchor_keeps_it_aligned`, `moving_a_path_of_an_aligned_compound_path_keeps_it_aligned`, `artboard_options_and_artboard_copies_keep_it_aligned`, `appearance_edits_keep_it_aligned`, `placed_gradients_follow_the_snapped_path`, `duplicates_and_pastes_keep_it_aligned`, `paths_added_to_or_moved_in_an_aligned_compound_path_keep_it_aligned`, `the_art_of_a_linked_opacity_mask_keeps_it_aligned`, `a_linked_opacity_mask_follows_a_snap`, `aligning_direct_selected_anchors_keeps_it_aligned`, `global_edit_keeps_its_members_aligned`, `a_path_with_live_corners_snaps_its_inner_edges`, `geometry_edits_keep_it_aligned`, `other_path_edits_keep_it_aligned`, `panels::transform::tests::align_to_pixel_grid_shows_and_sets_the_property`). - Align New Objects to Pixel Grid (`document.setup {alignNewObjectsToPixelGrid}`, a checkbox in New Document's Advanced Options and a checked item in the Transform panel menu) gives every path and compound path drawn in the document, the paths of a new grid or flare included, the pixel-aligned property, snapped in the step that draws it; it is on in the Mobile and Web presets and off in the others, saved presets and Recent keep it, and the document saves it. Type, images and groups do not take it, and art already in the document, pasted, duplicated or placed keeps its own property (VectorCraft's own rules) ([Pixel-aligned property](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/pixel-preview-mode-for-web-graphics.html); `tests::pixelalign::align_new_objects_makes_new_paths_pixel_aligned`, `align_new_objects_reaches_grids_flares_and_add_on_shapes`, `align_new_objects_is_saved_and_read_back`, `tests::newdoc::align_new_objects_to_pixel_grid_follows_the_preset`, `panels::transform::tests::align_new_objects_menu_item_toggles_the_active_document`, `dialogs::new_document::tests::align_new_objects_checkbox_follows_the_preset_and_reaches_the_document`). - The Transform panel works out its Align to Pixel Grid checkbox once for each document revision and reuses it on later frames, and lists the selected objects' ids only when the box is clicked. The box shows the same state. With Select All of 99,500 objects (100,000 paths, 1,000 of them in 500 compound paths), working the state out on every frame took a median 33.5 ms of thread CPU time per frame in a release build on a loaded machine; the first frame after a change now takes 31.5 ms and later frames take about 1 ns (`panels::transform::tests::align_to_pixel_grid_kept_state_equals_a_full_measure`, `align_to_pixel_grid_state_is_measured_once_per_revision`, `pixel_aligned_state_timing`). - Break Link to Symbol and Object › Expand give a symbol instance's art the instance's own bounding box: after Reset Bounding Box the art stands square to the page, an object turned inside the symbol keeps its angle relative to the instance's box, a group added for the instance's opacity takes the instance's box, and the clip groups of 9-slice art take the angle of their cell. Compound shapes and Pathfinder receive an instance's art with the same angles (VectorCraft's own behavior; `bboxrotate::reset_bounding_box_then_expand_symbol_instance`, `reset_bounding_box_then_expand_keeps_the_angles_inside_the_symbol`, `expanding_a_faded_symbol_instance_gives_its_group_the_instance_box`, `expanding_a_reflected_symbol_instance_keeps_its_box`, `symbol_nine_slice::break_link_turns_the_cells_of_a_sliced_instance_with_its_box`, effects `outline_object_turns_an_instances_art_with_its_box`). - Object › Transform › Reset Bounding Box squares the box of every object inside the selected ones as well: the children of groups, compound paths, clip groups, blends, envelopes, repeats and intertwines, and the art of linked opacity masks. Ungroup and the release commands then bring back boxes square to the page (VectorCraft's own behavior; `bboxrotate::reset_bounding_box_squares_the_objects_inside_a_group`, `reset_bounding_box_squares_the_turned_members_of_a_square_group`, `reset_bounding_box_then_release_clipping_mask` and the other `reset_bounding_box_then_*` tests, `reset_bounding_box_leaves_the_art_of_an_unlinked_opacity_mask`). + - Object › Transform › Rotate Bounding Box… turns the selection's bounding box by the angle typed in its dialog without moving the art (`object.rotateBoundingBox`, `absolute: true` to set the angle). Objects with different angles get one shared angle, and the objects inside a group and the art of a linked opacity mask turn with it. A path of a compound path selected on its own turns only its own box, and Reset Bounding Box squares only that path's box too (VectorCraft's own behavior; `bboxrotate::rotate_bounding_box_turns_the_box_and_leaves_the_art`, `rotate_bounding_box_back_to_zero_stores_zero`, `rotate_bounding_box_gives_a_mixed_selection_one_angle`, `rotate_bounding_box_turns_the_objects_inside_a_group_with_it`, `rotate_bounding_box_turns_a_linked_masks_art_only`, `reset_bounding_box_squares_every_box_rotate_bounding_box_turned`, `rotate_bounding_box_refuses_bad_params`, `tests::rotate_bounding_box_of_a_compound_paths_member_turns_only_that_path`, ui-egui `panels::transform::tests::rotate_bounding_box_menu_item_turns_the_box_by_the_dialog_angle`). - After a rotation the Free Transform tool shows and drags the same turned bounding box as the Selection tool: its handles, their cursors and its rotate zone sit on the selection's own sides, a handle scales along those sides from the opposite handle ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-objects.html)), Cmd/Ctrl on a side handle shears along that side, and Perspective Distort and Free Distort start from the turned box's corners (`object.distort` takes `angle` with `from`) (`bboxrotate::free_transform_handles_turn_with_the_object_and_scale_along_its_axes`, `free_transform_shears_along_the_turned_side`, `free_transform_distort_starts_from_the_turned_box`, `xform::distort_reads_from_in_a_turned_frame_and_rejects_a_bad_angle`, tools `xform::free::tests::the_box_and_its_handles_turn_with_the_selection`). - After a rotation the Scale and Reflect tools, the Scale and Reflect dialogs, `object.scale`, `object.reflect` with a named axis and the Transform and Properties panels' flips act along the selection's turned bounding box until Reset Bounding Box: the horizontal and vertical scale stretch along its own width and height, and the vertical and horizontal reflection axes are its own. The Reflect tool's default axis and its Shift steps start from the box's axes, and an axis drawn with the tool is the line drawn on the page. `basis: "page"` keeps the page's axes (VectorCraft's own rules; `bboxrotate::scale_and_reflect_follow_the_turned_box`, tools `xform::transform::tests::scale_and_reflect_drags_follow_a_turned_bounding_box`). - Perspective Distort and Free Distort (`object.distort`) turn each warped object's bounding box as the warp turns the object at its own center, the objects inside groups, compound paths and clip groups and the art of linked opacity masks included, so the next Selection or Free Transform drag uses the tilted box; Object › Transform › Reset Bounding Box squares it again, and corners left where they are add no undo step (VectorCraft's own rule; `bboxrotate::distort_turns_an_upright_box_with_the_warp_at_its_center`, `distort_turns_each_member_and_linked_mask_by_its_own_warp`, `mirrored_and_collapsing_distorts_keep_valid_angles`, `distort_angles_undo_redo_and_reopen_together`, `xform::unchanged_distort_records_no_history`). - The Free Transform widget's Constrain works in Free Distort as well as in Free Transform ([the help page](https://helpx.adobe.com/illustrator/using/tool-techniques/free-transform-tool.html)). With Constrain on, or Shift held, a corner dragged in Free Distort moves only along the line through the opposite corner, in the box's own proportions, and the other three corners stay in place; on a turned box the line runs through the box's own corners. The line is VectorCraft's own rule. Cmd/Ctrl+Alt+Shift on a corner still drags in Perspective Distort, where Constrain stays unavailable (tools `xform::free::tests::free_distort_corner_keeps_to_its_diagonal_with_shift_or_constrain`, `shift_pressed_during_a_free_distort_drag_constrains_it`, `a_turned_box_is_constrained_along_its_own_diagonal`, `along_diagonal_of_a_degenerate_box`; engine `xform::free_transform_constrained_distort_keeps_the_corner_on_its_diagonal`; ui-egui `free_transform::tests::the_widget_sets_the_mode_and_a_corner_drag_then_distorts`). + - With Smart Guides › Transform Tools on, a Free Transform shear (Cmd/Ctrl on a side handle) shows its angle next to the pointer, as the Shear tool does, and a handle drag that turns from a scale into a shear and back shows only the current operation's value ([the help page](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/smart-guides-options.html)). The angle's sign and its one decimal place are VectorCraft's own rule, the same as the Shear tool's label (tools `xform::free::tests::shear_drag_shows_its_angle_with_transform_tools_guides`, `a_handle_drag_that_changes_operation_relabels_it`). - Native macOS menu bar, vector tool cursors, a command palette (Help › Search Commands…), middle-button panning with any tool. Native menus explicitly end tracking on command selection, outside window presses and Escape; menu updates wait until tracking ends, and a dismissing press never starts a canvas gesture (M14.8). - Help › Search Commands… is the first item of the Help menu in the window, with its shortcut and a separator after it; in the native macOS menu bar it is the first item below the system's search field. This is VectorCraft's own order and does not raise a score (`menus::tests::help_starts_with_search_commands`, `tests::nativemenu::the_mac_help_menu_starts_with_search_commands`). - A Recent Commands button beside the Help › Search Commands field lists the last five commands, tools, panels and effects picked from the palette, most recent first, with a command picked again moved to the top. Choosing a row closes the palette and runs it as a pick of the same result does; with no picks yet the list shows a dimmed No recent commands row, and a command that is not available now, such as a filter of a plug-in that is not loaded, is left out until it comes back. The ids are saved with the UI state. While the list is open, Up and Down move through its rows, wrapping at the ends, and Escape closes the list before the palette. This is VectorCraft's own addition and does not raise a score (#6376; `palette` tests `recent_commands_*`, `a_recent_command_runs_what_its_pick_runs`, `the_keys_wrap_within_recent_commands`, `escape_closes_recent_commands_before_the_palette`). @@ -1067,8 +1106,10 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - A Learn tutorial's steps are marked complete as the learner works, and a skill's progress ring fills as its tutorials are finished, as the help page describes ([the help page](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/learn-skills-quick-skill-guide.html)). Each step has a check box that marks it done once the tutorial's sample is open (`learn.markStep`); Finish tutorial marks every step done; a skill's count shows its tutorials finished of all, and a finished tutorial has a check mark in its skill's list. Marking steps by hand, the count, keeping the progress in the preferences (the web build keeps it while the page is open) and Reset progress (`learn.resetProgress`) are VectorCraft's own rules; `learn.list` reports the progress. Regression tests: `a_step_s_check_box_marks_only_that_step`, `a_step_s_check_box_works_from_the_keyboard`, `finishing_tutorials_fills_their_skill_s_ring_and_count`, `a_skill_with_no_tutorials_shows_0_of_0`, `learn_mark_step_checks_its_params`, `reset_progress_clears_only_the_progress`, `the_preferences_keep_the_progress` and `saved_progress_is_read_leniently` in `crates/ui-egui/src/panels/learn/tests.rs`. - The Home screen has a Learn section with the in-app tutorials, as the help page lists among the Home screen's options ([the help page](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/homescreen-overview.html)): the Quick skill guide card shows the Learn panel's list of skills (`learn.skills`), and each tutorial, listed under its skill, shows the panel at its steps (`learn.show`). It shows with no document open and over open documents, and a choice leaves the documents as they are. Its place between Recent Files and the new-file presets, its layout and what a choice opens are VectorCraft's own rules (`tests::home::home_has_a_learn_section_that_opens_the_learn_panel`, `home_learn_section_over_open_documents_leaves_them_as_they_are`, `home_quick_skill_guide_card_works_from_the_keyboard`). - The errors of the blend spine commands (Move Spine Point, Reshape Spine Segment, Add Spine Point and Delete Spine Point) show in the status bar in the interface language: each has a row in every catalog that translates all status and error messages and in Bulgarian (`blend_spine_param_errors_are_translated`). + - The errors of Automatic Plane Positioning (`perspective.plane.infer`) and of its two Perspective Grid Options (`perspective.widget.options`) show in the status bar in the interface language: a hidden grid, both options off, a negative `tolerance`, `at` given with `clear`, and an `anchorPoint` or `gridlineIntersection` that is not true or false. Each has a row in every catalog that translates all status and error messages, with the parameter names kept (`automatic_plane_positioning_errors_are_translated`). - The errors of the 3D effects (Extrude & Bevel, Revolve, Inflate, Rotate and their Classic forms) show in the status bar in the interface language: the art a 3D effect cannot build a solid from, invalid light, graphics and surface settings, and the notes for an object that draws no 3D faces or more wireframe edges than the limit. Each has a row in every catalog that translates all status and error messages, and the effect's name and the values in the message are translated or kept as written (`three_d_refusals_are_translated_in_every_complete_catalog`, `three_d_refusals_translate_with_their_values`). - The errors of an SVG filter that the New or Edit button of Apply SVG Filter or an `svg.filter` effect refuses show in the status bar in the interface language: XML that cannot be read, a missing or too long id, an element or event attribute a filter does not take, an image that is not a `data:` URL, and the limits on primitives, `numOctaves`, `order`, `radius`, `stdDeviation`, `kernelUnitLength`, image pixels, nesting and size. Each has a row in every catalog that translates all status and error messages, and the limits, element and attribute names and the XML parser's position are kept as written (`svg_filter_refusals_are_translated_in_every_complete_catalog`, `svg_filter_refusals_translate_with_their_values`). Items side by side in a menu show different labels in every interface language (Effect › 3D and Materials › Revolve… and Rotate… in Turkish and Bulgarian, Effect › Warp and Distort, the Pathfinder effects, the Warp styles, Window › Attributes and Properties, and the whitespace characters), and no menu item shows a command id in place of its label (`menu_items_side_by_side_have_different_labels`, `menu_items_never_show_an_id`). + - Keyboard Shortcuts shows each entry under a name of its own in every interface language: the Scale and Zoom tools, the Column and Bar Graph tools and their stacked forms, the Pucker and Wrinkle tools, the Shear and Warp tools, Edit › Copy and Duplicate, Pathfinder Unite and Merge, and View › Saved View 2 to 17 have different names in every catalog (`no_two_entries_have_the_same_name_in_any_language`). The Line Graph tool reads as a line graph in Russian and Ukrainian, and in every catalog a row whose English name ends with a number keeps that number (`numbered_rows_keep_their_number`). - The errors of the parameter checks that many commands share show in the status bar in the interface language: a value that is not a number where a number goes (`object.move` with `"dx": "60 mm"`, and `object.rotate`, `object.setBounds` and the other commands that call `check_numbers`), a missing number or index, `ids` that are not a list of object ids, an object id that is not a non-negative integer or names no object, and a date that is not Unix seconds. Each has a row in every catalog that translates all status and error messages, and in Bulgarian, Danish, Indonesian and Dutch (`shared_param_check_errors_are_translated`). - File Info's (`file.info`) error for a value with control characters shows in the status bar in the interface language for every field: "description has control characters" for Description and Copyright Notice, which take line breaks and tabs, and "title has control characters or line breaks" for the other text fields and each keyword in a list. Each is its own message with a row in every catalog that translates all status and error messages, and the field's key stays as written (`file_info_control_character_refusals_translate_in_every_complete_catalog`, `control_characters_are_refused_with_the_field_rule`). - A parameter schema's errors show in the status bar with what the value must be in the interface language, for every type a schema has (a number with each kind of range and with a unit, an integer and its range, true or false, a string, a list of names, an object id, a list of object ids, a color, a point, an object and a list), in every catalog that translates all status and error messages; the path, the refused value, the bounds, the unit and the names stay as the English gives them. The error for a value that is not one of its names is also translated in Bulgarian, Bosnian, Danish, Indonesian and Dutch (`parameter_schema_expected_phrases_are_translated`, `bracketed_message_parts_translate_only_as_exact_messages`). @@ -1077,6 +1118,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - In that Liquify warning, the tool's name and each kind of object it left (graphs, type, symbols, images, meshes, envelopes, repeats, placed documents, blends) are shown in the interface language too, in the order the command lists them and joined as the language joins a list, in each catalog that translates all status and error messages (`liquify-tool`, `liquify-kind` and `liquify-list-*` rows); a kind that Liquify does not list leaves the tool and the list in English (`liquify_warning_translates_its_tool_and_kinds_in_every_complete_catalog`). - An effect a plug-in's output or an importer plug-in's objects carry that VectorCraft refuses (``[0] `id`: reason``) shows in the status bar with its reason in the interface language inside `plug-in output: …` and `can't open …`, in every catalog that translates all status and error messages; the index and the effect id stay as they are, and a JSON array in a message stays as it is (`nested_effect_refusals_translate_with_their_reason`, `bracketed_message_parts_translate_only_as_exact_messages`). - The untranslated report lists the status and error messages of the effects, swatch libraries, raster sizes and encoders, 3D solids and path operations that a catalog lacks, the messages that a `.map_err` closure or a named error handler returns, and the phrases a parameter schema's error builds for what a value must be (`untranslated_report_checks_every_message_crate_and_schema_phrase`, `message_scan_reads_map_err_closures`, `message_scan_reads_named_map_err_handlers`). + - The Swedish catalog has rows for the Apply SVG Filter and Check Spelling command names, the SVG Filter effect's name, which also names its undo step, and the 3D and Materials panel's note that graphics map onto the Plane, Extrude and Revolve object types, so these show in Swedish instead of English (`swedish_svg_filter_spelling_and_3d_labels_are_complete`). - Spanish messages (2026-11-13): the Spanish catalog (`crates/ui-egui/src/i18n/es.tsv`) has an `@msg` row for 114 of the 167 status and error messages that the untranslated report (`untranslated_report`) lists as missing in all 23 complete-message languages: the errors of the image encoders, color profiles, swatch exchange files and color books, 3D and Revolve, path operations, DXF import, the script engine and the parameter checks. Open #7211 and #7378 translate 51 of the others (the composite font and SVG filter errors), and 2 stay in English. The rows keep the placeholders, backticked names, accepted values and limits of their English (`spanish_translates_encoder_profile_swatch_revolve_and_parameter_errors`); native review remains; scores and estimates unchanged. - Export commands run through MCP, the control channel or the CLI refuse a key that no format takes, and warn about a key that only another format takes (`{"format": "pdf", "quality": 80}` writes the PDF with the warning "`quality` was not used: PDF files don't read it"; `an_option_only_another_format_reads_gets_a_note`, `control_export_notes_an_option_the_format_does_not_read`, `convert_warns_about_an_unused_option_only_when_one_was_given`), and a command that writes one format (`document.exportPdf`, `document.exportEps`, `document.exportDxf`) or takes one format's options (`document.pdfSettings`, `pdf.preset.save`) refuses a key that format doesn't take. An unknown key inside `marks`, `bleed`, `compression`, `output`, `advanced`, `security` or `flattener` is refused by its path. - Save commands run through MCP, the control channel or the CLI (`document.save`, `file.saveAs`, `file.saveCopy`, `file.saveAsTemplate`, `app.save`) refuse a key that no save format takes, beside the path or in `options`, and warn about a key the file doesn't read, beside the path or in `options`, with an export's `.ai` rules; Save Options sends a `.ai` save only the options the chosen version reads (`a_save_notes_the_ai_options_its_file_does_not_read`, `ai_save_options_send_only_the_options_the_version_reads`). Export for Screens refuses a key it doesn't take, and a key that no format takes in a format row or in a format's settings, by its path (`formats[1].marks.useDocumentBleed`), and warns about a key there that only another format takes (`a_row_option_only_another_format_reads_gets_a_note`); Export Assets (`assets.export`, `assets.settings.set`) checks the rows and settings it is given the same way. @@ -1100,14 +1142,20 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Symbols panel context menu** ([Symbols panel](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): right-clicking a symbol in thumbnail view or list view displays a context menu with Place Symbol Instance (passes view center or artboard center), Edit Symbol, Duplicate Symbol, Delete Symbol, Break Link to Symbol (enabled when canvas selection includes instances of this symbol), and Select All Instances. Right-clicking an unselected symbol selects it first (`symbol.setCurrent`). Tests: `panels::symbols::tests::right_click_context_menu_in_symbols_panel_runs_actions`. - **Drag a symbol onto New Symbol to duplicate it** ([the help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=197), Duplicate a symbol in the panel section): a symbol dragged from the Symbols panel, in thumbnail view or a list view, and released on the New Symbol button is copied as Duplicate Symbol copies it (`symbol.duplicate`), with no Symbol Options dialog, even while no art is selected and the button is disabled for clicks. VectorCraft's own rules: the copy is made of the dragged symbol, not the current one, under Duplicate Symbol's default name, in one undo step; the current symbol and the selection stay as they were and no instance is placed; the button is outlined while a symbol of the document is held over it; a library symbol, art, a name the document no longer has or a symbol dragged from another document is ignored. Tests: `panels::symbols::tests::symbol_dropped_on_new_button_duplicates_the_dragged_symbol_in_both_views`, `new_symbol_button_ignores_other_drops_and_releases_outside`, `a_symbol_dragged_from_another_document_is_not_duplicated`. - **Drag a symbol onto Delete Symbol to delete it** ([the tutorial](https://shop.smashingmagazine.com/2011/09/an-in-depth-study-of-symbols-in-illustrator-cs5/), [Symbols panel](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): a symbol dragged from the Symbols panel, in thumbnail view or a list view, and released on the Delete Symbol button is deleted as a click on the button deletes it (`symbol.delete`): an unused symbol asks "Delete the selected symbol?", a symbol with placed instances asks with Expand Instances, Delete Instances and Cancel, and Alt held at the release deletes an unused symbol without asking. VectorCraft's own rules: the dragged symbol is deleted, not the current one, in one undo step; a symbol that Select All Unused picked deletes every picked symbol still unused, after one question, and a symbol outside the pick is deleted on its own; the button is outlined while a symbol of the document is held over it; a library symbol, art, a name the document no longer has or a symbol dragged from another document is ignored. Tests: `panels::symbols::tests::symbol_dropped_on_delete_button_deletes_the_dragged_symbol_in_both_views`, `a_picked_symbol_dropped_on_delete_deletes_the_picked_symbols`, `delete_symbol_button_ignores_other_drops_and_releases_outside`. + - **Alt-drag art onto a symbol to redefine it** ([the help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=194), Modify a symbol instance section): art dragged off the canvas and released on a symbol in the Symbols panel with Alt (Option on macOS) held replaces that symbol's art, and every instance of the symbol updates, as Redefine Symbol does (`symbol.update` with the dragged art's `ids`). Released without Alt, the art still becomes a new symbol. VectorCraft's own rules: the symbol under the pointer is redefined, not the current one, in thumbnail view and both list views; the art becomes an instance of it, in one undo step; only that tile or row is outlined while the art is held over it with Alt; art of another document, objects the document no longer has and art that holds an instance of the symbol (directly, in an opacity mask or through the symbols it nests, which Redefine Symbol from the menu also refuses) change nothing. Tests: `panels::symbols::tests::alt_art_drop_on_a_symbol_redefines_that_symbol_in_one_step`, `alt_let_go_after_the_release_in_the_same_frame_still_redefines`, `a_plain_art_drop_on_a_symbol_makes_a_new_symbol`, `an_alt_art_drop_that_cannot_redefine_changes_nothing`, `a_secondary_button_release_drops_no_art`, `tests::brushsym::redefine_refuses_art_holding_an_instance_of_the_symbol`. + - **Shift with Redefine Symbol keeps the art** ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/edit-symbols.html), Redefine a symbol with another object section): Redefine Symbol chosen from the Symbols panel menu with Shift held updates the symbol and every instance of it from the selected art, and the selected art stays ordinary art instead of becoming an instance (`symbol.update {keepArt: true}`). Chosen without Shift, the art still becomes an instance. VectorCraft's own rules: the art keeps its ids, layer and place in the stacking order and stays selected, apart from art that is hidden or locked; the result has no instance id; the redefine is one undo step and, for the symbol being edited, also leaves symbol editing mode; `keepArt` defaults to false, and a value other than true or false is an error. Tests: `panels::symbols::tests::shift_redefine_symbol_in_the_menu_keeps_the_art_as_ordinary_art`, `tests::brushsym::redefine_with_keep_art_leaves_the_art_as_ordinary_art`, `redefine_with_keep_art_selects_only_selectable_art_and_refuses_a_bad_switch`, `tests::symboledit::redefining_the_symbol_being_edited_with_keep_art_leaves_the_art_and_the_mode`. + - **Shift with New Symbol keeps the art** ([the help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=192), Create a symbol section): holding Shift while making a new symbol from the selected art, with the Symbols panel's New Symbol button, its New Symbol… menu item or by dragging the art onto the panel, adds the symbol and leaves the art as ordinary art instead of turning it into an instance (`symbol.new {keepArt: true}`). Without Shift, the art still becomes an instance. VectorCraft's own rules: Shift is read when the button or menu item is clicked, or when the dragged art is released, and Symbol Options' OK uses it even if Shift has been let go; Shift with Alt on the button makes the symbol without Symbol Options and keeps the art; the art keeps its ids, layer and place in the stacking order and stays selected, apart from art that cannot be selected (hidden or locked art, art in a hidden or locked group or layer, template art, art outside an isolated group, art on a locked artboard); frames of threaded text stay in their thread; the result has no instance id; the new symbol becomes the current symbol in one undo step; `keepArt` defaults to false, and a value other than true or false is an error. Tests: `panels::symbols::tests::shift_new_symbol_in_the_menu_keeps_the_art_as_ordinary_art`, `shift_new_symbol_button_keeps_the_art_with_or_without_alt`, `shift_art_drop_on_the_panel_keeps_the_art_as_ordinary_art`, `symbol_options_checks_keep_art`, `tests::brushsym::new_symbol_with_keep_art_leaves_the_art_as_ordinary_art`, `new_symbol_with_keep_art_selects_only_selectable_art_and_refuses_a_bad_switch`, `cmd::threads::tests::frames_kept_as_art_by_a_new_or_redefined_symbol_stay_in_their_thread`. + - **Symbol Options button** ([Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), [Create and place symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html)): the help pages list a Symbol Options control among the Symbols panel's buttons, after Break Link to Symbol and before New Symbol, and it opens the settings of the chosen symbol. The panel's bottom bar has that button, and a click opens Symbol Options on the current symbol, as the panel menu's Symbol Options… does (`ui.symbolOptions {edit: true}`). VectorCraft's own rules: the button is disabled while the document has no current symbol, Alt-click does the same as a plain click, opening the dialog adds no undo step, and the icon is the one Swatch Options uses. Tests: `panels::symbols::tests::symbol_options_button_edits_the_current_symbol`. - **Symbols › Select All Unused** ([Symbols panel](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), #4918): the Symbols panel menu's Select All Unused shows the symbols nothing places selected (`symbol.unused`): instances in the art (opacity masks included), graph designs, pattern tiles and brush art count, and so do instances in a used symbol's art. Delete Symbol, the button or the menu item, then asks "Delete the selected symbols?" once and deletes those still unused in one undo step (`symbol.delete {names}`); Alt-click on the button deletes them without asking, and a click on a symbol picks just it again. Tests: `tests::brushsym::symbol_unused_lists_the_symbols_nothing_places_and_delete_takes_several`, `panels::symbols::tests::select_all_unused_picks_the_unused_symbols_and_delete_deletes_them`, `dialogs::symbol_delete::tests::several_symbols_get_the_plural_question`. - **Symbols › Sort by Name and the list views** ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): the Symbols panel menu's Sort by Name puts the symbols in alphabetical order (`symbol.sortByName`), and its Thumbnail View, Small List View and Large List View show them as thumbnails, in a compact list or in a list with larger thumbnails. VectorCraft's own rules: the sort ignores case and keeps names that differ only in case in their order; it changes the document's order, which `symbol.list` reports, as one undo step, keeps the current symbol and adds no undo step when the symbols are already in order; Thumbnail View is the default, Small List View has 18-point rows with 14-point thumbnails and Large List View 26-point rows with 22-point thumbnails, and a click or double-click on a symbol does the same in every view. `ui.panelView` sets the view of the Symbols panel, and of the Swatches and Graphic Styles panels, as their panel menus do. Tests: `tests::brushsym::symbol_sort_by_name_orders_the_symbols_in_one_undo_step`, `panels::symbols::tests::sort_by_name_and_the_small_and_large_list_views`, `panels::symbols::tests::panel_view_sets_the_view_of_each_panel`. - **The Symbols panel reads its current symbol from the document:** the Symbols panel and its panel menu read the current symbol on each frame without running `symbol.list`, which counts every symbol's instances by walking the whole document. The current symbol they show and act on is the one `symbol.list` reports, and an idle frame of the panel or its menu runs no command, so on macOS the native menu is not brought up to date on every frame while the panel is open. In a document with 200 symbols and 50,000 objects, the read takes 0.035 µs instead of 48.5 ms in a release build (thread CPU time on Linux, median of 7 runs); in a small document the difference is too small to notice. Tests: `tests::brushsym::current_symbol_is_the_current_symbol_list_answers`, `panels::symbols::tests::current_is_the_current_symbol_list_answers`, `panels::symbols::tests::idle_frames_of_the_panel_and_its_menu_run_no_command`; the timing probe is `panels::symbols::tests::current_symbol_read_timing`. - **Expand of symbol instances:** Object › Expand turns selected symbol instances (without effects, not in perspective, in groups or placed documents too) into their art as Break Link to Symbol places it, one level deep, as one undo step; the Expand dialog's Fill and Stroke reach that art (`object.expand`, `crates/engine/src/tests/expand_symbols.rs`; estimated, score unchanged). - **Reset Transformation** ([Transform symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/transform-symbols.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): the Symbols panel menu's Reset Transformation and the Control bar's Reset, shown while symbol instances are selected, give the selected instances their symbol's own scale again, without rotation or shear, as one undo step (`symbol.instance.resetTransform`); an instance in perspective is left as it is. VectorCraft's own rules: each instance keeps the center of its bounding box in place, reflection is removed too, and the menu item and the button are enabled only while a selected instance would change. Tests: `tests::brushsym::reset_transformation_restores_the_symbols_scale_and_keeps_the_center`, `reset_transformation_keeps_the_center_of_art_away_from_the_origin`, `reset_transformation_ignores_a_stored_size_that_is_not_positive`, `reset_transformation_leaves_unchanged_instances_and_refuses_bad_ids`, `panels::symbols::tests::reset_transformation_is_enabled_for_a_transformed_instance_and_resets_it`. + - **The Symbols and Properties panels find selected symbol instances once per revision:** whether the selection or its groups hold a symbol instance (Break Link to Symbol), one with appearance changes of its own (Reset Symbol Instance and the Properties panel's Reset), or one Reset Transformation would change is worked out in one walk of the selected objects for each document revision, and later frames reuse it. The buttons and menu items are enabled as before. With one selected group of 300,000 paths, the two panels' reads took a median 5.1 to 5.7 ms of thread CPU time per frame; the first read after a change now takes about 3 ms and later frames about 5 ns (Linux, opt-level 3, median of 7 runs). In a small document the difference is too small to notice. Tests: `panels::symbols::tests::instance_flags_are_found_once_per_revision_and_match_a_walk_of_the_selection`, `properties_and_symbols_panels_walk_the_selection_once_per_revision`. - **Expand of dimensions:** Object › Expand, Expand Appearance, Create Outlines and Outline Stroke turn a dimension whose art they change into a plain group of that art, which stays as it is through later moves, scales and edits of what it measured; undo gives the live dimension back (`crates/engine/tests/it/dimensions.rs`; VectorCraft's own rule; estimated, score unchanged). - **Brush libraries** ([public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html)): Window › Brush Libraries, the Brushes panel's Brush Libraries Menu and its menu's Open Brush Library open each library in a library panel of its own, as swatch, graphic style and symbol libraries do. The built-in libraries (Art Ribbons, Ink and Wash, Calligraphic Nibs, Bristle Brushes, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, Dry Media, Tech Circuit) are original brushes generated in code (`crates/engine/src/cmd/brushlib.rs`); Striped Ribbon's art is filled with the library's own pattern and Sparkles scatters the library's own symbol; Ink and Wash adds ink and wash brushes (the [help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html) lists an Ink brush library of strokes with varied thickness and texture; the names, shapes and opacities are VectorCraft's own): Tapered Ink, an art brush broad near its start that thins to a fine tip; Brush Pen, a calligraphic brush whose size follows the pen pressure; and Soft Wash and Pooling Wash, art brushes of translucent gray layers that take the stroke color as tints; Game Trails adds motion art brushes (Speed Line, Dash Trail, Burst Ray, Zigzag); Energy Beams adds laser and plasma art brushes (Laser Bolt, Plasma Arc, Charge Wave, Spark Trail); Dry Media adds grainy art brushes (Chalk Grain, Graphite Pencil, Wax Crayon, Charcoal Dust). A click on a brush adds it to the document's Brushes as one undo step with every resource its art uses (patterns, symbols, swatches, graphic styles, images), makes it the current brush and, with paths selected, applies it to them in the same step; a brush the document already has is not added again and a different brush of the same name comes in numbered ("Wave 2"). Shift/Cmd-clicks select brushes for Add to Brushes; a brush dragged onto a path is added and applied to it, and one dragged onto the Brushes panel is added. Save Brushes… / the Brushes panel's Save Brush Library… write the document's brushes (or the selected ones) as a `.vectorcraft` library into the `Brushes` folder next to the preferences, listed under User Defined, or to a file; Other Library… reads the brushes of any document VectorCraft opens. Thumbnails, in the library panels, the Brushes panel and Brush Options, render brush art with the patterns and symbols it uses. Copying brushed art now carries the patterns and symbols its brush's art uses too. Tests: `crates/engine/src/tests/brushlib.rs`, `crates/ui-egui/src/panels/tests_brush_libraries.rs`, `panels::brushes::tests::library_brush_previews_show_the_patterns_their_art_uses`, `canvas::tests::a_library_brush_dropped_on_a_path_is_added_and_applied_in_one_step`. - **Bristle Brushes library** ([What's new](https://helpx.adobe.com/illustrator/desktop/new-features/whats-new.html), [About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Bristle Brushes holds ten bristle brushes, one for each tip shape (Fine Liner, Pointed Flat, Stubby Round, Dry Scrub, Soft Dome, Filbert, Angled Round, Angled Flat, Fan Blender, Grass Fan). The brushes, their names and their values are VectorCraft's own, and every value lies inside the range the bristle brush keeps (`brush.libraries`, `brush.addFromLibrary`; `the_bristle_brushes_library_covers_every_tip_shape_within_the_bristle_ranges`). + - **Bristle strokes follow recorded pen input** ([brush documentation](https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=201)): a Bristle brush in VectorCraft widens its strand spread and thickness with pressure along the stroke; pen tilt changes the spread, and bearing and barrel rotation turn it in the path's local frame. Missing pen channels use neutral values, and mouse strokes keep their existing appearance. This is VectorCraft's own rendering model; hardware-specific output has not been verified. `bristle_pen_pressure_changes_its_footprint`, `bristle_pen_pressure_is_sampled_along_the_stroke`, `trimmed_bristle_strands_read_pressure_where_they_begin` and `bristle_pen_orientation_changes_its_footprint` cover the geometry in `crates/brush/src/tests.rs`; `bristle_path_keeps_and_draws_its_pen_pose` covers saving and export in `crates/engine/src/tests/brushsym.rs`; area scores unchanged. - **Tech Circuit library:** Circuit Trace is a chamfered art brush with 45-degree elbows and terminal pads; Bus Lines repeats three parallel conductor lanes; Terminal Nodes repeats solder pads, circular test points and connecting leads. Original vector geometry generated in code, with Tints colorization and continuous pattern tile edges. Evidence: `the_tech_circuit_library_constructs_adds_and_applies_each_brush` in `crates/engine/src/tests/brushlib.rs` covers listing, finite geometry on straight, curved, short and closed paths, add/apply, undo/redo, deduplication and saved-library round trips. G5 remaining estimate 3–13 h (estimated); area scores unchanged. - **Dry Media library** ([help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Dry Media holds four art brushes with textured strokes like dry drawing materials, each 100 pt long: Chalk Grain (about 8 pt high), Graphite Pencil (about 2.3 pt), Wax Crayon (about 5.5 pt) and Charcoal Dust (about 7 pt). The brushes, their names, sizes and art are VectorCraft's own: each is filled vector paths from a fixed seed, at most 80 paths and 500 anchors, stretched along the path with Tints colorization, and the chalk and crayon art has even-odd gaps where the paper shows (`brush.libraries`, `brush.addFromLibrary`; `the_dry_media_library_holds_grainy_art_brushes_with_bounded_art`). - **Brush names in library panels**: a built-in brush library's panel shows its brushes' names in the UI language, in its list rows and tooltips, and its Find field matches the name shown or the English name. This is VectorCraft's own rule. A User Defined or Other Library… library's brushes, and the document's Brushes panel, show names as they are stored. A click, a drag, Add to Brushes and `brush.addFromLibrary` still use the English name, so the brush comes into the document under that name (`built_in_library_brushes_are_listed_in_the_ui_language`, `built_in_library_brush_names_are_in_complete_catalogs`). @@ -1122,6 +1170,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Pixel Snapping Options:** Control bar › Snapping › Pixel Snapping Options… sets whether View › Snap to Pixel snaps drawing, moving and scaling, each on by default (`view.snapToPixel.options`, the `pixelSnap` preference group; [the help page](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/draw-pixel-perfect-art.html)). Tests: `pixel_snapping_options_read_set_and_reset`, `pixel_snapping_options_choose_the_edits_snap_to_pixel_rounds`, `handle_drag_follows_the_while_scaling_option`, `move_follows_the_while_moving_option`, `an_anchor_drag_follows_the_while_moving_option`, `new_ruler_guide_follows_the_while_moving_option` and `the_control_bar_snapping_menu_opens_pixel_snapping_options`. Scores and estimates unchanged. - **Measure tools and Snap to Glyph:** with Snap to Glyph, Smart Guides and Alignment Guides on, and Snap to Grid and Snap to Pixel off, both ends of a Measure or Measure & Inspect drag land within the snapping tolerance on the guides of live type that the Character panel's options allow, except Anchor Point, and a Shift-drag's end slides along its 45° step to them. The guide shows during the drag. This is VectorCraft's own rule (`Targets::for_measure`, `xform::measure::tests::its_ends_land_on_glyph_guides_with_snap_to_glyph`); scores and estimates unchanged. - **Drawing readout without the rubber band:** with Enable Rubber Band for the Pen or Curvature tool off and Measurement Labels on, the Pen, the Smart Pen and the Curvature tool hide the preview segment but still show the D / Angle / dX / dY readout at the snapped pointer before the next click, and the Curvature tool also shows it when going on from the current end of a selected path. Measurement Labels show distance and placement while drawing ([the help page](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/smart-guides-options.html)), and the rubber band preference turns off the path preview ([the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/preview-paths-drawn.html)). Showing the readout with the rubber band off is VectorCraft's own rule (`pen::tests::measurement_label_shows_with_the_rubber_band_off`, and `the_measurement_label_shows_with_the_rubber_band_off` in `draw2::curvature::tests` and `addons::smart_pen::tests`); scores and estimates unchanged. + - **Pen handle drags in the Info panel:** while a Pen drag pulls a handle out of an anchor, the Info panel shows the change in x and y (W, H), the distance (D) and the angle, as the Info panel overview in the [archived user guide](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=76) describes for the Pen. The values run from the anchor being shaped to the end of the handle the drag shapes: the outgoing handle of a new or added anchor or of the last anchor, and the incoming handle of the first anchor when the drag closes the path. Shift gives the constrained handle, Space moves the anchor with its handle, and the readout starts past the 3-pixel drag threshold and ends when the button comes up, the press is dropped or the tool changes. These details are VectorCraft's own rules. Tests: the `info_readout_*` tests in `pen::tests`; scores and estimates unchanged. - The desktop app keeps the Color panel's Show Options or Hide Options between sessions, and `ui.colorPanel` sets its mode and options as its panel menu does. - Preferences that act (#394, in part): Show Tool Tips, Double Click To Isolate, Zoom with Mouse Wheel (the wheel zooms about the pointer, Shift-wheel scrolls up and down, Cmd/Ctrl-wheel sideways; Alt/Option-wheel and a trackpad pinch zoom about the pointer either way), Use Precise Cursors; Selection & Anchor Display › Tolerance (objects, anchors and handles), Object Selection by Path Only, Command Click to Select Objects Behind (cycling down the stack), Zoom to Selection, anchor Size, Highlight anchors on mouse over; Type › Number of Recent Fonts (up to 15); Guides & Grid › guide and grid Color and Style (lines or dots) and Grids In Back. Then Snap to Point (its distance, for moves, drawn points and reference points), Move Locked and Hidden Artwork with Artboard, Enable Rubber Band for the Pen and Curvature tools, Handles style, Show handles when multiple anchors are selected, Hide Corner Widget for angles greater than; General › Transform Pattern Tiles (the transforms' and dialogs' Transform Patterns, Align and Distribute, art moved or duplicated with an artboard, and objects moved whole with direct-selected anchors) and Select Same Tint %; Type › Size/Leading, Tracking and Baseline Shift increments (`type.step`, Cmd+Shift+. and Cmd+Shift+, for the size, the Type tool's Alt+arrows), Enable Missing Glyph Protection and Fill New Type Objects With Placeholder Text. Then Smart Guides › Color, Alignment Guides, Anchor/Path Labels, Measurement Labels, Transform Tools, Object Highlighting (with Smart Guides on) and Snapping Tolerance (4 px by default, for every smart guide snap), then Construction Guides and their Angles (#506: a drawn point near a line at one of those angles through the point it leaves from lands on it). Then Type › Type Object Selection by Path Only (type is picked on the baseline of any of its lines, area type's frame or the path of type on a path, no longer anywhere in its bounds; the Type tools and the Eyedropper still take a click among the characters). Then General › Anti-aliased Artwork (off, the canvas draws the art with hard edges). Then Guides & Grid › Show Pixel Grid (Above 600% Zoom), a line at every document pixel over the art in Pixel Preview, turning with a rotated view as the document grid now does too. Then General › Show The Home Screen When No Documents Are Open (off, closing the last document leaves an empty window; the Home button still opens the screen). Then Units › Numbers Without Units Are Points (on by default: a number typed with no unit into a field in picas is read in points, a typed unit still wins; dimmed unless a unit is Picas). Then User Interface › Auto-Collapse Iconic Panels (off by default: on, a click away from a panel popped out of the icon column puts it away). Then Performance › Animated Zoom (on, with GPU Performance, which it needs and which dims it when off: the Zoom tool dragged sideways zooms about the press, right in and left out, and held still zooms on, Alt out; off, a drag zooms to the area dragged across, now drawn as a marquee), User Interface › Large Tabs (taller document tabs) and Scale Cursor Proportional to UI (off, the tool cursors keep their size whatever the UI Scaling), and File Handling › Display Bitmaps as Anti-aliased Images in Pixel Preview (off by default: Pixel Preview draws images with each pixel taking its nearest image pixel). Type › Auto Size New Area Type works too (new area type gets Auto Size). They reach agents too (`prefs.set`, then `pointer_gesture` or `press_key`; `ui.wheel` on the control channel). Then Smart Guides › Spacing Guides (moves space the selection evenly with its row or column, see Drawing aids). Then Hyphenation › Exceptions (comma-separated words that never break, or break only at their hyphens; `prefs.set` and restore push them into the hyphenator, #394). Then Type › Show Font Names in English (off, font menus label a family by its native-language name when the font has one; documents still use the English family, #394). Then General › Display Print Size at 100% Zoom (off by default: View › Actual Size is one document point per screen point; on, one document inch fills 96 screen points, an inch at the reference density display scaling is set against; `view.actualSize` / `prefs.set`, #394). Then Guides & Grid › Gridline every and Subdivisions (changing either sets the grid of every open document; new and opened documents take that grid too, except a native file and the native document an SVG, PDF, `.ai` or EPS file carries, which open with the grid they were saved with; `file.new`, `document.open`, `file.newFromTemplate`, `file.revert`, #394). Then Appearance of Black › On Screen (Display All Blacks Accurately by default: pure CMYK black shows through the CMYK profile, a dark grey; Display All Blacks as Rich Black shows it on the canvas as RGB black, also in CMYK documents drawn by ink planes, while rich blacks, black tints and images show as before; `RenderOptions::rich_black`, #394). Then Appearance of Black › Printing / Exporting (Output All Blacks Accurately by default; Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB raster exports and Print as Bitmap; CMYK ink exports and the document stay unchanged; `prefs.blackOutput` / `richBlack`, #394). Then Units › Identify Objects By (Object Name by default: Layers, Variables and Layer Options show and edit free names; XML ID shows and edits AI-style XML ids, `_` for a space and `_xHH_` escapes, and `layer.setProps` / rename refuse invalid ids; the document still stores the object name, #394). Then Type › Highlight Alternate Glyphs (off by default; on, pink shows behind OpenType substitutions on screen, such as ligatures and contextual forms; Document Setup's Highlight Substituted Glyphs stays separate; `prefs.set` key `highlightAlternateGlyphs`, #394). Then Units › East Asian Type (the bullet below). Then User Interface › Open Documents As Tabs (see Window › Arrange). Two stored options still do nothing yet: Plug-ins & Scratch Disks › Primary and Secondary, and Clipboard Handling › Legacy vector clipboard (the audit below). - Preferences › General › Scroll Sideways with Cmd/Ctrl + Wheel (on by default; dimmed while Zoom with Mouse Wheel is on): while Zoom with Mouse Wheel is off, Cmd/Ctrl with a mouse wheel's whole notches scrolls the canvas sideways instead of zooming. Alt + Cmd/Ctrl-wheel and a pinch on a Mac trackpad, on a touch screen or in the web build still zoom about the pointer, and once a trackpad gesture holds Alt, it zooms until it ends, also after Alt is let go. Under either wheel preference, Cmd/Ctrl with a touchpad zooms about the pointer. @@ -1143,13 +1192,16 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - A plain step of a number field (Up/Down or a wheel notch) goes to the next whole unit in its direction and a Ctrl/Cmd step goes to the next tenth, so 5.1 mm steps up to 6 mm and down to 5 mm (#2881). A Shift step adds or takes ten and keeps the fraction. - In the number, text and color fields of the panels and the Control bar, Shift+Enter (Shift+Return) applies the value and keeps the field active with its value selected; a text box of several lines takes it as a line break. In a dialog, Shift+Enter applies the value and confirms the dialog, as Enter does. - The Pattern Options panel's Name field and the name fields that a double-click opens in the Layers, Artboards and Asset Export panels take Shift+Enter (Shift+Return) the same way: it applies the name and keeps the field active with the name selected. - - Scrubby labels (#400, beyond Illustrator, as in Photoshop): dragging a numeric field's label left or right (the ↔ cursor shows over it) steps the value one unit every 2 points (Shift: ten, Ctrl/Cmd: a tenth; counts stay whole), in the field's unit and within its limits, applied live as the art follows; the whole drag is one undo step and Escape puts the value back. A click on the label focuses the field; the text box itself never scrubs, and a field with no label doesn't. Text labels before a field (Transform, Properties, Control bar, Stroke, Transparency, form rows in dialogs) and the Character and Paragraph panels' icons act as labels, and so do the links that label a field (the Control bar's Stroke: and Opacity:, the Properties panel's Stroke), which a click still follows to their panel (#4088). Preferences › General › Scrub Numeric Fields by Dragging (on by default) turns it off. + - Scrubby labels (#400, beyond Illustrator, as in Photoshop): dragging a numeric field's label left or right (the ↔ cursor shows over it) steps the value one unit every 2 points (Shift: ten, Ctrl/Cmd: a tenth; counts stay whole), in the field's unit and within its limits, applied live as the art follows; the whole drag is one undo step and Escape puts the value back. A click on the label focuses the field; the text box itself never scrubs, and a field with no label doesn't. Text labels before a field (Transform, Properties, Control bar, Stroke, Transparency, form rows in dialogs) and the Character and Paragraph panels' icons act as labels, and so do the links that label a field (the Control bar's Stroke: and Opacity:, the Properties panel's Stroke), which a click still follows to their panel (#4088), and the Control bar's X:, Y:, W: and H:, which a click follows to the Transform panel. Preferences › General › Scrub Numeric Fields by Dragging (on by default) turns it off. - In the Transform panel, the Properties panel's Transform section and the Control bar, Alt+Enter (Option+Return) applies a value to a copy of the selection and selects the copy, in one undo step. With anchor points selected with Direct Selection it applies the value to them, as Enter does. Ctrl/Cmd+Enter in W or H applies the value and scales the selection proportionally with the link off. With the Artboard tool, it scales the active artboard proportionally. A percentage typed alone in W or H (`50%`) is that share of the size the field shows, and the link and Ctrl/Cmd+Enter keep the proportions as with a length (#2401). - The Control bar's underlined Transform link opens the Transform panel in a popover under it (reference point, X/Y/W/H, Rotate and Shear with their icons and angle presets, flips, shape properties, Scale Corners and Scale Strokes & Effects), as its Stroke link does the Stroke panel; X/Y/W/H also show inline while the bar has room. The reference point locator is nine squares, the outer eight joined around the box. As VectorCraft's own keyboard rule, the locator is one tab stop in the Control bar popover, the Transform panel, the Properties panel and the dialogs, the Arrange Tools dialogs included. While it has the focus it shows an outline, and ←, →, ↑ and ↓ move the reference point one square, stopping at the edges (`the_reference_point_grid_is_one_tab_stop`, `arrow_keys_move_the_reference_point`, `the_reference_point_locator_is_one_tab_stop_and_arrows_move_it`). + - A click on the Control bar's underlined X:, Y:, W: or H: label opens the Transform panel in a popover under that label, as the Transform link does, and a second click, Escape or a click elsewhere closes it; with the Artboard tool the popover shows the artboard's fields. The help page () describes these four labels as another way to bring up the Transform panel. VectorCraft's own rules: the click does not give the field the keyboard, a drag on the label still scrubs the field, and the labels are not tab stops, so Tab still moves from one field to the next and the Transform link stays the keyboard's way to the panel (`the_control_bars_x_y_w_and_h_labels_open_the_transform_panel`, `the_artboard_control_bars_x_y_w_and_h_labels_open_the_transform_panel`). + - The Control bar's inline X and Y show the point of the selection's box that the Transform panel's locator chose, counted from the ruler origin, and a new X or Y moves that point there; a new W or H resizes the selection about it. The help page () describes typing X and Y in the Transform panel or the Control panel after choosing the point on the locator. Use Registration Point for Symbol applies to the inline fields as it does to the panel's. Choosing another point changes only what the fields show; each field edit is one undo step (`panels::transform::tests::the_control_bar_fields_use_the_shared_reference_point`). - In isolation mode the Control bar has an Exit Isolation Mode button (`object.exitIsolation`), except while a pattern is edited. Outside isolation mode, with one group, compound path, path, image, mesh or placed file selected, it has an Isolate Selected Object button (`object.isolate`), which also isolates a path inside a group that Direct Selection selected. - The canvas context menu has Isolate Selected Path (`object.isolate`) when the selection is one path, a path selected inside a group or a compound path included, as the [help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=324) lists it beside Isolate Selected Group. As VectorCraft's own rule, neither item shows for two or more objects, or for an object `object.isolate` refuses: a hidden or locked object, one in a hidden or locked group or layer, a guide while Lock Guides is on, and, while a symbol is edited, an object outside the symbol's art (`single_path_context_item_enters_isolation`, `isolation_context_item_follows_selected_kind`, `isolation_context_item_skips_objects_that_cannot_be_isolated`). - While an opacity mask is edited, Exit Isolation Mode (Esc, the isolation bar's back arrow, the Control bar's button, and the Layers panel menu's and canvas context menu's Exit Isolation Mode) leaves mask editing as Stop Editing Opacity Mask does, in one undo step: the mask keeps the edits, and the masked object is selected. While a pattern is edited, the Exit Isolation Mode item of the Layers panel menu and of the canvas context menu saves the pattern and leaves pattern editing, as Done does. - A click anywhere on the isolation bar, the isolated object's name included, outside its back arrow, the breadcrumbs of the levels above and its buttons leaves isolation mode altogether, nested isolation included, as Exit Isolation Mode does ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=207)). As VectorCraft's own rules, the click stops editing an opacity mask, leaves symbol editing mode even while a group inside the symbol's art is isolated, together with the isolation the mode was entered from, and does nothing while a pattern is edited; a drag across the bar does not leave (`isolation_bar_background_click_exits_nested_isolation`). + - With a sublayer isolated, Exit Isolation Mode (the Layers panel menu item, the isolation bar's back arrow, the Control bar button and `object.exitIsolation`) goes back one layer at a time, isolating the parent layer, and leaves isolation mode from the top-level layer, as the [help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/isolate-objects.html) and an archived [help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=213) describe. As VectorCraft's own rules, Esc and the top-level layer's crumb leave isolation mode from a sublayer at any depth (`object.exitIsolation {all: true}`), a sublayer's crumb isolates that sublayer, a hidden or locked parent layer is not isolated, and a step up records no undo step (`exit_isolation_goes_up_one_layer_from_a_sublayer`, `isolation_bar_back_button_steps_up_through_sublayers`, `escape_leaves_an_isolated_sublayer_in_one_step`). - Numeric spinner arrows keep stepping while held with the mouse past the click timeout and stop on release (#6307; `a_held_spinner_arrow_repeats`). - Object › Vector Halftone keeps the selection box and hides selection marks on the temporary dots during Preview; turning Preview off or cancelling restores the original selection marks (#6369). - Tab shows and hides the panels (in the Type tool it types a tab) without moving the keyboard focus onto a field, so the next shortcut or letter still works; in dialogs and panel fields it moves between fields, one press each — a numeric field's scrub label is not a tab stop of its own, and the Transform panel's, Properties panel's and Control bar's W/H link comes after the fields it sits between (`one_tab_moves_from_a_field_to_the_next`). A field's up/down spinner, the chevron that opens its presets (Stroke Weight, font size, Rotate, Export for Screens' scale) and the Transparency row's opacity slider chevron are not tab stops either. Alt+↓ with no other modifier in a field with presets opens them with the keyboard focus on the chosen one, instead of stepping the field down; Enter picks the focused preset without pressing a dialog's OK, and after a pick or Escape the field has the keyboard focus again (`tab_goes_from_field_to_field_past_the_spinner_and_the_preset_chevron`, `tab_goes_from_the_opacity_field_past_its_slider_chevron`, `alt_down_opens_a_fields_presets_for_the_keyboard`, `escape_closes_a_fields_presets_and_returns_to_the_field`). @@ -1177,6 +1229,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Cmd/Ctrl+Alt+Shift+. and , (`type.size.increaseByFive`, `type.size.decreaseByFive`) step the font size of the selected type, or of the text the Type tool has selected, by five times the Size/Leading increment (Preferences › Type); Cmd/Ctrl+Shift+. and , still step it by one increment. - Cmd/Ctrl+Alt+Q (`type.resetTracking`) sets the tracking of the selected type, or of the text the Type tool has selected, to 0 and clears manual kerning while keeping the automatic method, in one undo step; at a caret it resets only the kerning there: of the character before it, or at the start of a line the space before the character after it (#5111). - Cmd/Ctrl+Alt+K (`type.highlightKerning`) and Cmd/Ctrl+Alt+Shift+F (`type.highlightFontName`) show the Character panel and give its Kerning field the keyboard focus with the value selected, or open its font family menu with the search field focused, on the keys the reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists for highlighting kerning and the font name field. The page lists the same key for selecting the tracking value; `type.highlightTracking` focuses the Tracking field the same way and has no default key in Keyboard Shortcuts. + - Type › Size ends with Other… (`type.highlightFontSize`), for a size the list does not hold: it shows the Character panel and gives its Font Size field the keyboard focus with the value selected, and the size typed applies on Enter. [The help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=488) describes Other in the Size menu as the way to enter a new size in the Character panel. Selecting the field's value, the separator before Other… and the item being dimmed without selected type are VectorCraft's own choices. - Cmd/Ctrl+Alt+L (`ui.newLayer`) opens Layer Options for a new layer, as an Alt-click on the Layers panel's New Layer button does, on the key the reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists for adding a layer through the New Layer dialog box. OK adds the layer above the current layer, and Cancel adds none. Cmd/Ctrl+L still adds a layer without the dialog. - F8 (`ui.symbolOptions`) opens Symbol Options for a new symbol made from the selection, as the Symbols panel's New Symbol button does, on the key the reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists for making a new symbol. OK makes the symbol and puts an instance of it in place of the art, and Cancel makes none. With nothing selected, F8 opens no dialog, and the status bar says that nothing is selected. Shift+F8 and Cmd/Ctrl+F8 still show the Transform and Info panels. - Cmd/Ctrl+Shift+X (`type.resetHorizontalScale`) sets the horizontal scale of the selected type, or of the text the Type tool has selected, to 100% as the Character panel shows it (the object's own stretch included), in one undo step; at a caret it leaves the text as it is. @@ -1184,6 +1237,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Cmd/Ctrl+Alt+N (`file.newWithoutDialog`) makes a document without opening the New Document dialog, on the key the reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page assigns to creating a document directly. The page does not say which settings the document gets. VectorCraft gives it the settings the dialog opens on (the first Recent entry, or the Print category's Letter while Recent is empty) and the next untitled name. - Cmd/Ctrl+F6 (`window.nextDocument`) and Cmd/Ctrl+Shift+F6 (`window.previousDocument`) make the next and the previous open document the current one, in tab order and as a click on its tab does, on the keys the reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists for navigating to the next and the previous document. After the last document comes the first, and before the first document comes the last. From the Home screen the keys go to the first and the last document. Keyboard Shortcuts lists both under Window. - Cmd/Ctrl+Alt+Shift+U (`document.switchUnits`) switches the document to the next unit of measurement, in one undo step, on the key the reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists for switching units of measurement. The page does not give an order. VectorCraft steps through the units in the order a right-click on a ruler lists them (Points, Picas, Inches, Millimeters, Centimeters, Pixels, Feet & Inches, Meters, Yards, Feet) and goes from Feet back to Points. + - Ctrl+` (`tool.selectLastSelection`, Select Last Selection Tool) on Windows and Linux chooses the selection tool chosen last of Selection, Direct Selection and Group Selection, on the key [the help page](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) lists for switching to the last-used selection tool; Magic Wand and Lasso do not count. Before one is chosen it chooses the Selection tool, and it keeps the remembered tool when that tool is already active. On macOS it has no default shortcut, because the system uses Command+` to switch between an app's windows; Edit › Keyboard Shortcuts can assign one. The first choice and the macOS default are VectorCraft's own rules. - Shortcut sets other apps save as text (`.kys`) open in Import Shortcut Set from File › Open, from Edit › Keyboard Shortcuts › Import… in the desktop app, or from a drop on the window. It matches each entry to a tool, command or panel by name and decodes the file's key and modifier codes where VectorCraft's default shortcuts agree on them; the user answers the rest, and Apply fills the Keyboard Shortcuts dialog's working set. The answers are kept with the preferences for the next import (`shortcutSet.read`, `importMatches.*`). - Edit › Keyboard Shortcuts › Export Text… saves the set shown in the dialog as a UTF-8 text file, as the reference app's [Export keyboard shortcuts list as a text document](https://helpx.adobe.com/illustrator/desktop/get-started/preferences-and-settings/export-keyboard-shortcuts-list.html) page describes (`shortcuts.exportText {path?, format?, pageSize?}`). The layout is VectorCraft's own: the set's name, then the Tools and Menu Commands rows in the dialog's order, each with its name, a tab and its shortcuts as the dialog shows them, and nothing after the tab for a row with no shortcut. In the desktop app its save dialog also offers a printable shortcut sheet as a PDF, which `format: "sheet"` also picks (`pageSize: "letter" | "a4"`, A4 when the current document prints on A4): the rows with a shortcut under a colored band per group, in columns on landscape pages, a layout of VectorCraft's own. It also offers a CSV file of the same rows (`format: "csv"`; Group, Command and Shortcut columns). Tests `shortcut_editor::tests::export_text_*`, `shortcut_editor::tests::export_sections_*`, `shortcut_editor::tests::the_save_dialogs_answer_picks_the_export_text_format`, `shortcut_editor::tests::the_sheet_is_on_a4_when_the_document_prints_on_a4`, `shortcut_sheet::tests::*`, `tests::picks::keyboard_shortcuts_export_text_*` and `tests::picks::export_text_with_a_format_gives_the_answered_name_its_extension`. - On Windows and Linux the app bar is the window's title bar (its own minimize, maximize and close buttons, drag to move, edges to resize), with the dragon app icon as the brand mark; dialogs and menus size to their content. As on a native menu bar, once one menu is open, moving the pointer onto another title opens that one. @@ -1227,6 +1281,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur `css.export` refuses a `scope` or `path` that is not a string (`5`, `true`, `["all"]`, `null`) before writing anything, instead of exporting the selection or returning the CSS as data; a left-out `scope` still exports the selection, and a left-out `path` still returns the CSS. `css.generate` and `css.export {scope: "all"}` refuse a malformed `ids` or `id`, which they do not use, as the selection's export does. Agents read the key object: `select.key` returns it, and `document.inspect` and the `ui.pointer` and `pointer_gesture` replies report it as `key`. `select.key` with an id that isn't a selected top-level object returns an error and leaves the key unchanged. The Select menu's Same commands, its Object commands that select art, Next Object Above and Below, saved selections and the Magic Wand (#2655) select only objects that Select All selects and objects inside them: nothing hidden or locked, nothing in a hidden or locked group, layer or sublayer, nothing on a template layer, and in isolation mode nothing outside the isolated group or layer. In isolation mode Select All, All on Active Artboard and Inverse select nothing while the isolated group or layer, or a group or layer it is in, is hidden, locked or a template layer. + Next Object Above and Below check only the siblings of the selected object, each through the layers and groups that hold it, instead of collecting every object Select All can reach on each press, and they select the same object. In a release build, stepping from the middle of 100,000 rectangles on one layer takes a median of 0.08 µs of thread CPU time per step, against 11.5 ms with a test-only copy of the earlier search, and 0.08 µs against 7.4 ms with 1,000 groups of 100 (7 alternating runs of each in one process; `next_object_perf`). The earlier search's time grows with the number of objects in the document, so the change matters on large documents. `next_object_gives_what_the_search_over_every_selectable_object_gave` compares every node and every step of random documents, isolation mode included, with the earlier search. In a CMYK document the Magic Wand's Fill Color and Stroke Color tolerances run from 0 to 100 and compare the colors' CMYK values; in an RGB document they run from 0 to 255 and compare RGB values, as the [help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf) gives the two ranges. The distance is VectorCraft's own: the Euclidean distance between the C, M, Y and K percentages, with RGB, Gray and Lab colors converted to CMYK. A tolerance above 100 set in an RGB document applies as 100 in a CMYK document and comes back in an RGB one. `magicWand.set` refuses a tolerance out of its range and changes nothing (`cmyk_document_compares_fill_and_stroke_colors_in_cmyk`, `set_rejects_tolerances_out_of_range_and_changes_nothing`). The Magic Wand finds compound paths, the selected objects and the objects it picks through hash sets instead of searching lists, and it selects the same objects in the same order. In a release build, with every second object selected in a document of 50,000 paths (12,500 of them in 6,250 compound paths), setting that selection and Shift-clicking takes a median of 142 ms of CPU time, against 353 ms for the same steps run with test-only copies of the earlier searches, and 30 ms against 61 ms at 20,000 paths (7 alternating runs of each in one process, measured while other builds were running; `magic_wand_membership_timing`). Small documents gain little: 2.1 ms against 2.3 ms at 2,000 paths. `membership_sets_give_the_same_objects_in_the_same_order_as_searches` compares the selection in each mode with the earlier searches. Select ▸ Object ▸ Bristle Brush Strokes selects the objects whose topmost stroke has a bristle brush, whatever the brush is named, and leaves out objects whose brush is of another type, also when its name has "Bristle" in it. @@ -1243,7 +1298,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Compound paths:** Make keeps the backmost object's appearance and each contour; selecting a member in Direct Selection reads and changes the compound's fill rule in Attributes. Direction remains a per-member edit. Rendered holes, unchanged contour geometry, no-op history and Undo/Redo are covered by `engine/tests/it/compound_attributes.rs` (#1197). Behaviour reference: [public compound-path documentation](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/create-compound-paths.html). Make Compound Path on a group (such as outlined type) keeps the paint of its backmost path instead of drawing nothing, and compound paths joined into one keep their holes (#1537). - **Saved selections:** Select ▸ Save Selection… asks for a name and keeps the selection in the document (saved with the file, undoable, up to 25); each one is listed at the bottom of the Select menu and a click selects its objects again; Edit Selection… lists them to rename or delete, applied together on OK. A file's saved selections are capped and checked against its objects when it opens. Select ▸ Update Selection replaces the objects of the saved selection last recalled with the selected objects, in one undo step that marks the document changed (`select.update`). After Edit Selection… renames that saved selection, Update Selection replaces it under the new name; after Edit Selection… deletes it, Update Selection is disabled until another saved selection is recalled or the delete is undone. Undo and Redo do not change which saved selection is recalled. - - **Drawing modes:** in Draw Inside, a double-click with a selection tool outside the object being drawn into sets the drawing mode to Draw Normal, as Shift+D does. Pastes follow the drawing mode ([drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html)) (#3705): in Draw Inside, Paste, Paste in Place and Paste on All Artboards put the copies inside the object drawn into, in one undo step, Paste Remembers Layers aside; in Draw Behind, Paste in Place and Paste on All Artboards put them just below the selection; Paste in Front and Paste in Back ignore the mode. Shift+D cycles Draw Normal → Draw Behind → Draw Inside → Draw Normal, skipping Draw Inside unless one path, compound path or type is selected. With the object drawn into isolated (a double-click on it with the Selection tool), art drawn or pasted inside it takes isolation mode into its clip group, so it can be clicked and isn't dimmed, as art added in isolation mode belongs with what is isolated ([isolation mode](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/isolate-objects.html)) (#3705); undo or redo that removes the isolated object ends isolation mode. While Draw Inside lasts, a dotted open rectangle marks the corners of the object drawn into (#4319). + - **Drawing modes:** in Draw Inside, a double-click with a selection tool outside the object being drawn into sets the drawing mode to Draw Normal, as Shift+D does. Pastes follow the drawing mode ([drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html)) (#3705): in Draw Inside, Paste, Paste in Place and Paste on All Artboards put the copies inside the object drawn into, in one undo step, Paste Remembers Layers aside; in Draw Behind, Paste in Place and Paste on All Artboards put them just below the selection; Paste in Front and Paste in Back ignore the mode. Shift+D cycles Draw Normal → Draw Behind → Draw Inside → Draw Normal, skipping Draw Inside unless one path, compound path or type is selected. With the object drawn into isolated (a double-click on it with the Selection tool), art drawn or pasted inside it takes isolation mode into its clip group, so it can be clicked and isn't dimmed, as art added in isolation mode belongs with what is isolated ([isolation mode](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/isolate-objects.html)) (#3705); undo or redo that removes the isolated object ends isolation mode. While Draw Inside lasts, a dotted open rectangle marks the corners of the object drawn into (#4319). In Draw Behind, New Layer (the Layers panel's button, its menu, Ctrl/Cmd+L and the Layer Options dialog) puts the new layer directly below the current layer, at its level, as [the help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=234) describes and [drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html) lists; Ctrl/Cmd-click still puts it on top and Ctrl/Cmd+Alt-click below, and New Sublayer is not affected (VectorCraft's own rule). - **Drawing:** Pen, Curvature, anchor tools, Pencil, Paintbrush, Blob Brush, Smooth, Path Eraser, Join. Direction handles dragged with Direct Selection or the Anchor Point tool snap to smart guides, and Shift keeps them at 45° steps from their anchor. The Pen continues any open path from the end clicked, and while drawing, a click on an end of another open path joins the two into one (#776). The Curvature tool edits any selected path, whatever drew it, keeping its shape except where edited (#798): a click on a point makes it current and a drag moves it, re-curving only its two segments; double-click, or Alt-click on any point but an end of an open path, toggles it smooth or corner and Delete removes it; a click on a segment adds a point without changing the shape; with an end of an open path current, clicks go on from it and its other end closes it (`path.curvatureEdit`). An Alt-click on an end of a selected open path makes that end current without changing it, so the next click goes on from it, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-shapes-with-the-curvature-tool.html) describes for continuing a path; an Alt-click that starts a new path places a corner point, as later Alt-clicks do. Every point a drawing tool places snaps to Smart Guides through one snapper (#506): the Pen's and Curvature tool's anchors, the Pencil's ends, the shape tools' start and dragged corner or radius (Rectangle, Rounded Rectangle, Ellipse, Polygon, Star, Line Segment, Arc, Spiral, the grids), the Type tool's click and frame, a new artboard's corners. A filled Pencil path keeps a stroke of None (#1804, part of #1679). While a Pencil or Paintbrush stroke is drawn back to within Close Paths When Ends Are Within of its start, the cursor shows the closing ring and a release there closes the path, as [Draw straight lines with the Pencil tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-straight-lines-with-the-pencil-tool.html) describes for the Pencil. The [ and ] keys reach the Blob Brush, the Eraser and the Symbolism tools in the app (#1734, part of #1661). Blob Brush and Eraser Tool Options' Size is Fixed or Pressure with a Variation (#4590, #3961): with Pressure a pen stroke is Size − Variation wide where it presses lightest and Size + Variation where it presses hardest, and a mouse stroke keeps the Size. `path.blob` and `path.eraseRegion` refuse a Size outside 0.1 to 1000 pt and a Variation outside 0 to 1000 pt, also with Size set to Fixed, and the drawing commands that read pen values refuse a pressure outside 0 to 1, a tilt outside −90° to 90°, a rotation outside 0° to 360° and a point array of more than six numbers, with an error naming the key; the document, the selection and the undo history stay as they were. The pressure and tilt ranges are those of [Pointer Events](https://www.w3.org/TR/pointerevents3/); the Size, Variation and rotation ranges are VectorCraft's own values (`tests::draw2::pen_values_outside_their_ranges_are_refused`). @@ -1253,10 +1308,12 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur While Alt is held during a Paintbrush stroke or before a press with no path selected that the Smooth tool can act on, the Paintbrush shows a closing cursor (a crosshair with a ring), and so does the Pencil with Alt key toggles to Smooth Tool off when Alt is pressed after the drag starts; releasing the mouse button with Alt still held closes the path. Before a Paintbrush press with such a path selected, Alt shows the Smooth cursor, and holding Alt at the press smooths that path with the Smooth tool's radius and Smooth Tool Options' Fidelity. A Pencil drag started with Shift or Alt held draws a straight line instead, which stays open. Smooth Tool Options' Fidelity is in pixels, as [the help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=79) gives it: the Smooth tool, and an Alt smoothing drag with the Pencil, Paintbrush or Blob Brush, refits the path at Fidelity divided by the zoom, so a drag smooths a path as much on screen at 25 % as at 800 %. Reading the pixels as screen pixels is VectorCraft's own rule, as for the Pencil and the Paintbrush (#5729); the range (0.05 to 100 px) and the default (2.5 px) are VectorCraft's own values, and a saved Fidelity keeps its number (`crates/tools/src/draw2/gesture/tests.rs` test `smooth_fidelity_is_in_screen_pixels_at_any_zoom`, `crates/engine/src/tests/draw2.rs` test `smooth_region_refits_at_the_tolerance_sent_at_any_zoom`). With Shift held at the press, the Pencil draws a straight line from the press point to the pointer at 45° steps from the Constrain Angle, as [Draw straight lines with the Pencil tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-straight-lines-with-the-pencil-tool.html) describes; pressed on an end of a selected open path, the line continues the path from that end (part of #3799). With Option/Alt held at the press and Alt key toggles to Smooth Tool off, the Pencil draws a straight line at any angle, and it stays open when Alt is still held at the release; Shift and Alt together keep the 45° steps (#3799). While Shift or Alt is held before the press, the Pencil shows a straight-line cursor (a crosshair with a short level line), as the page describes. Over an end of a selected open path, where the stroke continues the path, freehand or as a straight line, it shows a path-continuation cursor (a crosshair with a short line rising to the right), as [Extend paths with the Pencil tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/extend-paths-with-the-pencil-tool.html) describes, and again while a continuing stroke ends near an open end of another selected path, where the release connects the two ([Connect two paths with the Pencil tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/connect-two-paths-with-the-pencil-tool.html)). A continuing stroke, a straight line too, that ends within Close Paths When Ends Are Within of the path's other end shows the closing cursor, and the release closes the path; Alt held at the release closes a continuing freehand stroke too (a straight line stays open, as above). - - **Shapes:** all shape tools (including Flare) and the line, arc, spiral and grid tools. Space held while dragging out a shape, line, arc, spiral or grid moves it at its current size. While a grid is dragged out, Up/Down change its rows (concentric dividers) and Left/Right its columns (radial dividers). A click with a grid tool asks for the size, the divider counts and the grid options (#1377, in part): a skew for each set of dividers, Use Outside Rectangle As Frame or Create Compound Path From Ellipses, and Fill Grid; they are parameters of `shape.rectangularGrid` and `shape.polarGrid`, stay as the tool's options and apply to drags too. A shape just drawn stays adjustable with its tool: its Live Shape widgets drag, a press on its centre point (Show Center) moves the selection with the Selection tool's move arrow, snapping and Alt copy, and a press in the rotate zone just outside a bounding-box corner turns it about the centre with the Selection tool's rotate cursor (#5477; tests `a_shape_tool_moves_the_selection_by_its_centre_point_and_turns_it_from_a_corner` and, through the engine, `shapetools.rs`). A drag on one of its eight bounding-box handles scales it as the Selection tool's handles do, with their cursors and snapping, instead of drawing a new shape from the handle. A shape tool takes a press as a handle's only on the drawn handle square (VectorCraft's own rule: 3 screen points from its centre along each axis at the default Anchor Size, a half point more or less per step; the Selection tool takes 5), so a press just beside a handle still draws (tests `a_shape_tool_scales_the_selection_by_its_bounding_box_handles`, `a_shape_tool_draws_from_a_press_just_beside_a_handle` and `a_shape_tool_scales_the_shape_just_drawn_by_its_bounding_box_handle`). The curve a skew percentage follows and the direction of the radial skew are our own (the public documentation gives neither), and the dialogs have no reference point locator. An ellipse's Pie Start and End Angle and Invert Pie (Transform and Properties panels' Ellipse Properties, `object.setLiveShape {pieStart, pieEnd, invertPie}`) cut it as a pie (#812). With the bounding box showing, the Selection tool shows a selected ellipse's two pie widgets just outside it; dragging one sets its angle in one undo step and double-clicking one makes the ellipse whole again. A live polygon's Polygon Properties there: side count, angle, corner type and radius, radius, side length and Make Sides Equal once an uneven scale has made its sides differ (`object.setLiveShape {sides, polygonAngle, polygonRadius, sideLength, makeSidesEqual}`, part of #812); a star is a plain path, as in Illustrator. The Flare Tool Options last as the tool's options: the next flare dragged out uses them, a click's dialog shows them and double-clicking the tool opens them (part of #812). + - **Shapes:** all shape tools (including Flare) and the line, arc, spiral and grid tools. Space held while dragging out a shape, line, arc, spiral or grid moves it at its current size. While a grid is dragged out, Up/Down change its rows (concentric dividers) and Left/Right its columns (radial dividers). A click with a grid tool asks for the size, the divider counts and the grid options (#1377, in part): a skew for each set of dividers, Use Outside Rectangle As Frame or Create Compound Path From Ellipses, and Fill Grid; they are parameters of `shape.rectangularGrid` and `shape.polarGrid`, stay as the tool's options and apply to drags too. A shape just drawn stays adjustable with its tool: its Live Shape widgets drag, a press on its centre point (Show Center) moves the selection with the Selection tool's move arrow, snapping and Alt copy, and a press in the rotate zone just outside a bounding-box corner turns it about the centre with the Selection tool's rotate cursor (#5477; tests `a_shape_tool_moves_the_selection_by_its_centre_point_and_turns_it_from_a_corner` and, through the engine, `shapetools.rs`). A drag on one of its eight bounding-box handles scales it as the Selection tool's handles do, with their cursors and snapping, instead of drawing a new shape from the handle. A shape tool takes a press as a handle's only on the drawn handle square (VectorCraft's own rule: 3 screen points from its centre along each axis at the default Anchor Size, a half point more or less per step; the Selection tool takes 5), so a press just beside a handle still draws (tests `a_shape_tool_scales_the_selection_by_its_bounding_box_handles`, `a_shape_tool_draws_from_a_press_just_beside_a_handle` and `a_shape_tool_scales_the_shape_just_drawn_by_its_bounding_box_handle`). With such a tool, a double-click on a corner widget of a selected live rectangle or polygon shows and selects the Transform panel, and the tool, the selection and the document stay as they were (test `a_double_click_on_a_corner_widget_shows_the_transform_panel`). The curve a skew percentage follows and the direction of the radial skew are our own (the public documentation gives neither), and the dialogs have no reference point locator. An ellipse's Pie Start and End Angle and Invert Pie (Transform and Properties panels' Ellipse Properties, `object.setLiveShape {pieStart, pieEnd, invertPie}`) cut it as a pie (#812). With the bounding box showing, the Selection tool shows a selected ellipse's two pie widgets just outside it; dragging one sets its angle in one undo step and double-clicking one makes the ellipse whole again. A live polygon's Polygon Properties there: side count, angle, corner type and radius, radius, side length and Make Sides Equal once an uneven scale has made its sides differ (`object.setLiveShape {sides, polygonAngle, polygonRadius, sideLength, makeSidesEqual}`, part of #812); a star is a plain path, as in Illustrator. The Flare Tool Options last as the tool's options: the next flare dragged out uses them, a click's dialog shows them and double-clicking the tool opens them (part of #812). - **Shapes:** all shape tools (including Flare) and the line, arc, spiral and grid tools. Space held while dragging out a shape, line, arc, spiral or grid moves it at its current size. The Flare tool's center drag turns the rays by 0.1 radian at each drag update in which the pointer's document y grows, and back by as much at each one in which it falls, Shift held keeps their turn, and Space held during either of its drags moves the flare. While a grid is dragged out, Up/Down change its rows (concentric dividers) and Left/Right its columns (radial dividers). A click with a grid tool asks for the size, the divider counts and the grid options (#1377, in part): a skew for each set of dividers, Use Outside Rectangle As Frame or Create Compound Path From Ellipses, and Fill Grid; they are parameters of `shape.rectangularGrid` and `shape.polarGrid`, stay as the tool's options and apply to drags too. The curve a skew percentage follows and the direction of the radial skew are our own (the public documentation gives neither), and the dialogs have no reference point locator. An ellipse's Pie Start and End Angle and Invert Pie (Transform and Properties panels' Ellipse Properties, `object.setLiveShape {pieStart, pieEnd, invertPie}`) cut it as a pie (#812). With the bounding box showing, the Selection tool shows a selected ellipse's two pie widgets just outside it; dragging one sets its angle in one undo step and double-clicking one makes the ellipse whole again. A live polygon's Polygon Properties there: side count, angle, corner type and radius, radius, side length and Make Sides Equal once an uneven scale has made its sides differ (`object.setLiveShape {sides, polygonAngle, polygonRadius, sideLength, makeSidesEqual}`, part of #812); a star is a plain path, as in Illustrator. The Flare Tool Options last as the tool's options: the next flare dragged out uses them, a click's dialog shows them and double-clicking the tool opens them (part of #812). - **Shapes:** all shape tools (including Flare) and the line, arc, spiral and grid tools. Space held while dragging out a shape, line, arc, spiral or grid moves it at its current size. The Flare tool's center drag turns the rays with the pointer, Shift keeps them in their original orientation (unturned, or turned by a nonzero General › Constrain Angle), and Space held during either of its drags moves the flare. While a grid is dragged out, Up/Down change its rows (concentric dividers) and Left/Right its columns (radial dividers). A click with a grid tool asks for the size, the divider counts and the grid options (#1377, in part): a skew for each set of dividers, Use Outside Rectangle As Frame or Create Compound Path From Ellipses, and Fill Grid; they are parameters of `shape.rectangularGrid` and `shape.polarGrid`, stay as the tool's options and apply to drags too. The curve a skew percentage follows and the direction of the radial skew are our own (the public documentation gives neither), and the dialogs have no reference point locator. An ellipse's Pie Start and End Angle and Invert Pie (Transform and Properties panels' Ellipse Properties, `object.setLiveShape {pieStart, pieEnd, invertPie}`) cut it as a pie (#812). With the bounding box showing, the Selection tool shows a selected ellipse's two pie widgets just outside it; dragging one sets its angle in one undo step and double-clicking one makes the ellipse whole again. A live polygon's Polygon Properties there: side count, angle, corner type and radius, radius, side length and Make Sides Equal once an uneven scale has made its sides differ (`object.setLiveShape {sides, polygonAngle, polygonRadius, sideLength, makeSidesEqual}`, part of #812); a star is a plain path, as in Illustrator. The Flare Tool Options last as the tool's options: the next flare dragged out uses them, a click's dialog shows them and double-clicking the tool opens them (part of #812). - **Shapes:** all shape tools (including Flare) and the line, arc, spiral and grid tools. Space held while dragging out a shape, line, arc, spiral or grid moves it at its current size. The Flare tool's center drag turns the rays with the pointer, Shift keeps them in their original orientation, and Space held during either of its drags moves the flare. While a grid is dragged out, Up/Down change its rows (concentric dividers) and Left/Right its columns (radial dividers). A click with a grid tool asks for the size, the divider counts and the grid options (#1377, in part): a skew for each set of dividers, Use Outside Rectangle As Frame or Create Compound Path From Ellipses, and Fill Grid; they are parameters of `shape.rectangularGrid` and `shape.polarGrid`, stay as the tool's options and apply to drags too. The curve a skew percentage follows and the direction of the radial skew are our own (the public documentation gives neither), and the dialogs have no reference point locator. An ellipse's Pie Start and End Angle and Invert Pie (Transform and Properties panels' Ellipse Properties, `object.setLiveShape {pieStart, pieEnd, invertPie}`) cut it as a pie (#812). With the bounding box showing, the Selection tool shows a selected ellipse's two pie widgets just outside it; dragging one sets its angle in one undo step and double-clicking one makes the ellipse whole again. A live polygon's Polygon Properties there: side count, angle, corner type and radius, radius, side length and Make Sides Equal once an uneven scale has made its sides differ (`object.setLiveShape {sides, polygonAngle, polygonRadius, sideLength, makeSidesEqual}`, part of #812); a star is a plain path, as in Illustrator. The Flare Tool Options last as the tool's options: the next flare dragged out uses them, a click's dialog shows them and double-clicking the tool opens them (part of #812). + A live line drawn with the Line Segment tool shows Line Properties in the Transform panel and the Properties panel's Transform section: Line Length (a length above 0, in the document's units) and Line Angle (0° horizontal, 90° vertical, any value brought into 0° to 360°), the two properties that [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/live-shape-properties.html) lists for a line (`object.setLiveShape {lineLength, lineAngle}`). Typing one sets every selected line in one undo step. These rules are VectorCraft's own: the angle runs counterclockwise from 3 o'clock, as the Rotate field does; a new length keeps the line's first end in place and a new angle turns it about its midpoint; a line whose ends meet reads 0°; the section shows only while every selected object is a live line; and a line that would reach past the document's coordinate limit is an error that changes nothing. Expand Shape makes the line a plain path without these properties (tests `a_line_shows_and_takes_its_line_properties` and, through the engine, `a_line_takes_its_length_and_angle`). + Ellipse Properties in the Transform panel and the Properties panel's Transform section has a Constrain Pie Angle link beside Pie Start and Pie End Angle: while it is on, a typed angle moves the other one by the same amount, so the pie keeps its size, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/live-shape-properties.html) describes (`object.setLiveShape {pieStart or pieEnd, constrainPie}`). These rules are VectorCraft's own: the link starts off at every launch and is not saved; the two panels share it; each selected ellipse keeps its own span, counted counterclockwise from its start angle to its end angle and across 0°, in one undo step for all of them; a whole ellipse stays whole; after Invert Pie the swapped span is kept; and the on-canvas pie widgets still move one angle at a time (tests `the_constrain_pie_angle_link_keeps_the_span` and, through the engine, `constrain_pie_keeps_each_ellipses_span`). Backtick (`` ` ``) held while a rectangle, rounded rectangle, ellipse, polygon, star or line is dragged out leaves copies of the shape being drawn along the drag, each its own object: the continuous duplicate that the Keys for drawing table of [the help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=469) lists. Each copy is the shape as the drag showed it then, with its modifiers and Up/Down counts; the release keeps the copies and the last shape as one undo step, and Escape takes them all back. The spacing (a copy each time the pointer has moved 8 screen points with the key down, none for the key alone) and the limit of 128 copies a drag are VectorCraft's own values, and a shape with no width, height or length leaves no copy. The arc, spiral, grid and Flare tools do not leave copies (tests `backtick_drag_leaves_copies_of_the_rectangle_being_drawn` and, through the engine, `a_backtick_drag_leaves_copies_of_the_shape_as_one_undo_step`). Escape while a polygon, star or rounded rectangle is dragged out cancels it and puts back the side count, point count, corner radius or star ratio its Up/Down and Ctrl/Cmd changed, so the next drag, the tool's options and General › Corner Radius start from the values before the canceled drag; a drag that is let go keeps them, and an option set with `tool.setOption` during the drag stays. This is VectorCraft's own rule. A click with the Rounded Rectangle tool opens the size dialog with its radius at General › Corner Radius, and OK makes the radius typed there that preference, so later rounded rectangles and the dialog's next opening start from it while rounded rectangles already drawn keep their corners, as [the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=64) describes. A radius outside the preference's range of 0 to 1296 pt, which is VectorCraft's own, or one that is not a length is refused with an error: the dialog stays open, nothing is drawn and the preference keeps its value. Evidence: `dialogs::shapes::tests::{rounded_rectangle_click_dialog_opens_on_and_sets_the_corner_radius, rounded_rectangle_click_dialog_refuses_a_radius_out_of_range}`. @@ -1275,17 +1332,21 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With Smart Guides on, a straight Knife cut snaps to anchor points and paths: [Cut objects using the Knife and Scissors tools](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/cut-objects.html) describes the Knife snapping to anchor points and paths while Smart Guides are on. Its ends snap as the ends of the Pencil's straight line do, to anchor points and path segments of art that is shown: the press, and the release of an Alt-drag. Shift+Alt steps 45° from the snapped press, and its release stays on that step. With Smart Guides off, or with Snap to Pixel or Snap to Grid on, the cut is not snapped. The dashed line and `path.knife` use the snapped points. Eraser Tool Options has Angle and Roundness besides Size, as [Erase paths using the Eraser tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/erase-paths-using-eraser-tool.html) describes: the Eraser's tip is an ellipse Size across, its long axis at Angle and its short axis Roundness percent of the long one, and a drag with a tip that is not round shows the outline of the area it erases (`path.eraseRegion` `angle` and `roundness`). `path.eraseRegion` refuses an Angle outside −180° to 180° and a Roundness outside 1% to 100% with an error and leaves the document unchanged; a key left out or null takes its default (0° and 100%). The help page gives no range for the two options, so the ranges are VectorCraft's own values. `path.split` refuses a `t` outside 0 to 1 in the same way. + `path.eraseSegments` (the Path Eraser) refuses a `width` outside 0.001 to 1000 pt with an error and leaves the document unchanged; left out or null, the width is 8 pt. The help page gives the Path Eraser no width option, so the range is VectorCraft's own value. Eraser Tool Options gives Angle, Roundness and Size each a menu of Fixed, Random, Pressure, Tilt, Bearing and Rotation with a Variation field, as the same page describes: the tip varies by up to the Variation either way, Random once per drag and the others with what the pen reads at each point of the drag, and the tip outline at the pointer follows the pen while it erases. The outline of the area a drag shows takes, at each step, the tip the pen's readings give halfway along it, with a Random value shown as the value itself, and a mouse drag erases at the set values (`path.eraseRegion` `angleMode`, `roundnessMode`, `sizeMode` and their variations). The outline a Blob Brush or Eraser drag shows is built a bounded amount per frame, so a long stroke does not slow the canvas: each frame takes at most 256 new points of the drag and outlines again only the pieces of up to 32 segments they change, and the parts of a piece's outline inside the rest of the area are removed a limited amount at a time. While work is left, the canvas draws again with the pointer still, the points not outlined yet show as a thin line, and the tip shows at the pointer. When the tip varies with the pen (Size set to Pressure, or an Eraser mode that follows the pen), each step is its own piece and the outline also shows only the edge of the whole area. The release sends the whole stroke as before (`path.blob`, `path.eraseRegion`). The settled part of that outline is kept in paths of up to 64 pieces each. A path is shared from one frame to the next until a piece in it changes, and the canvas keeps the triangles it drew the path with while the view stays the same, so a frame does not copy, flatten or tessellate a settled path again; a pan, zoom or rotation draws each one once more. This is VectorCraft's own rule. The line that a drag of more than 64 segments shows with a round Eraser tip, the Knife, the Path Eraser or the Pencil with Live preview off is kept the same way, in pieces of 64 segments: a frame builds again only the last piece, and the Knife's dashes run on from one piece to the next. With the Eraser's Size set to a mode that follows the pen, each step of such a drag is kept as its own path and a frame builds only a new step. A smoothing drag's band is kept until it changes. The canvas still copies the kept triangles of every piece into each frame. - **Transform:** Rotate, Reflect, Scale, Shear (click or Alt-click snaps the reference point to anchors and centres; Alt-click opens the tool's dialog, and a drag with Alt down at the release, from the press or pressed mid-drag, transforms a copy), Reshape, Free Transform (free and perspective distort and shear, switched by the keys held during a handle drag). A Reshape drag stretches part of a path from the dragged point without losing the path's general form, as [Adjust path segments](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/adjust-path-segments.html) has it. On an open path the stretch reaches both ends: the end anchors stay in place, each anchor between moves less the nearer it lies to an end, and the handles of a smooth anchor stay in line (`path.reshape`; the reach and the shares are VectorCraft's own rule, in `docs/mcp.md`). A click sets a focal point and a click on a segment adds a highlighted anchor there; Shift-click adds more, and a drag from any of them moves them all. The anchors that are not direct-selected stay in place and a closed path selected whole moves whole (VectorCraft's own rule, in `docs/mcp.md`). - Align, Distribute, Distribute Spacing, Reflect and Shear return an error for any `horizontal`, `vertical`, `to`, `axis`, `bounds` or `spacing` value they don't take, listing the choices, and Align returns one when a call gives neither `horizontal` nor `vertical`; nothing moves and no undo step is recorded. Align and Distribute act on the anchor points selected with Direct Selection: the points of one path align to each other, not to the artboard, and Distribute spaces them (#1641, fixes #1636; aligning to a key anchor is still missing). + Align, Distribute, Distribute Spacing, Reflect and Shear return an error for any `horizontal`, `vertical`, `to`, `axis`, `bounds` or `spacing` value they don't take, listing the choices, and Align returns one when a call gives neither `horizontal` nor `vertical`; nothing moves and no undo step is recorded. Shear takes an angle from -359° to 359° and shears by its tangent, so 120° slants as -60°; an angle outside that range, and ±90° and ±270° (VectorCraft's own rule), return an error ([shear objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/shear-objects.html); `shear_angles_slant_by_their_tangent`, `shear_rejects_angles_with_no_shear_or_out_of_range`). Align and Distribute act on the anchor points selected with Direct Selection: the points of one path align to each other, not to the artboard, and Distribute spaces them (#1641, fixes #1636; aligning to a key anchor is still missing). Transform Each opens on the scale, move, rotate, reflect, Random, reference point, Transform Objects and Preview it was last confirmed with (kept with the UI state; Copy never is), and its Copy button, left of Cancel, transforms a copy of each object as the [Scale multiple objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-multiple-objects.html) help page has it; the Copy checkbox is gone (#1732; the remembered values follow a maintainer comment on the issue, not the help page). Its Scale section has the Relative and Absolute radio buttons the same page describes: percentages of each object's size, or the width and height it becomes (`object.transformEach` `relative`, which Transform Again repeats); Absolute measures each object's own box, and the scales act along its axes about that box's reference point, so a turned shape keeps its shape and objects of different sizes come out alike; the fields show the width and height the selected objects share and read "Mixed" when they differ or a side is 0 (a line's), each object measured by its own box, rotated with it, as the Transform panel and the Control bar show it (sizes they show alike count as the same), and a size typed into them sets every object to it (a side left Mixed keeps its size), our choices where the page leaves them open; a live Repeat scales its spacing by the geometric mean of the two factors, so its Absolute size is approximate. The link beside the two scales keeps them in proportion, as the shape dialogs' Width and Height link does (`__constrain`, kept with the dialog's values; where it sits is our choice, the public pages don't establish it). The panel lists Scale, Move and Rotate, then the Options in two columns (Transform Objects, Transform Patterns, Scale Strokes & Effects, Scale Corners; Reflect X, Reflect Y, Random), the Reference Point, and Preview at the left of the button row, level with Copy, Cancel and OK. Transform Again uses the Copy, Transform Patterns, Scale Strokes & Effects and Scale Corners choices of the transform it repeats; after a bounding-box handle drag on area type, it resizes the type area again and the type keeps its size (`object.transformAgain`). With anchors selected with Direct Selection, Move, Rotate, Scale, Reflect, Shear and Transform Again (the commands, their dialogs and the four tools' drags) transform only those anchors, their handles with them, about the centre of the box around them unless a point was clicked; a copy still copies the whole object (#1408; behaviour reference: [adjust path segments](https://helpx.adobe.com/illustrator/using/adjust-path-segments.html); the default reference point and the copy are our choices). The Move, Rotate, Scale, Reflect and Shear dialogs have a Preview checkbox, off when they open: while it is on the canvas follows the values, Cancel rolls it back and OK is still one undo step; Up/Down step the Rotate and Shear angles and the Scale percentages by 1, Shift by 10 (#1412). The five dialogs and Transform Each have Transform Objects beside Transform Patterns: off, the art stays and only its pattern tiles transform (`objects` on the transform commands), and Transform Again repeats the choice (#1448; behaviour reference: [scale objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-objects.html); the checkboxes are always enabled and the Scale page's pair is applied to all of them, our choices). Reflect's axis is Horizontal, Vertical or an angle (#1460; [reflect objects along an axis](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/reflect-objects-along-an-axis.html)). + Shear's axis is Horizontal, Vertical or Angle: the Shear dialog's Axis Angle field, and a numeric `axis` on `object.shear`, set a line on the page from -359° to 359° that the art slides along, apart from the shear angle; an axis angle outside that range is an error and nothing changes ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/shear-objects.html) describes this angled axis and its range; counter-clockwise from horizontal and the field's 0° start are our choices). Tests: `shear_along_an_axis_at_an_angle`, `reflect_and_shear_reject_unknown_axes_without_changing_state` and `shear_takes_an_axis_angle`. - **Pen:** Alt pressed in the middle of dragging out an anchor splits its handles and keeps the curve already shaped into it (only the outgoing handle follows the pointer); Space held while dragging out an anchor moves it, handles and all. A press on the first anchor of the path being drawn closes it whatever the drag then does: the drag shapes the closing curve and the release closes the path wherever it ends (#501). The first anchor's incoming handle mirrors the pointer, and a click leaves it retracted and the anchor a corner. Its outgoing handle stays where it is on a corner, so the first segment keeps its shape, and on a smooth anchor it turns to stay in line at its own length; Alt makes the anchor a corner and leaves the outgoing handle where it was when Alt went down. The Smart Pen's closing drag does the same (fixes #6634; `path.close`'s `in` and `out`; behavior reference: [draw with the Pen, Curvature, or Pencil tool](https://web.archive.org/web/20220614224656/https://helpx.adobe.com/illustrator/using/drawing-pen-curvature-or-pencil.html), where a click or drag on the first anchor closes the path and Alt breaks the pairing of the closing anchor's handles; which handles the drag sets are our choices). Space held during the Pen's closing drag moves the first anchor, handles and all, as that page also describes (`path.close`'s `at`). Clicking the last anchor of the path being drawn retracts its outgoing handle (convert cursor), and dragging from it pulls out a new one on its own. Auto Add/Delete: over a selected path, a click on a segment adds an anchor and a click on an anchor deletes it (add and delete cursors); Shift held, or Preferences › General › Disable Auto Add/Delete, starts a new path instead. Alt held over a handle end or an anchor of a selected path (the one being drawn too) works as the Anchor Point tool, with its convert cursor: dragging a handle moves it alone, clicking a smooth anchor makes it a corner, dragging an anchor pulls out new symmetric handles, dragging a segment reshapes it; drawing then goes on. Cmd (Ctrl) held drags with the selection tool chosen last, Direct Selection until one is (handles, anchors and segments of the path being drawn or another), and the Pen then goes on drawing its path while that stays selected; the pointer shows that tool's while Cmd is held. The same holds for agents (`pointer_gesture` with `mods.cmd`), as the borrowing now lives in the engine (#494). A drag's preview (the Pen's, the Anchor Point tool's, Direct Selection's handles and anchors) follows every position the pointer is seen at (#834): the canvas sends the tool a drag whenever the pointer's document position differs from the last one it sent, not only when egui's frame delta is non-zero (zero when a compositor coalesces motion and in the frame the pointer comes back into the window after leaving it), and a move that arrives in the release's own frame shapes the preview before the release commits it, once the press has dragged. With the Pen, a press that moves under 3 screen pixels is a click (a corner without handles), and a Precise Cursors command toggles the existing preference and can take a shortcut (#1663). + Choosing the Pen again while it draws a path (P, a click on its button, `tool.select`) ends the path as Escape does: the path stays open and selected (a path inside a compound path leaves the compound path selected), the Pen stays chosen, and the next click starts a new path. The [help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/preview-paths-drawn.html) describes P doing this with the preview off; doing it with Rubber Band on and for the button and `tool.select` are VectorCraft's own rules. - **Direct Selection (#1278):** clicking a segment picks its connection, with hollow endpoint anchors and only that curve's direction handles. Delete leaves the neighboring curves and appearance intact, opens/splits contours in one undo step, and another Delete removes the remaining selected path. A whole-path drag and deliberate anchor selection keep their existing behavior; egui frames and native control/art checked, OS mouse/visual QA pending. Where anchors of overlapping objects coincide, a click or drag takes the anchor of the selected object, also when another object lies over it (#1509, fixes #1508). Delete removes every selected anchor of a closed path (it used to remove the wrong ones), removes objects selected whole along with the selected anchors of others, and keeps the remainder selected so a second Delete removes it (#1674). In isolation mode Direct Selection and Group Selection pick only inside the isolated object (#1666). Escape cancels a Direct Selection drag (#1803, #1743). Double-clicking type (including type nested inside a group) switches to the Type tool and puts the caret at the clicked character. With Direct Selection and Group Selection, a drag that starts on an object while the selection also holds direct-selected anchors or segments moves those anchors and the objects selected whole in one undo step (`path.moveAnchors`), as a drag of a selected anchor does, and the other anchors of a partly selected path stay in place. While Alt is held during the drag, it copies the selected objects instead (`object.transform`). When direct-selected anchors are moved or transformed together with objects selected whole (such a drag, an anchor drag, an arrow key, or Move, Rotate, Scale, Reflect and Shear without a copy), a path inside a selected group is transformed once, with the group. + VectorCraft's own preference General › Interpolate Control Points When Moving Anchors (`interpolateControlPoints`, off by default, fixes #7832): on, a Direct Selection drag, an arrow-key nudge, a Move or a Transform Again of selected anchors re-maps both handles of each segment with one moved end by the turn, uniform scale and move that take its old ends to its new ends, so a segment between corner anchors keeps its shape; a segment with both ends moved, or with its ends at the same place before or after the move, moves rigidly, and a smooth anchor keeps its handles in line. The commands take an `interpolate` param that defaults to the preference, and the value used joins the journal and Transform Again. Each drag or nudge is one undo step (`a_nudge_with_the_preference_on_re_maps_both_handles_of_the_segment`, `a_direct_selection_drag_with_the_preference_on_re_maps_the_handles_in_one_undo_step`, `a_smooth_anchor_keeps_its_handles_in_line`). A path segment with a control point whose x or y is infinite or larger in size than `f64::MAX / 16` is measured by its control points, so its bounds hold the whole curve and the canvas check refuses an edit that leaves such a path selected (`path.create` included). With Direct Selection, the Pen and the anchor tools, a group, compound path or clip group selected whole shows the anchors of its paths filled, as a path selected whole does; the direction handles still show only on a path that is selected itself. Public references: [Adjust anchor point, handle, and bounding box display size](https://web.archive.org/web/20251114182206/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/adjust-anchor-point-handle-and-bounding-box-display-size.html) and [Drawing basics](https://web.archive.org/web/20231130064834/https://helpx.adobe.com/illustrator/using/drawing-basics.html) (archived copies). When the Add Anchor Point tool, the Pen's Auto Add, the Smart Pen's Alt-click on a segment or Alt-click with the Scissors adds an anchor to a path with direct-selected anchors or segments (`path.insertAnchor`), the same points stay selected: the anchors and segments after the new anchor are numbered one higher, and a selected segment that the new anchor splits stays selected as its two halves. @@ -1306,6 +1367,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur View › Hide Edges hides the Live Corners widgets, the bounding box and the type widget, and the selection tools then do not answer a press on them or change the cursor over them. - **Blend spine Anchor Point tool (#2544):** on a selected blend, dragging a spine corner makes symmetric Smooth handles; the tool displays and picks existing spine handles when switched to, drags one independently or retracts it on click, and clicking a point with handles retracts both. The spine is edited live without moving its key objects. Windows native canvas checks and screenshots reviewed: symmetric and independent handles, corner/retraction, Shift constraints and perpendicular reshaping, tool switching, key preservation, Undo/Redo, save/reopen, hidden handles and overlapping Path/Blend priority (PR #2643). Behaviour reference: [public path-editing documentation](https://helpx.adobe.com/illustrator/using/adjust-path-segments.html). - **Blend spine points by marquee:** with Direct Selection, a marquee picks the spine points inside it on a selected blend, the topmost one when several are selected, and the picked points drag together as Shift-clicked ones do; Shift-marquee adds points or takes picked ones away, a plain marquee around none of them drops the picks, and Escape during the marquee keeps them. Unselected, locked and hidden blends are skipped. The spine's points are anchor points edited with Direct Selection ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/modify-spine-of-blended-objects.html)), and a boundary drag with the tool selects anchor points ([the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/select-anchor-points-in-paths.html)); the rules for selected, topmost and Shift are VectorCraft's own (`crates/tools/src/direct/tests.rs`, `marquee_picks_selected_blend_spine_points_which_drag_together`, `shift_marquee_toggles_selected_blend_spine_points`, `marquee_skips_unselected_locked_and_hidden_blend_spines`, `escape_cancels_a_marquee_and_keeps_the_picked_spine_points`). + When no selected object is a blend, the selected-spine checks of Direct Selection's hover, press and marquee, the Anchor Point tool and the Pen return at once instead of building every blend's spine first; on 20,000 paths and 200 blends with one path selected, 500 checks took 24 µs instead of 336 ms, and the results are the same (`the_selected_spine_check_builds_no_spine_without_a_selected_blend`, `the_selected_spine_check_matches_a_filter_of_every_spine`; `selected_spine_check_timing` times it). - **Blend steps of brushed strokes:** the steps interpolate the pen pressure, tilt, bearing and rotation recorded with the Paintbrush, so a Calligraphic, Scatter or Art brush that varies with the pen changes gradually from one key to the next. A key without a recording counts as half pressure, half tilt and 0°, as brushes read it, and angles turn the shorter way round. When the blend starts a key's path at another anchor (an open path run from its end, a closed one turned to another start), the key's recordings, width profile, arrowheads, dashes and a gradient along or across the stroke turn with the path. Different brushes still switch halfway (VectorCraft's own rule; strokes blend their options, as [Blended objects overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blended-objects-overview.html) describes; `crates/doc/src/blend.rs`, `pen_pressure_tilt_and_angles_interpolate_for_brushes`, `stroke_profiles_turn_with_a_key_path_started_elsewhere`, `stroke_gradients_and_dashes_turn_with_a_key_path_started_elsewhere`). - **Blend steps of spot gradients with process plates:** when the matching stops of two gradients, or of a gradient and a solid, are tints of one spot swatch, each step's stop stays linked to it at a tint between the two and keeps the process inks printed with it, each of C, M, Y and K between the two stops' amounts; a stop or solid without process inks counts as none of each. Gradients with different stop counts keep the inks at every resampled stop. PDF export writes such a step as one DeviceN shading of the spot and process inks. Tints of one spot color blend into tints of it, as [the help page](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blended-objects-overview.html) describes; the process-ink interpolation is VectorCraft's own rule (`crates/doc/src/blend.rs`, `blend_gradient_spot_process_plates_interpolate`, `resampled_gradient_spot_process_plates_interpolate`, `blend_gradient_missing_plates_mean_zero`, `blend_solid_to_spot_gradient_does_not_copy_plates`; `crates/pdf/src/tests/output.rs`, `blend_steps_between_spot_gradients_with_process_plates_print_both_inks`). - **Path editing (#494):** the handles shown are the handles that drag: Direct Selection drags those of a path selected as a whole (as the Pen leaves it), the Anchor Point tool and Pen+Alt no longer grab handles that Show handles when multiple anchors are selected hides, a handle shorter than the tolerance leaves its anchor to be picked, and the anchor tools pick within Selection & Anchor Display › Tolerance. A dragged segment keeps a smooth anchor at either end smooth. With Direct Selection, the Pen, the Curvature and the anchor tools, a path selected as a whole shows all its anchors selected, and the Control bar and the Properties panel offer Convert (corner, smooth) for them too; Remove and Cut wait for anchors direct-selected (#504). A handle drag gathers its snap targets once per drag (it took 21 ms per pointer move on a 20,000-path document, now 1 ms; `vectorcraft-cli perf` measures handle and segment drags on a 5,000-anchor path). Join merges the selected anchor points that lie on one another, as after Average, into one anchor (#1582, fixes #1533), and removes the merged anchors in one pass over the path, so a long run of them no longer moves the anchors after it once per merge (`cmd::path::tests::a_long_run_before_many_other_anchors_merges_in_one_pass`); Object › Path › Average & Join… (`path.averageJoin`, Cmd+Alt+Shift+J, the "Create corner or smooth join" shortcut of [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)) moves two open path ends to their midpoint and joins them there, a corner or smooth point as its dialog's Points choice asks, in one undo step. @@ -1334,6 +1396,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur As VectorCraft's own rule, a zoom marquee that Cmd+Space starts while the Type tool edits text keeps the marquee's Space rules after Cmd is let go: Space held since the press sizes it, Space pressed again moves it ([the help page](https://helpx.adobe.com/illustrator/using/viewing-artwork.html) describes holding the spacebar to move the marquee), and that Space types no space, nor does it during an animated zoom drag. With no zoom drag, Space types a space. Test: `canvas::tests::space_moves_a_text_edit_zoom_marquee_after_cmd_is_let_go`. - **Swatches panel clicks:** Ctrl/Cmd-clicking New Swatch makes a spot color, and Ctrl/Cmd+Shift-clicking it makes a global process color. - **Panel drag and drop:** art dragged off the canvas onto the Symbols panel becomes a symbol, art dragged onto the Swatches panel becomes a pattern swatch, and art dropped on the Brushes panel opens New Brush for that art; a symbol dragged onto the canvas places an instance where it is dropped, and a brush dragged onto a path is applied to it. + A symbol dragged from one document's Symbols panel and dropped on the canvas after another document became active places the dragged symbol, not a symbol of the same name in the active document (`symbol.placeFromDocument`). VectorCraft's own rules: the symbol, the symbols it nests and the resources they use are added to the active document as a drop of art from the other document adds them, in the same undo step as the instance; a symbol the document already has with the same art and Symbol Options is used, and one with the same name but other art or options is added under a free name ("Leaf 2"); the chip at the pointer shows the dragged symbol; a symbol whose document was closed before the drop places nothing and the status bar shows the error. Tests: `canvas::tests::a_symbol_dragged_from_another_document_places_that_documents_symbol`, `a_symbol_whose_document_closed_places_nothing`, `the_pointer_chip_of_a_dragged_symbol_shows_its_own_documents_symbol`, `tests::symbollib::another_documents_symbol_is_added_and_placed_in_one_step`. New Brush asks for the type of brush first, as the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy) describes. The Brushes panel's New Brush button, its menu's New Brush… and art dropped on the panel open the New Brush dialog, where Scatter Brush, Art Brush and Pattern Brush need selected or dropped art. OK opens that type's Brush Options for the new brush, and their OK makes the brush with the name and options set; Cancel in either dialog adds no brush (`ui.newBrush`). The menu's New Calligraphic Brush, New Bristle Brush and New Art, Scatter and Pattern Brush from Selection items still make a brush at once. - **Panel drag and drop:** art dragged off the canvas onto the Symbols panel becomes a symbol, onto the Swatches panel a pattern swatch and onto the Brushes panel an Art brush; a symbol dragged onto the canvas places an instance where it is dropped, and a brush dragged onto a path is applied to it. In the Brushes panel, a brush dragged onto another brush of its type goes before or after it, by the half of the tile or row the pointer is over, and a bar marks the slot while the brush is held there (`brush.move`); the move is one undo step. Brushes move only within their type, as the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page states: a brush dropped on a brush of another type stays where it is, and the status bar shows "brushes move only within their type". @@ -1357,17 +1420,21 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Before a press that draws a new path, the Pencil cursor shows a small star, as [Draw freeform paths with the Pencil tool](https://web.archive.org/web/20260926095638/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-freeform-paths-with-the-pencil-tool.html) describes; over a selected path within Edit selected paths' distance, which the press continues from an end or redraws, the star is not shown ([Reshape paths with the Pencil tool](https://web.archive.org/web/20260106004407/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/reshape-paths-with-the-pencil-tool.html)). Keep selected in the Pencil and Paintbrush Tool Options is on by default: while it is on, a stroke selects the path it draws or continues and replaces the earlier selection. While it is off, a new stroke leaves nothing selected, the earlier selection included, as the reference application starts the stroke by dropping it (#5752); a continued or redrawn path is deselected while the rest of the selection stays (`path.freehand` `keepSelected`). With two open paths selected, a Pencil stroke from an end of one that ends within Edit selected paths' distance of an end of the other connects them into one path with the first path's appearance, in one undo step, as [Connect two paths with the Pencil tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/connect-two-paths-with-the-pencil-tool.html) describes (`path.freehand` `connect`). + `path.freehand` and `brush.freehand` refuse a `connect` without `extend` with an error, and check a `connect` given with `extend` before a stroke of one point returns, so a bad one changes neither the path's brush nor the selection. Double-clicking the Shape Builder tool opens Shape Builder Tool Options ([Shape Builder tool options](https://web.archive.org/web/20260105172244/https://helpx.adobe.com/illustrator/using/building-new-shapes-using-shape.html)): with Consider Open Filled Paths as Closed off, a filled open path cuts regions as an unfilled one does; Pick Color From Color Swatches fills merged shapes with the current fill, the Left and Right arrow keys step it through the document's color swatches, and Cursor Swatch Preview shows the current fill and the swatches before and after it above the pointer; Selection Straight Line merges what the line from a drag's first point to its last crosses ([Setting Illustrator's Shape Builder Options](https://web.archive.org/web/20260615204453/https://creativepro.com/setting-illustrators-shape-builder-options/)); with Highlight Fill off, merge mode shades no regions (`shapeBuilder.merge` `openFilledAsClosed` and `pickColorFrom`). As VectorCraft's own rule, Consider Open Filled Paths as Closed counts an open path as filled when any of its fill rows draws (shown, painted and above 0% opacity), whichever row is on top, as the canvas paints it: a painted fill under an unpainted top fill closes the path, and a painted fill that is hidden or at 0% opacity does not. The region map, merges, erasing and Clicking Stroke Splits the Path follow that rule, and the Shape Builder takes the faces and edges of a Live Paint group that one of their fill or stroke rows draws and whose own opacity is above 0. Regression tests: `tests::build::shape_builder_closes_open_paths_by_the_fill_rows_that_draw`, `tests::build::shape_builder_stroke_split_closes_open_paths_by_the_fill_rows_that_draw` and `tests::build::shape_builder_takes_the_live_paint_faces_and_edges_that_draw`. With In Merge Mode, Clicking Stroke Splits the Path on in the same dialog, a click on a stroke in merge mode splits its path into the run of stroke under the pointer and the rest of the path, as the [Shape Builder tool options](https://web.archive.org/web/20260105172244/https://helpx.adobe.com/illustrator/using/building-new-shapes-using-shape.html) page describes; the run goes from the anchor or crossing point before the pointer to the one after it, and the pointer shows scissors over it. Highlight Stroke When Editable draws that run in the color chosen in its Color list (Red by default), and with Pick Color From Color Swatches the run takes the current fill as its stroke (`shapeBuilder.merge` `splitStroke`). As VectorCraft's own rule, OK in Shape Builder Tool Options gives an error for a highlight Color with an alpha part (`#rrggbbaa` or `#rgba`) and changes nothing. Regression test: `dialogs::shape_builder_options::tests::a_highlight_color_with_an_alpha_part_is_refused`. With Pick Color From Artwork, a merged shape takes the appearance, opacity and blending mode of the object where the drag starts, else of the object where it ends, else of the front-most selected object, as the [Shape Builder combine page](https://web.archive.org/web/20251006211643/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/combine-shapes-with-shape-builder-tool.html) describes. A click in an area that no selected object covers, such as a hole other shapes enclose, takes the front-most selected object's look (`shapeBuilder.merge` `points`: the first point is where the drag starts, and the last point is where it ends). A Shift-drag with the Shape Builder tool draws a rectangular marquee for merging many paths at once, as [Combine shapes with the Shape Builder tool](https://web.archive.org/web/20251006211643/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/combine-shapes-with-shape-builder-tool.html) describes: the regions it reaches are shaded while it is drawn and merge into one shape on release, or with Alt they are deleted. The marquee reaches each region whose outline crosses it or has an anchor inside it, and the region that holds the whole marquee; this rule is VectorCraft's own. For Pick Color From Artwork, the marquee's starting corner is where the drag starts and the opposite corner is where it ends (`shapeBuilder.merge` `rect`). + The Shape Builder works on the selected paths, as [Combine shapes with the Shape Builder tool](https://web.archive.org/web/20251006211643/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/combine-shapes-with-shape-builder-tool.html) describes. As VectorCraft's own rule, a click or drag that builds nothing says why in the status bar when it is released: "Shape Builder: select paths or compound paths" when nothing is selected or the selection holds no unlocked, visible path; "Shape Builder: select all paths you want to merge" when the release is over a path or compound path that is not selected; and "Shape Builder: no region under the pointer" otherwise. The document, the selection and the undo history stay as they were, and the next gesture that builds something clears the message. Regression tests: `shape_builder_with_nothing_selected_says_what_to_select`, `shape_builder_names_the_unselected_path_under_a_release_that_built_nothing` and `shape_builder_replayed_gesture_over_nothing_gives_its_status_once` in `builder/tests.rs`, and `tests::build::shape_builder_click_that_builds_nothing_shows_why`. Shape Builder pieces on dense hatches (lines at exact 0.25 or 0.5 pt steps across another line) come back one per stretch between crossings, with no speck where the sweep cut a line's two passes a rounding error apart: the planar map contracts the stub between such cuts into one vertex, bounded by each cluster's extent so a run of tiny level segments keeps its length (`crates/pathops/src/planar.rs` tests `a_dense_hatch_at_exact_binary_steps_cuts_each_line_once_per_crossing`, `a_run_of_tiny_level_segments_is_not_contracted_as_stubs`, `a_line_crossed_where_its_two_passes_part_is_cut_once`). + The Shape Builder's gray hatch over the region under the pointer and the regions a drag has touched is drawn by a sweep that tests each hatch line only against the region's edges that span it, instead of every edge on every line. The hatch lines are the same, coordinate for coordinate; on a 2,000-sided region 1,000 hatches take about 83 ms of CPU time instead of 356 ms (release build, median of 7 alternating runs), and on a region of 40 sides the time is about the same, so the gain is on large, complex regions such as traced art (`crates/tools/src/builder/tests.rs` tests `hatch_matches_testing_every_edge`, `hatch_tests_only_the_edges_spanning_each_line` and `hatch_sweep_finds_the_crossings_of_every_edge`; timing: `hatch_perf`). The planar map's edge-source grid stays linear in memory on any input: a segment is filed once per cell it crosses, and the grid holds at most a budget of cell references (a few dozen per item plus a few rows' worth), past which the remaining items go to a short scanned list and are still found, so thousands of coincident segments cannot make the index quadratic (`crates/pathops/src/planar.rs` test `rect_index_holds_a_bounded_number_of_references`). The Blob Brush Tool Options have Keep selected and Merge only with selection, both off by default: while Keep selected is off, the blob a stroke draws or merges into is not selected afterwards, and while Merge only with selection is on, a stroke merges only with selected blobs of its color that it touches (`path.blob` `keepSelected` and `mergeOnlySelection`). The Blob Brush Tool Options also have Angle and Roundness, as the reference app's [Blob Brush options](https://web.archive.org/web/20261012042029/https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/blob-brush-options-and-best-practices.html) list them: Angle from −180° to 180° (0° by default) and Roundness from 0% to 100% (100%, a round tip, by default). The elliptical tip keeps its angle on the page along a stroke, a 0% tip is drawn 0.1% as wide as it is long, and the dialog shows the tip and three dabs of it. The values are kept with the tool's options (`path.blob` `angle` and `roundness`). Not done: the Random and pen-driven variations of Angle and Roundness. The Blob Brush Tool Options' tip preview is the Angle slider for screen readers, with the Angle in degrees as its value: a click or a drag in it points the Angle at the pointer and gives it the keyboard focus, Tab reaches it after the Roundness field, and the arrow keys step the Angle by 1° (10° with Shift, Home and End to −180° and 180°). + The tip preview also has an arrowhead on its Angle line and a black dot at each end of the tip's short axis. A drag that starts on a dot sets the Roundness: moving the dot toward the center makes the tip flatter and moving it away makes it rounder, as the Blob Brush tool options section of the [help page](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=183) describes. A click or a drag that starts anywhere else in the square still sets only the Angle. The mapping is VectorCraft's own: the Roundness is the pointer's distance from the center along the short axis as a percentage of half the tip's length (18 pt in the preview), in whole percent from 0% to 100%, and the drag goes on past the square's edge until the release. A press within 8 pt of a dot takes the dot. The dot drag gives the keyboard focus to a Roundness slider, which screen readers get after the Angle slider and which Tab reaches after it; its arrow keys step the Roundness by 1% (10% with Shift, Home and End to 0% and 100%). Regression tests: `dialogs::tests::a_drag_on_a_blob_brush_tip_dot_sets_the_roundness`, `dialogs::freehand::tests::a_roundness_dot_sets_its_distance_along_the_short_axis`. The Blob Brush Tool Options also have Fidelity, which the reference app's [Blob Brush options](https://web.archive.org/web/20261012042029/https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/blob-brush-options-and-best-practices.html) list as setting how far the pointer moves before the path gets a new anchor point. The range and default are VectorCraft's own values: the Pencil's logarithmic slider from Accurate (0.01 pt) to Smooth (20 pt) and its field (up to 100 pt), 1.5 pt by default and kept with the tool's options. The brush follows the stroke fitted at the Fidelity, as a Pencil stroke is fitted: a low value follows the drag closely, jitter included, and a higher one gives smoother curves (`path.blob` `fidelity`). `path.blob` rejects an Angle outside −180° to 180°, a Roundness outside 0% to 100% and a Fidelity outside 0.01 to 100 pt with an error and leaves the document unchanged; a key left out or null takes its default (0°, 100% and no fitting). A Blob Brush stroke merges with the topmost path of its fill color and no stroke that it touches, and with the other such paths it touches in the same group or layer that are next to that path in stacking order with no other kind of object between them; matching paths in other groups or layers are left alone, as the Blob Brush tool guidelines in [Paint with fills and strokes](https://web.archive.org/web/20241219085603/https://helpx.adobe.com/illustrator/using/painting-fills-strokes.html) describe (`path.blob`). @@ -1384,7 +1451,13 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Command Palette leaves out the engine commands that Edit › Keyboard Shortcuts marks as needing a value: a query with no default key and no menu bar item (Document JSON, Select All Unused in the Brushes panel), and a command that needs a value no menu item gives (Window › Transparency's `transparency.set`, Document Setup's units). Of those, it still lists the ones whose pick does something without params: Stop Script, Clear Script Console, Clear Plug-in Cache, Reset Preferences, Forget Import Matches, Begin Undo Group and End Undo Group, the six Save … Preset commands, Delete Gradient Preset, Pixel Snapping Options…, the Asset Export commands, New Symbol, Gradient Vector, Define Perspective Grid and Select Slice. Each panel is a result under Window › Show Panel, whose pick shows the panel and leaves one already showing as it is, and each Effect menu item is a result, named as the menu names it, whose pick runs what its menu item runs; while the item is dimmed, no dialog opens and the status line says why. A query of "layers" shows the Layers panel first. The search field's hint and the app bar's search tooltip say "Search commands, tools, panels and effects" (`palette` tests `the_palette_leaves_out_the_commands_a_pick_cannot_run`, `a_pick_of_a_session_command_runs_it`, `a_panel_is_a_result_whose_pick_shows_it`, `an_effect_is_a_result_whose_pick_runs_its_menu_item`; `shortcut_editor` test `a_command_given_a_key_that_needs_a_value_is_no_pick`). The Command Palette shows each result as a 20-point row, with no gap between rows, and shows 12 rows at a time in a list that scrolls; a short window shows fewer. A name too long for its row ends with "…". The list holds up to 50 results, and the line under it says how many matched ("14 results", "50 of 120 results. Keep typing to narrow them." or "No commands match"). Up and Down move the highlight and wrap at the ends, Page Up and Page Down move it by the rows shown and stop at the ends, and the highlighted row scrolls into view; after a scroll with the wheel, the highlight moves to the nearest row in view. A click anywhere on a row runs it. Screen readers stay on the search field, whose description names the highlighted result and its place among every match ("2 of 14: …", or "2 of 120: …" when the list holds 50); the rows are list items, the highlighted one selected, and the keyboard focus goes back to where it was when the palette closes, unless a pick opened a dialog (`palette` tests `results_are_compact_rows_that_touch`, `the_footer_counts_the_results`, `with_no_match_enter_runs_nothing`, `the_sixteenth_result_is_reached_by_keyboard_and_runs`, `page_keys_move_by_a_page_without_wrapping`, `a_wheel_scroll_keeps_the_highlight_in_view`, `the_row_under_the_pointer_is_the_one_highlighted`, `a_long_name_ends_with_an_ellipsis`, `the_popup_stays_inside_a_short_window`, `a_click_anywhere_on_a_row_runs_it`, `screen_readers_hear_the_highlighted_result_and_the_count`, `closing_gives_the_focus_back`). A press of any pointer button outside the Command Palette closes it: a click, a right-click or the start of a drag. While the palette is open, the canvas, the toolbars, the docked panels and the app bar under it do not respond to the pointer, so the press that closes the palette does not press a tool button or another control there. A window drawn above them, such as a progress window, still gets its click, and that click also closes the palette (`palette` tests `a_click_on_the_canvas_closes_the_palette`, `a_click_on_another_control_closes_the_palette_without_pressing_it`, `a_right_click_or_a_drag_outside_closes_the_palette`, `a_click_on_a_window_above_closes_the_palette_and_reaches_it`, `the_click_that_opens_the_palette_does_not_close_it`). + A modal window that opens without a press in the window (a dialog opened from the macOS menu bar or by an automation command, the About window, a file dialog, the update prompt, or the progress window of a plug-in, trace or open run) closes the Command Palette, a tool group's flyout, the All Tools drawer and any open menu or popup in the pass it opens. While such a window is open, the palette stays closed, so opening it from the macOS menu bar or by an automation command does not take the keyboard from the window; it opens again once the window closes (`palette` tests `a_dialog_opened_from_the_system_menu_closes_the_palette`, `the_about_window_closes_the_palette`, `a_progress_window_closes_the_palette`, `the_palette_opened_over_a_dialog_closes`, `a_click_on_the_menu_bar_closes_the_palette_before_a_dialog_opens`, `a_dialog_opened_without_a_press_closes_a_flyout`, `a_dialog_opened_without_a_press_closes_the_tools_drawer`, `a_dialog_opened_without_a_press_closes_a_menu`, `the_palette_opened_as_a_dialog_closes_stays_open_until_the_next_dialog`). The Command Palette ranks its results by how well they match. A query that is a result's id lists that result first (`view.goto1` lists Saved View 1 above Saved View 10); then come results whose name is the query, results whose name without its menu path starts with it, and results whose initials it is ("ea" finds Export As…). Within each of those, a result where every word of the query is a whole word of its name ranks above one where a word only starts a word of the name, then one where it is a word of the menu that holds it, then of its id, then text inside a word, so a query that is a menu's title ("object") lists results named with that word above the items of that menu. A tool ranks above a menu command, panel, effect or filter plug-in that matches as well, so "rect" lists the Rectangle Tool above Effect › Convert to Shape › Rectangle…, and of two results of the same kind the shorter name comes first. Words of the menu bar item that runs a result also find it, the item's own label included ("exit" finds Quit VectorCraft, which File › Exit runs); with the native macOS menu bar, the items that bar moves into its application menu are found under it (Preferences… under Settings). Every result the earlier search found is still found, and the highlight stays on its result when a plug-in is installed, a shortcut changes or the language changes while the palette is open (`palette::search` tests `a_better_word_grade_ranks_first`, `a_better_whole_query_tier_ranks_first`, `kind_and_length_never_lift_a_worse_grade`, `a_menu_title_does_not_lift_its_items`, `common_queries_list_the_command_near_the_top`, `every_result_is_found_first_by_its_name_and_its_id`, `every_result_found_before_is_still_found_and_shown`, `results_know_their_place_in_the_menu_bar`, `native_homes_follow_the_native_application_menu`; `palette` test `the_highlight_stays_on_its_result_when_the_results_change`). + A Command Palette query word in an English plural or verb form finds a result whose English name or menu path holds the base word: "rounded corners" lists Effect › Stylize › Round Corners… first, and "scaling" finds Object › Transform › Scale…. The search drops `'s`; `es` after `s`, `x`, `z`, `ch` or `sh` (also trying the word with only its `s` dropped, so "rasterizes" finds Rasterize…); a final `s` in words of more than 3 letters, except after `ss`, `us` or `is`; `ing` in words of more than 5 letters and `ed` in words of more than 4. After `ing` or `ed`, a doubled `b`, `d`, `g`, `m`, `n`, `p`, `r` or `t` is tried both single and doubled, the single letter only when at least 3 letters are left ("cutting" meets Cut, "added" meets Add); otherwise the word is also tried with an `e` ("scaling" meets Scale…). It turns `ies` into `y` or `ie` in words of more than 5 letters and `sses` into `ss`, and leaves `series` and `species` as they are. Among results that the whole query matches the same way (as an id, as a label, at the start of a label, as initials, or none of these), a result whose name holds the base word of a query word ranks below one that holds the query word whole and above one where the query word only starts a word of the name, so "scale zz" lists a name with "Zz Scaling" above one with "Zz Scalers". "scale" alone still lists "Scalers" above "Scaling", because "Scalers" starts with the query. A partly typed word that is not itself a word of any result ("scal") does not meet a base word. Names shown in other languages and ids are not changed this way, and every result found before is still found (`palette::search` tests `plurals_and_verb_forms_meet_their_base_word`, `a_plural_or_verb_form_finds_the_result`, `a_better_word_grade_ranks_first`, `a_partly_typed_word_does_not_lift_a_verb_form`, `a_whole_query_tier_comes_before_a_stem_form`, `results_matched_without_a_stem_keep_their_order`). + A Command Palette query word with a typo still finds the result: "gruop" lists Object › Group first, and "eyedroper", "rectange" and "elipse" list the same first results as the words spelled right, the Eyedropper, Rectangle and Ellipse tools among them. When a query word of 4 or more letters is not a word, a base word or the start of a word of any result's name, menu path or id, the search compares it with the words of result names and menu paths, and a word 1 edit away (2 for a query word of 8 or more letters) matches; a letter added, left out or changed, or two letters next to each other swapped, is one edit. A query word meets at most the 32 nearest such words. Results matched through a typo come after every result the query matches without one, and among them the query is read with the misspelled word replaced by the word it meets, so they come in the order the word spelled right gives; then a result whose label holds the word comes before one whose menu path holds it. Ids, and query words and result words with Chinese, Japanese or Korean letters, are not compared this way, and results without typos keep their order (`palette::search` tests `edits_are_counted_up_to_a_bound`, `a_word_with_a_typo_finds_the_result`, `a_typo_meets_at_most_32_words`, `misspelled_words_find_the_command`). + A Command Palette query word also finds a result whose name or menu path holds a word with the same meaning: "remove bg" lists Remove Background… first, "outline text" lists Type › Create Outlines first, and "flip", "combine", "vectorize" and "colour" list Reflect…, Unite, an Image Trace command and the Color panel among the first 3 results. The words come from VectorCraft's own table of 21 groups of English words (`palette/words.rs`, at most 60 groups of at most 6 words); a word that is the whole label of another command, such as Merge or Mirror, is in no group, and neither is Insert. A word or its English base word that is in a group meets the other words of its group in labels and menu paths, and their base words, but not ids or word starts. A result whose label holds the word itself ranks above one whose label holds a word with the same meaning, which ranks above one whose menu path holds the word, so "type" now lists Scale Text Attributes above Type › Orientation › Vertical. A catalog may add a group's words in its language with a row in the `search` context (the group's English words joined by ", ", then that language's words), used while that language is the UI language; no catalog has to have these rows (`palette::search` tests `a_word_with_the_same_meaning_finds_the_result`, `a_catalog_row_adds_words_to_a_group`, `words_with_the_same_meaning_find_the_command`; `palette::words` tests; `i18n` test `search_rows_name_a_group_and_add_single_words`). + A Command Palette query word also finds a command by what the command's description says: "transparent background" lists Remove Background… among the first 3 results, and "png" lists it after every result with "png" in its name or menu path. The description is the command's params text (an engine or plug-in command's, a UI command's, or an effect's) without each `{…}` group that is not inside a `{`, `[` or `(` group, without each such `[…]` or `(…)` group just after a `→`, and without the `→` before a removed group, cut to its first 300 characters at the end of a word. The words of a schema ("corners" for Remove Background…) and of a result written as a group do not find the command; a result written as words after a `→` stays in the description. Words of 2 characters or fewer, words with no letter, and "the", "and", "ids", "true", "false" and "null" are left out. A query word that is a word of a description, shares an English base word with one, starts one or has the same meaning as one finds the result, and such a result ranks below every result that the query matches in its name, menu path or id, as text inside a word or through a typo. Descriptions are English only, and a typo does not match them. Tools, panels and filter plug-ins have no description (`palette::search` tests `a_description_leaves_out_the_schema_and_the_result`, `a_word_of_the_description_finds_the_result`, `a_description_match_ranks_below_a_typo`, `words_of_a_description_find_the_command`). + Each Command Palette row starts with an icon for its kind (a tool's own icon, or one for a panel, an effect, a filter plug-in or a command) and shows where the result lives after its label, in smaller dim text: the menu path of the menu bar item that runs it, with that item's label when it differs from the result's ("File › Exit" for Quit VectorCraft), and "No menu item" for a command no item runs. A panel's row shows "Window". A row with a home shows its label without the menu path in front of it. A path that keeps two results' names apart stays in the label, unless the row's home shows the same path; a tool's row drops the "Tools" in front of its name. A tool's row names the toolbar it is on: "Toolbar" for its button on the Tools panel, or the name of a toolbar made with New Toolbar, followed by ", in the group" when the tool is hidden in the group of a slot whose button shows another tool ("Toolbar, in the Direct Selection Tool group" for the Group Selection Tool), and "All Tools" when no toolbar holds it. A toolbar shown now comes first (the Tools panel, then the toolbars made with New Toolbar), then a hidden Tools panel, then hidden toolbars made with New Toolbar; toolbars count as hidden in Presentation Mode and while Tab hides the panels. The Learn command (`window.learn`), which Window › Learn runs, takes the Window menu as its home, so a search reads its menu path like any other result's, and among results that tie on everything else it ranks as a command of the menu bar, before panels and after tools. The home is cut short with "…" before the label, and a label too long for the row keeps the id it shows after its name unless the id alone is wider than the row. A cut row shows all its text while the pointer rests on it, and screen readers read the kind, the label, the home and the shortcut. The row height is unchanged (`palette` tests `rows_show_where_each_result_lives`, `no_two_rows_read_alike`, `a_tool_row_names_its_toolbar_slot`, `a_narrow_row_cuts_the_home_first_and_keeps_the_id`, `screen_readers_hear_the_kind_and_home`, `catalogs_translate_the_kind_and_home_words`). `object.setProps` with `visible: false` or `locked: true` deselects every selected object that is then hidden or locked, the key object included, as the eye and lock columns do. Ctrl/Cmd+Alt-clicking an eye switches the other layers to Outline and the row's layer to Preview, or switches all layers back to Preview when the others are in Outline (`layer.outlineOthers`, `layer.previewAll`). Ctrl/Cmd+Alt-clicking New Layer adds a layer directly below the current layer, at its level (`layer.new {below: true}`), and Ctrl/Cmd+Alt-clicking New Sublayer adds a sublayer under the contents of the layer it goes into (`layer.newSublayer {bottom: true}`), each in one undo step. The reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists these clicks for placing a layer below the selected layer and a new sublayer at the bottom of the layer list. @@ -1394,6 +1467,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Layer Options for several highlighted rows shows the first row's settings, and OK changes only the settings set in the dialog: each row keeps its own color, Template, Lock, Show, Print, Preview and Dim Images otherwise (`crates/ui-egui/src/dialogs/layer_options.rs` tests). As VectorCraft's own rule, a layer color (`layer.setProps`, `layer.new`, `layer.newSublayer`) or a Live Paint Gap Preview Color (`livePaint.gapOptions`) given as a hex color with an alpha part (`#rrggbbaa` or `#rgba`) is an error and changes nothing, instead of being set without its alpha. Regression tests: `a_layer_color_with_an_alpha_part_is_refused` in `crates/engine/src/tests/layers.rs` and `a_gap_color_with_an_alpha_part_is_refused` in `crates/engine/src/tests/build.rs`. Panel Options › Locate Selected Objects (beyond Illustrator, off by default): when the last selected object changes on the canvas or by a command, the panel opens the layers and groups around it and scrolls to its row, as Locate Object does, without highlighting the row; when Show Layers Only, a search or the filter leaves the object without a row, the panel opens no rows for it and scrolls as with the option off. + With Panel Options › Show Layers Only on, Locate Object is named Locate Layer and highlights the layer that holds the selected object instead of the object's own row, which that mode does not list (help page: https://helpx.adobe.com/illustrator/desktop/manage-layers/create-and-organize-layers/locate-objects-in-the-layers-panel.html). As VectorCraft's own rules, the bottom bar's button and a row's menu are renamed too, the innermost sublayer holding the object is the one highlighted, a layer row locates itself, and the panel opens the layers around it. Locate Object or Locate Layer run again on the row it already highlighted opens the layers around that row again and scrolls to it, VectorCraft's own rule (`locate_layer_highlights_the_layer_holding_the_object` in `crates/engine/src/tests/layers.rs`, `with_show_layers_only_locate_object_becomes_locate_layer` and `a_repeated_locate_reveals_the_row_it_already_highlighted` in `crates/ui-egui/src/panels/layers/tests.rs`). - **Drawing aids:** Smart Guides and snapping (moving, with the Selection, Group Selection or Direct Selection tool, and resizing by the bounding-box handles with the Selection or Free Transform tool, Shift and Alt too: the dragged corner or side lands on the other objects' anchors and centres ("anchor", "center") or lines up with their edges and centres (a line and "align"); with Smart Guides › Spacing Guides, a moved selection that lines up with nothing along an axis lands as far from its neighbour as two other objects of its row or column are apart, or halfway between its two neighbours, the equal gaps marked; with View › Snap to Grid on, a moved selection lands on the grid instead, by whichever of its edges is nearest a gridline on each axis (the center does not snap), #740, #1816; the Rotate, Scale, Shear and Reflect tools drag from the anchor they grab and snap the pointer the same way, so a corner dragged onto another object's anchor scales exactly onto it, #482; anchors dragged with Direct Selection: the one pressed on lands on other anchors, its own path's that stay put among them, on path segments or in line with them, the others following, Shift keeps 45° steps, and with Smart Guides off Snap to Point pulls it onto anchors; the Artboard tool snaps artboards, and their bleed, to other artboards, bleeds and art, the grid or whole pixels while moving, copying and resizing them, and the Transform panel shows and edits the active artboard's X/Y/W/H; drawn points, #506: hovering shows where the press goes, the point lands on the other objects' anchors, centres and paths ("anchor", "center", "path") or lines up with their anchors, edges and centres ("align"), the Pen's on the path being drawn too, near a construction guide through the anchor before it on that guide (Preferences › Smart Guides › Construction Guides and Angles), and with Shift kept to its 45° step or a square's diagonal it slides along that way into line; the targets are gathered once per document state, from the art in the window, and the anchors, centres and lines near the pointer are found by bisection, so hovering never rescans the document), guides dragged out of the rulers (#451: they snap as moved guides do, Shift to the ruler's ticks; with the Artboard tool they are artboard guides, which run across their artboard only and move, copy and delete with it, `guide.add {artboard}`) that the Selection, Direct Selection and Group Selection tools then pick and drag (#414: the selected guides highlight and move together, Alt copies them, Shift snaps the dragged one to the ticks, otherwise it snaps to pixels, the grid or the edges, centres (so the sides' midpoints) and anchors of the art and the artboards, or with Smart Guides off Snap to Point pulls it onto anchors; Shift-clicked they join the selected art, and Shift-added art keeps them, so guides and art are selected together in either order, Delete then deleting both in one step; the arrow keys nudge them, Delete deletes them, dragging one back onto its ruler deletes it, Lock Guides and Hide Guides leave them alone; `guide.list`, `guide.select`, `guide.move` and `guide.remove` reach agents), a right-click on either ruler or the origin box to pick the document's units (the current one checked; `document.setUnits`, one undo step, #528), and Draw Normal / Behind / Inside modes. Smart Guides: a point drawn with the Pen or a shape tool, and an anchor dragged with Direct Selection, snaps to where paths and ruler guides cross, labelled "intersect" (#1658, part of #1602; a moved selection's own anchors don't, except the anchor the Selection tool grabbed it by). A selection the Selection tool grabs by one of its anchors snaps that anchor onto the other objects' paths ("path"), and where a path crosses another path or a ruler guide ("intersect"), in the order Direct Selection uses for a dragged anchor; when the anchor lands on a path, the selection's bounds do not also line up with other objects (#7411). The archived 2007 [user guide](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=55) (page 49) says Smart Guides align the pointer of a moved object to existing paths. Snapping onto paths only when the selection was grabbed by an anchor is VectorCraft's own rule; a selection grabbed anywhere else still lines its bounds up. Tests: `select::tests::a_move_grabbed_by_an_anchor_lands_it_on_another_path`, `a_move_grabbed_by_an_anchor_lands_it_where_paths_cross` and `a_move_grabbed_by_an_anchor_lands_it_where_a_path_crosses_a_ruler_guide`. With Smart Guides › Measurement Labels on, the Line Segment tool labels the segment being drawn with its distance, angle and X and Y offsets (`D`, `Angle`, `dX`, `dY`), and the Pen, Curvature and Smart Pen tools label their rubber band the same way when Enable Rubber Band is on (#2983). A move that Shift keeps level, upright or diagonal stays on that line when it snaps, with the Selection, Group Selection or Direct Selection tool. It slides along the line until the selection lands on the grid or on whole pixels, lines up with the other objects or is spaced evenly with them, or until the line passes an anchor or crosses a ruler guide near the point the selection was grabbed by. A level or upright move snaps along its own axis only. Snap to Last Location: with Smart Guides on and Preferences › Smart Guides › Snap to Last Location on (off by default, VectorCraft's own choice), a selection moved by dragging with the Selection, Group Selection or Direct Selection tool, Shift too, goes back to where the move began while it is within Snapping Tolerance of it, labeled "last location"; an Alt copy is not pulled back onto its original, and with View › Snap to Grid or Snap to Pixel on the move snaps to the grid or to whole pixels instead (`prefs.set` key `snapToLastLocation`). The public [Smart Guides options](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/smart-guides-options.html) page lists the option as snapping objects back to their previous position; the distance, the label, the copy rule and the grid and pixel rule are VectorCraft's own. Tests: `select::tests::snap_to_last_location_puts_a_move_back_where_it_began`, `select::tests::snap_to_pixel_wins_over_snap_to_last_location`, `direct::tests::snap_to_last_location_puts_a_path_moved_by_its_anchor_back`, `direct::tests::snap_to_pixel_wins_over_snap_to_last_location_for_a_path_moved_by_its_anchor`, `tests_prefs::snap_to_last_location_puts_a_dragged_square_back`. @@ -1407,6 +1481,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Artboard click-to-fit (#1227):** a plain click fits the topmost editable object or group to a new artboard, including its stroke like Fit to Selected Art, and makes the new artboard active. Art and its selection stay unchanged; creation is one undo step. Handles, modified clicks, drags, Escape and tool changes retain their meaning. Tested inside an artboard and on the pasteboard (`crates/engine/tests/it/artboard_click.rs`); the public [CS6 Printing Guide](https://helpx.adobe.com/content/dam/help/en/indesign/pdf/CS6_PrintGuide.pdf) documents the object-click gesture. This legacy gesture adds evidence without regrading the 2026 canvas controls. - **Rotated views:** with the view rotated, Fit Artboard in Window, Fit All in Window and the status bar's artboard navigator fit the artboard or the art as the view turns it, and a Zoom tool marquee (Animated Zoom or GPU Performance off) zooms to the area dragged across. Ruler guides on no artboard turn with the view. The canvas draws the selection marquee where the tools select, Show Hidden Characters draws the marks of type partly inside the canvas, the Contextual Task Bar stays under the selection, and the Navigator's red box outlines what the window shows. - **Navigator panel options:** the Navigator panel menu's Panel Options… sets the color the view box is drawn in, from a preset list (VectorCraft's own: Light Red, the default, then the layer colors) or a custom color, and Draw Dashed Lines as Solid Lines, off by default, which draws dashed strokes without their dashes in the panel's thumbnail only (`ui.navigatorPanelOptions`; kept with the UI state; behavior reference: [View artwork](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)). +- **Navigator View Artboard Contents Only:** the Navigator panel menu's View Artboard Contents Only is on by default, and the thumbnail then shows only the art inside the artboards, with art on the pasteboard and in the gaps between artboards left out; turning it off shows the art outside the artboards too (`ui.navigatorPanelOptions {viewArtboardContentsOnly}`; kept with the UI state, read as on when it was never saved; the fit to the artboards' union and the cut at each artboard's edge are VectorCraft's own rules; behavior references: [Navigate and zoom artwork](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/navigate-and-zoom-artwork.html), [View artwork](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)). - **Views:** the status bar's artboard navigator (first, previous, next, last; `view.goToArtboard`) goes to an artboard, fits it and synchronizes the Artboard tool selection when that tool is active; ordinary object selection is preserved. Its four buttons are also commands of their own (`view.firstArtboard`, `view.previousArtboard`, `view.nextArtboard`, `view.lastArtboard`), listed in Edit › Keyboard Shortcuts without a default key, so a user can give them keys such as Page Up and Page Down (#5218). Actual Next-button regressions cover keyboard/Properties deletion and Undo in `chrome.rs`. Fit Artboard in Window and Actual Size show the navigator's artboard. The Artboards panel highlights that active artboard: clicking a row makes it active (the Artboard tool's too, while it is chosen) as does clicking an artboard with the Artboard tool, double-clicking its number also fits it in the window and double-clicking its name renames it. Duplicate Artboards, or a row dragged onto New Artboard, copies the artboard with its art (#446). Escape leaves Presentation Mode, `view.screenMode` from it goes back to Normal Screen Mode, and the screen mode isn't saved with the preferences: the app always starts in Normal Screen Mode with its menus and panels (#472). View › Pixel Preview shows the art as the document pixels it rasterizes to, one per point and hard-edged when magnified, turning with a rotated view (it used to draw the smooth vectors, with only the pixel grid over them). In Outline view a template layer keeps drawing in Preview, dimmed, so a picture placed to be traced stays visible under the outlines (#1505, fixes #1486). Outline view draws on a white canvas in every interface brightness and Canvas Color, pasteboard included, with the artboards as their edges and no paper (VectorCraft's own rule), so the black outlines of art on the pasteboard show. In Presentation Mode, → and ← go to the next and the previous artboard, and a click anywhere goes to the next one, as the status bar navigator's Next and Previous do (`view.goToArtboard`): on the last artboard → and a click leave the view as it is, and so does ← on the first. The arrow keys do not move the selection there, and the tool does not receive a click, so a click selects and draws nothing (behavior reference: [View artwork](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)). Full Screen Mode and Presentation Mode put the window full screen, covering the taskbar and the window's frame, and Normal Screen Mode or Full Screen Mode with Menu Bar puts it back (#4365); a window the user made full screen stays so. @@ -1473,6 +1548,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Export 3D Object (Asset Export's menu): an object with Extrude & Bevel, Revolve, Inflate or Rotate becomes a 3D asset whose Format is USDA (the default), USDZ, glTF or OBJ, and Export writes each of its solids as a mesh with a material in its paint's color (`assets.add3D`, `assets.set3DFormat`, `assets.export3D`; [export 3D vector artwork](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/export-3d-vector-artwork.html)). - Export 3D Object builds each Extrude & Bevel (both kinds) and Inflate solid once: the same build gives the faces that count toward the object's limit and the faces of its mesh, and the meshes match those of a separate build bit for bit. Tests `mesh::tests::a_meshed_solid_is_built_once`, `an_extruded_solid_and_its_mesh_match_the_two_built_apart`, `inflated_solids_and_their_meshes_match_the_two_built_apart`, `solids::tests_mesh::one_build_exports_the_meshes_built_apart`, `a_stroke_past_the_limits_is_left_out_of_the_export`. - Export 3D Object writes the graphics mapped onto a plane or onto Extrude & Bevel's front and back caps as a PNG texture of each face, the face's color with its graphics drawn flat and unlit over it, on a mesh of that face with texture coordinates, in all four formats (glTF embeds it, USDZ packs it after the layer, OBJ and USDA write `-texture-1.png` beside them; `assets.export3D` `textureSize`, 128 to 4096 pixels, default 1024, VectorCraft's own values; [the help page](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/map-artwork-on-3d-objects.html)). Graphics on Revolve's side, materials and lighting are not exported. Tests `a_caps_mesh_corners_go_back_to_the_art_they_were_made_from`, `a_mesh_carries_its_caps_graphics_flat_in_the_arts_plane`, `each_format_carries_a_textured_part_with_its_coordinates_and_picture`, `export_3d_paints_mapped_graphics_on_their_caps_in_every_format`. + - The 3D and Materials panel works out whether Export 3D Object is available once for each document revision and reuses it on later frames. The button shows the same state. With 200,000 paths selected, working it out on every frame took a median 61.6 ms of thread CPU time per frame in a release build on Linux (57.1 ms with a path of a compound path with Extrude & Bevel selected last); the first frame after a change still takes about as long, and later frames take about 2 ns (`panels::three_d::tests::export_3d_object_state_kept_for_a_revision_equals_a_fresh_one`, `export_3d_object_state_is_worked_out_once_per_revision`, `export_3d_object_state_timing`). - Checking an Extrude & Bevel (both kinds) or Inflate effect builds each solid the effect draws once, about the bounds the effect draws it about; a shape with no fill still has its profile built on its own. Tests `solids::tests::the_check_builds_each_drawn_solid_once`, `the_check_builds_the_profile_of_a_shape_with_no_fill`. - Initial live Revolve (#605, #846): a portable geometry and shading crate (`three-d`), editable path and compound profiles, compact options with artboard rotation and light gizmos, SVG/PDF vector output and Expand Appearance that can trim covered faces. Open ends have continuous caps by default, shading is smooth with one to ten colored lights, and intersecting surfaces' visibility is approximate ([revolve.md](revolve.md)). - Revolve takes graphics on its swept side, shaded with the object's light ([the archived reference, page 185](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=185)). By VectorCraft's own rule a graphic wraps around the axis at its own size at every distance from it, narrows toward the silhouette, follows the profile along its length and is hidden where the side faces away (`threeD.mapGraphic`; `revolve::tests_graphics`, `tests::side_faces_lie_on_the_unrolled_surface_and_caps_do_not`, `map_graphic_puts_a_graphic_on_the_side_of_a_revolve`). @@ -1516,6 +1592,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Manual kerning on inline graphics:** a manual kerning value on an inline graphic's character spaces it from the next character in reading order by the same distance as on a letter of its run's size, in left-to-right, right-to-left and vertical type; Auto and Optical kerning still apply no font pairs to it. This is VectorCraft's own rule. Test: `manual_kerning_on_an_inline_graphic_spaces_it_like_a_letter`. - **Inline graphics in symbol art follow their symbols:** when a symbol changes, type with an inline graphic of it is laid out again wherever the type is: in the layers, in the art of other symbols, graph designs and pattern tiles, and in opacity masks. A symbol's type is laid out before the type that shows that symbol inline, so a symbol whose art holds an inline graphic, its instances and the inline graphics that show it take its new size. Opening and reverting a document and Refresh Font List resolve them in the same order. An inline graphic of a symbol whose art shows that symbol inline, directly or through other symbols, is an empty slot. This is VectorCraft's own rule. Tests: `inline_graphics_in_symbol_art_follow_their_symbol`, `inline_graphics_in_masks_and_pattern_tiles_follow_their_symbol`, `symbols_are_resolved_after_the_symbols_they_show_inline`, `a_symbol_that_shows_itself_inline_is_an_empty_slot` in `crates/engine/src/tests/inline.rs`. - **Inline graphics of symbols that hold other symbols:** an inline graphic of a symbol whose art holds an instance of another symbol is sized by that symbol's own art, placed by the instance, and follows it when that symbol changes. A symbol's type is laid out after the type in the art of the symbols its instances show. An inline graphic of a symbol whose art reaches that symbol through an instance and an inline graphic is an empty slot; an instance that does not size the art, such as one a clipping path hides, does not count. An instance of a missing symbol, of a symbol without art, of a symbol that holds an instance of itself, or of a symbol whose art nests symbols 32 deep is measured by the 20 × 20 square. This is VectorCraft's own rule. Tests: `an_inline_graphic_follows_the_art_of_a_symbol_nested_in_its_symbol`, `symbols_are_resolved_after_the_symbols_their_instances_show`, `a_symbol_that_shows_itself_through_an_instance_is_an_empty_slot` in `crates/engine/src/tests/inline.rs`; `a_symbol_nested_in_symbol_art_is_measured_by_its_own_art`, `nested_instances_without_art_of_their_own_are_measured_by_the_square`, `only_instances_that_size_a_symbols_art_make_it_depend_on_their_symbol` in `crates/doc/src/inline.rs`. +- **Inline graphics after an edit, in large documents:** after an edit, a document with symbols checks its type's inline graphics again only in the layer trees that differ from the document the last check left, as long as the symbols, graph designs, pattern tiles and the symbols' natural sizes and 9-slice guides are unchanged and each symbol the type shows measures as before; otherwise every tree is checked, as before. The document and the texts laid out again are the same either way. Measured in one process (thread CPU time, median of 7 runs, 100 groups, three symbols, one inline graphic, one rectangle moved): the check went from 1.0 ms to under 0.05 ms at 50,000 rectangles and from 5.7 ms to under 0.05 ms at 200,000, and a whole `object.move` from 1.55 ms to 0.7 ms and from 11.9 ms to 6.2 ms; the rest of an edit still walks the document. Tests: `refreshing_only_changed_trees_matches_the_full_pass` in `crates/engine/src/tests/inline.rs`; `a_pass_after_an_edit_checks_only_the_trees_the_edit_changed`, `changed_symbols_or_symbol_sizes_take_the_full_pass` in `crates/doc/src/inline.rs`; timings: `inline_refresh_perf` (ignored). - **Recent font pickers (#3515):** The shared Character, Properties, Glyphs and Find Font family picker lists recently applied families first, once each, in most-recent order and limited by Preferences › Type › Number of Recent Fonts. Search and filters apply to both sections; unavailable families are omitted. Section headings cannot be selected or previewed. Confirmed character-range font edits update the same saved history; previews and failed edits do not. Requirement: [issue #3515](https://github.com/storytold/vectorcraft/issues/3515). - **Show samples on white (a VectorCraft addition):** Preferences › Type › Show samples on white (`fontSamplesOnWhite`, off by default) draws each family's sample in every font menu, and in Type → Font in the in-window menu bar, in dark type on a white area in every interface brightness. A highlighted row's color shows above and below the white area, and the names and the rest of the menu keep the interface's colors. The checkbox is dimmed while Enable in-menu font previews is off. Tests: `crates/ui-egui/src/tests/font_menu.rs`, `crates/ui-egui/src/font_menu/tests.rs`, `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Show Similar Fonts: families without numbers come last:** in a font menu's Show Similar Fonts list and `text.similarFonts`, a family whose faces give none of the numbers the list compares (PANOSE, weight, width, heights, average width, italic angle) in common with the chosen family comes after every family of its script group that shares one, instead of right after the chosen family as an exact match. This is VectorCraft's own rule; the help page (https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/font-options-overview.html) describes the list only as fonts that look like the chosen one. Regression tests: `a_family_without_numbers_comes_after_the_measured_ones` and `likeness_is_a_distance` in `crates/text/src/tests/similar.rs`. @@ -1523,8 +1600,9 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Find Font: Escape and the replacement search:** Escape with the Replace With Font From or Find In list open closes only the list. The dialog stays open with its choices and its search, also while Escape is held down, and the next press of Escape closes it. Done, Enter, Escape, and Find in Folder… once the Missing Fonts dialog opens, each forget the replacement search, so the next Find Font starts with an empty one; with no folder picked, Find Font stays open with its search. This is VectorCraft's own rule: a dropdown or popover open in a dialog closes before the dialog. Tests: `crates/ui-egui/src/find_font.rs`. - **Select Text by Font: scope (a VectorCraft addition, #5529):** `select.font` takes `scope`: `"document"` (the default, as before), `{artboards: [index, …]}` or `{layers: [id, …]}` (sublayers included). On an artboard means what All on Active Artboard takes (the bounds overlap it or the center is on it; one shared test, `select::on_artboard`); hidden and locked text stays out as before; a symbol instance counts where the instance is. Type › Find Font…'s Find In dropdown passes the active artboard or the selected layers (else the current layer). Tests: `crates/engine/src/cmd/fonts.rs`, `crates/ui-egui/src/find_font.rs`, `crates/engine/tests/command_sweep.rs`. - **Find Font: type in opacity masks and pattern swatches:** Type › Find Font…'s Document list (`text.fonts`), Find (`select.font`), Change and Change All (`text.replaceFont`), Replace Missing Fonts (`addon.cleanup.replaceFonts`), the Missing Fonts dialog (`text.missingFonts`), Document Info's Fonts and Font Details for the whole document (`document.info`), File › Package and the export warning about fonts that aren't available include the type in opacity masks (on objects and layers, disabled masks and masks inside mask, symbol or pattern art included) and in the art of pattern swatches, also a swatch that nothing paints with. A pattern's type is listed and changed once, however many objects the pattern paints. Find selects the objects whose mask holds the font, the text whose inline graphics draw a symbol whose art uses it, and the objects painted with a pattern whose art uses it by a visible fill or stroke above 0% opacity (VectorCraft's own rule; a layer's mask and a swatch that nothing paints with select nothing); Change and Change All leave the type in the mask of a hidden or locked object in its font and count it in `skipped`, and Change does the same with the type of a pattern that only hidden or locked selected objects paint with. The help page (https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/find-and-replace-fonts.html) says the Document list holds all the fonts the document uses. Tests: `crates/engine/src/cmd/fonts.rs`, `crates/engine/src/cmd/addons/cleanup/text/tests.rs`, `crates/engine/src/cmd/docinfo.rs`. +- **Find Font works out the document's fonts once per version:** while Type › Find Font… is open, its Document list (`text.fonts`) and whether it shows Find in Folder… (the document misses a font) are worked out once for each version of the document's content and of the available fonts, and later frames reuse them. The list and the button are the same as before; an edit, an undo, another document in front, entering or leaving pattern editing, a composite font defined or taken out, and fonts added or scanned again give them anew. With 2,000 point-type objects of 50 characters each, set in five installed faces and a missing family, working them out took a median 1.53 ms of thread CPU time per frame in a release build on Linux; the first frame after a change still takes about as long, and later frames take about 10 ns. With 20 such objects it took 58 µs per frame. Tests: `find_font::tests::the_font_list_is_worked_out_once_per_document_version`, `an_edit_works_the_font_list_out_again`, `other_available_fonts_work_the_font_list_out_again`, `the_font_list_follows_the_document_in_front`; the timing probe is `find_font::tests::find_font_list_timing`. - **Mouse wheel over the font family field (#5253):** In the Character and Properties panels and the Control bar, turning the mouse wheel over the closed font family field applies the next family to the selected type (the previous one when turned up), keeping the style when the family has it, else its closest. Each notch is one undo step; leaving the field or Escape keeps the family, and Undo takes it back. The steps use the font menu's order at the first turn and keep it until the pointer leaves the field or the text selection changes, so recent-font updates do not reshuffle later turns. That order follows the font filters every font menu shares (one chosen in the Glyphs panel's menu or a dialog's applies too) but ignores its search text, puts recent families first, and stops at the first and last family. A turn with a modifier key is left to the panel and the canvas. Behavior reference: the [Illustrator CS6 reference](https://help.adobe.com/archive/en/illustrator/cs6/illustrator_reference.pdf#page=10) describes editing hovered dropdown controls with the mouse wheel; [Find and apply fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/find-and-apply-fonts.html) names the family field's places. Applying it to the font field, the order, the ends and the undo steps are VectorCraft's own rules. Tests: `crates/ui-egui/src/tests/font_menu.rs`, `crates/ui-egui/src/font_menu/tests.rs`, `crates/ui-egui/tests/font_wheel.rs`. -- **Type:** Character size, leading, baseline shift and horizontal-scale controls account for object/group transforms (#1034): exact document-point sizes, mixed-value display and keyboard increments, range edits, resettable horizontal stretch, undo/redo and native save/reopen (`tests_typescale`, Character panel tests). Point size is the transformed em-height axis, independent of glyph ink bounds; affine rotation, reflection and shear are retained. Group scaling still scales text; preserving font sizes is a separate enhancement. Behaviour reference: [Transform text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/transform-text.html) (public documentation). Text Wrap, Type on a Path effects (Rainbow/Skew/3D Ribbon/Stair Step/Gravity) and Options (Flip, Align to Path, Spacing; OK keeps the type where it is), type on a path's start, centre and end brackets (Selection and Direct Selection drag them to set where the type runs, slide it along its path and, across the path, flip it: #429), Character and Paragraph Styles (override-preserving redefine), paragraph attributes per paragraph (alignment, indents, spacing, hyphenation, hanging punctuation, tab stops, paragraph style, direction, mojikumi and leading model; the Paragraph, Tabs and Paragraph Styles panels act on the paragraphs the Type tool's selection or caret touches, Return continues the paragraph's style, threads and SVG keep them), Area Type Options (rows/columns/inset/first baseline, Text Flow by rows or by columns (#4978), vertical Align Top/Center/Bottom/Justify per row/column, reflowing non-rectangular frames and text wrap), threaded text across any closed shapes, Fit Headline, the Every-line Composer for justified and ragged text (paragraph-wide breaks for an even rag, Single-line per object from the Paragraph panel menu or `text.setFormat {composer}`). Area type resizes like Illustrator's type areas: a bounding-box handle drag (Selection tool) or Area Type Options Width/Height size the frame and the text reflows at its size (threads too); Direct Selection drags a frame corner or edge (`text.reshapeArea`), and an anchor of the path of type on a path outside perspective, the type reflowing along it (`text.reshapePath`, #3980). Point type still scales. Auto Size: the frame height follows the text after every edit, in the same undo step (rectangular frames of horizontal type in one row; columns get the least height that holds them; a height set by hand or threading turns it off), and the "Auto Size New Area Type" preference gives it to new area type. Shrink Text to Fit (beyond Illustrator): overflowing area type scales its sizes, leading and baseline shifts down by the largest factor (in 0.1 pt steps of the first run, down to a minimum percentage) that fits, at layout time so every export sees it. `text.areaOptions` and `document.inspect` report overflow and the shrink factor. The Selection tool shows the type widget beside selected type's bounding box (hollow on point type, filled on area type); double-clicking it converts between them (Type › Convert To Area Type / Convert To Point Type), keeping the text and its styles in place. Variable fonts list every named instance as a style of their family (Figtree Light to Black and their italics, Bahnschrift, Segoe UI Variable), and the instance chosen is shaped, drawn, outlined and measured at its axis settings; PDF and SVG embed it as that instance. The Character panel's Variable Font sliders set each axis (see Fonts). Beyond Illustrator: inline graphics (`text.insertInline`, Type ▸ Insert Inline Symbol) set a document symbol in a run of type as one character that flows, wraps and justifies like a glyph (InDesign-style inline objects, e.g. mana symbols in card rules text): sized to a multiple of the font size, centred on the cap height, opening up tall lines, following Redefine Symbol; a character of its run's size for Character Alignment and Top-to-Top leading, placed by the bidi reordering in right-to-left text (a neutral U+FFFC); drawn on the canvas, kept as live text plus a `` in SVG and as vector art in PDF; Backspace removes it whole. Hebrew and Arabic are laid out right to left with the Unicode bidirectional algorithm (embedded Latin and numbers keep their direction, lines put in visual order after wrapping) in point, area and path type, with caret, selection and arrow keys in visual order; each paragraph's direction comes from its first strong character unless Paragraph Direction sets it (Paragraph panel with Show Indic Options, `text.setFormat {direction}`), and new type aligns to the start of its direction. SVG export outlines right-to-left text. Arabic typefaces: builds made with a craft-fonts checkout that holds its Arabic families (Noto Sans Arabic, the Arabic fallback, plus Cairo, Tajawal, Almarai, IBM Plex Sans Arabic, Noto Kufi Arabic, Amiri, Alexandria, Fustat, Reem Kufi, Aref Ruqaa and Gulzar once craft-fonts adds them, storytold/craft-fonts#11; releases get them when their craft-fonts pin moves) list them in the font menus on desktop; the web build fetches them from beside the wasm (Noto Sans Arabic before start, so Arabic never shows as boxes, the rest in the background). Font Size and Leading are combo boxes in the Character and Properties panels (Font Size in the Control bar too, beside the Character link, font family and style): type, step with ↑/↓ or the spinner, scrub the label, or pick a preset (6–72 pt, shown in the type unit; Leading also Auto), each pick one undo step; Kerning and Tracking list -100…200; a size, leading, kerning or tracking the selected text doesn't share shows blank (#458). Type › Bold and Italic (beyond Illustrator, as page layout apps have them; Cmd+Shift+B / Cmd+Shift+I while the Type tool edits text) switch the selected type to its family's own Bold or Italic face and back, keeping its width (a Narrow face stays Narrow); a family without that face says so (#724). The commands that make or restyle type (and the MCP `add_text` tool) say in their result when area type does not fit its frame, and `add_text` takes Auto Size and Shrink Text to Fit (#1500, fixes #1471). Cmd+Shift+C (Align center) works on Windows and Linux too (#1940). A double-click on area type's bottom middle handle turns on Auto Size (#1940). Print and Print Preview warn about the area type and type on a path that prints without the text that doesn't fit, and give their ids. A tab stop in the Tabs panel drags from where the press landed, a stop just added included (#1487, fixes #1458). Area type in a non-rectangular shape moves a word too wide for the top lines down to the first line that holds it instead of breaking it (#1617, fixes #1615). Stylistic sets (ss01–ss20), stylistic and titling alternates, proportional and lining figures, and superscript and subscript glyphs can be turned on as OpenType features of a character style (`text.setStyle {features}`), and the OpenType panel keeps them (#1611, fixes #1607). Escape while typing ends the edit, keeps the type selected and switches back to the tool that was active before type editing began (kept while clicks move editing to other text), or to the Selection tool when there was none (#1802, #1686, #1656). Select › Same matches type on its characters' fill and stroke (#1746, #1737). `text.create`, `text.createInPath` and the MCP `add_text` tool take `justify`, so point type can be centred on or end at its point (#1752, #1748). New type, made with the Type tools, `text.create`, `text.createInPath` or by pasting plain text, starts in [Normal Character Style] as every character does by default ([Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html)), so it is filled black, or with the fill a redefined [Normal Character Style] has (editing that style is how new type's defaults change: [FAQs on fonts in Illustrator](https://helpx.adobe.com/illustrator/using/fonts-faq.html), "How to change the default font"), not with the current fill left from the last shape; a `color` given to the command still wins (#7975). Tests: `new_type_takes_the_normal_character_style_fill_not_the_current_fill`, `pasted_plain_text_takes_the_normal_character_style_fill`. +- **Type:** Character size, leading, baseline shift and horizontal-scale controls account for object/group transforms (#1034): exact document-point sizes, mixed-value display and keyboard increments, range edits, resettable horizontal stretch, undo/redo and native save/reopen (`tests_typescale`, Character panel tests). Point size is the transformed em-height axis, independent of glyph ink bounds; affine rotation, reflection and shear are retained. Group scaling still scales text; preserving font sizes is a separate enhancement. Behaviour reference: [Transform text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/transform-text.html) (public documentation). Text Wrap, Type on a Path effects (Rainbow/Skew/3D Ribbon/Stair Step/Gravity) and Options (Flip, Align to Path, Spacing; OK keeps the type where it is), type on a path's start, centre and end brackets (Selection and Direct Selection drag them to set where the type runs, slide it along its path and, across the path, flip it: #429), Character and Paragraph Styles (override-preserving redefine), paragraph attributes per paragraph (alignment, indents, spacing, hyphenation, hanging punctuation, tab stops, paragraph style, direction, mojikumi and leading model; the Paragraph, Tabs and Paragraph Styles panels act on the paragraphs the Type tool's selection or caret touches, Return continues the paragraph's style, threads and SVG keep them), Area Type Options (rows/columns/inset/first baseline, Text Flow by rows or by columns (#4978), vertical Align Top/Center/Bottom/Justify per row/column, reflowing non-rectangular frames and text wrap), threaded text across any closed shapes, Fit Headline, the Every-line Composer for justified and ragged text (paragraph-wide breaks for an even rag, Single-line per object from the Paragraph panel menu or `text.setFormat {composer}`). Area type resizes like Illustrator's type areas: a bounding-box handle drag (Selection tool) or Area Type Options Width/Height size the frame and the text reflows at its size (threads too); Direct Selection drags a frame corner or edge (`text.reshapeArea`), and an anchor of the path of type on a path outside perspective, the type reflowing along it (`text.reshapePath`, #3980). Point type still scales. Auto Size: the frame height follows the text after every edit, in the same undo step (rectangular frames of horizontal type in one row; columns get the least height that holds them; a height set by hand or threading turns it off), and the "Auto Size New Area Type" preference gives it to new area type. Shrink Text to Fit (beyond Illustrator): overflowing area type scales its sizes, leading and baseline shifts down by the largest factor (in 0.1 pt steps of the first run, down to a minimum percentage) that fits, at layout time so every export sees it. `text.areaOptions` and `document.inspect` report overflow and the shrink factor. The Selection tool shows the type widget beside selected type's bounding box (hollow on point type, filled on area type); double-clicking it converts between them (Type › Convert To Area Type / Convert To Point Type), keeping the text and its styles in place. Variable fonts list every named instance as a style of their family (Figtree Light to Black and their italics, Bahnschrift, Segoe UI Variable), and the instance chosen is shaped, drawn, outlined and measured at its axis settings; PDF and SVG embed it as that instance. The Character panel's Variable Font sliders set each axis (see Fonts). Beyond Illustrator: inline graphics (`text.insertInline`, Type ▸ Insert Inline Symbol) set a document symbol in a run of type as one character that flows, wraps and justifies like a glyph (InDesign-style inline objects, e.g. mana symbols in card rules text): sized to a multiple of the font size, centred on the cap height, opening up tall lines, following Redefine Symbol; a character of its run's size for Character Alignment and Top-to-Top leading, placed by the bidi reordering in right-to-left text (a neutral U+FFFC); drawn on the canvas, kept as live text plus a `` in SVG and as vector art in PDF; Backspace removes it whole. Hebrew and Arabic are laid out right to left with the Unicode bidirectional algorithm (embedded Latin and numbers keep their direction, lines put in visual order after wrapping) in point, area and path type, with caret, selection and arrow keys in visual order; each paragraph's direction comes from its first strong character unless Paragraph Direction sets it (Paragraph panel with Show Indic Options, `text.setFormat {direction}`), and new type aligns to the start of its direction. SVG export outlines right-to-left text. Arabic typefaces: builds made with a craft-fonts checkout that holds its Arabic families (Noto Sans Arabic, the Arabic fallback, plus Cairo, Tajawal, Almarai, IBM Plex Sans Arabic, Noto Kufi Arabic, Amiri, Alexandria, Fustat, Reem Kufi, Aref Ruqaa and Gulzar once craft-fonts adds them, storytold/craft-fonts#11; releases get them when their craft-fonts pin moves) list them in the font menus on desktop; the web build fetches them from beside the wasm (Noto Sans Arabic before start, so Arabic never shows as boxes, the rest in the background). Font Size and Leading are combo boxes in the Character and Properties panels (Font Size in the Control bar too, beside the Character link, font family and style): type, step with ↑/↓ or the spinner, scrub the label, or pick a preset (6–72 pt, shown in the type unit; Leading also Auto), each pick one undo step; Kerning and Tracking list -100…200; a size, leading, kerning or tracking the selected text doesn't share shows blank (#458). Type › Bold and Italic (beyond Illustrator, as page layout apps have them; Cmd+Shift+B / Cmd+Shift+I while the Type tool edits text) switch the selected type to its family's own Bold or Italic face and back, keeping its width (a Narrow face stays Narrow); a family without that face says so (#724). The commands that make or restyle type (and the MCP `add_text` tool) say in their result when area type does not fit its frame, and `add_text` takes Auto Size and Shrink Text to Fit (#1500, fixes #1471). Cmd+Shift+C (Align center) works on Windows and Linux too (#1940). A double-click on area type's bottom middle handle turns on Auto Size (#1940). Print and Print Preview warn about the area type and type on a path that prints without the text that doesn't fit, and give their ids. A tab stop in the Tabs panel drags from where the press landed, a stop just added included (#1487, fixes #1458). Area type in a non-rectangular shape moves a word too wide for the top lines down to the first line that holds it instead of breaking it (#1617, fixes #1615). Stylistic sets (ss01–ss20), stylistic and titling alternates, proportional and lining figures, and superscript and subscript glyphs can be turned on as OpenType features of a character style (`text.setStyle {features}`), and the OpenType panel keeps them (#1611, fixes #1607). Escape while typing ends the edit, keeps the type selected and switches back to the tool that was active before type editing began (kept while clicks move editing to other text), or to the Selection tool when there was none (#1802, #1686, #1656). Select › Same matches type on its characters' fill and stroke (#1746, #1737). `text.create`, `text.createInPath` and the MCP `add_text` tool take `justify`, so point type can be centred on or end at its point (#1752, #1748). New type, made with the Type tools, `text.create`, `text.createInPath` or by pasting plain text, starts in [Normal Character Style] as every character does by default ([Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html)), so it is filled black, or with the fill a redefined [Normal Character Style] has (editing that style is how new type's defaults change: [FAQs on fonts in Illustrator](https://helpx.adobe.com/illustrator/using/fonts-faq.html), "How to change the default font"), not with the current fill left from the last shape; a `color` given to the command still wins (#7975). It also takes the font, style, size and other character attributes of a redefined [Normal Character Style], so redefining that style in a New Document profile sets the default font of the profile's documents ([Change the default font](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/change-the-default-font-in-illustrator.html)); a `font`, `style` or `size` given to the command still wins. Tests: `new_type_takes_the_normal_character_style_fill_not_the_current_fill`, `pasted_plain_text_takes_the_normal_character_style_fill`, `tests::newdoc::a_profiles_normal_character_style_is_the_default_font`. The Character panel menu's Show Font Height Options shows a Set Font Height Reference dropdown under Font Size (`text.setFormat` or `text.setRangeStyle` `{fontHeightReference}`). Each reference shows an icon of the height it measures before its name, in the open list and in the closed field (#6304): a frame around a letter for Em Box, a bar from the baseline to the top of a capital for Cap Height and of a lowercase x for x-Height, and a frame inset in the em square for ICF Box. With Em Box, the default, the font size is the size of the em square; with Cap Height, x-Height or ICF Box, the characters are set at the em size at which the font's OS/2 cap height, its x height or the height of its ideographic character face equals the font size. With a font that has no such value, or one outside 0.1 to 2 em, the size measures the em box. SVG, PDF and legacy `.ai` export and the CSS Properties rules write the em size the characters are drawn at, and DXF export writes 0.7 times that em size as each TEXT entity's height (group 40, the height of its capitals). Behavior reference: [Vary font height](https://web.archive.org/web/20251118174722/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/vary-font-height.html). The Every-line Composer composes a paragraph whose characters differ in line metrics (type size, font, leading or vertical scale, or an inline graphic taller than the text) in area type of any shape, rows, columns and text wrap included. In a frame that is not a rectangle, or with text wrap, each line it tries is measured where the lines above it put it, across the line's own height, so a taller line gets the room of the narrower part of the frame, or of the span beside a wrap object, that it reaches. When the frame cannot hold all of such a paragraph, the lines it holds are still composed with the whole paragraph, the lines past the frame's end measured as wide as the last line the frame holds (VectorCraft's own rule); they overflow or go on in the next threaded frame, which composes them again. Such a paragraph is broken with the Single-line Composer when the frame has no room for its first line or when the search passes VectorCraft's own limits. The Single-line Composer measures a line's room across the height of its tallest character too: a line that takes in a taller character is placed again and broken again in the room there. Behavior reference: [the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/set-hyphenation-and-line-breaks.html), and for text that flows on between threaded objects, [the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/add-manage-text/create-text-threads-between-objects.html). A text wrap object's Offset may be negative as well as positive ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=307)). A negative Offset (to -1000 pt) shrinks the wrap object by that distance, measured from each edge itself and from the edges of its holes, so lines beside it, above it and below it run that far into it, and an object narrower than twice the distance no longer moves text aside. With Invert Wrap, a negative Offset keeps the text that far inside the object. These are VectorCraft's own rules for the shape of the shrunk object. Text Wrap Options, `object.textWrap.make` and `object.textWrap.options` and the MCP `text_wrap` tool take the negative value, and layout uses it (`crates/text/src/layout/region.rs` tests, `cmd::textwrap::tests::text_wrap_options_negative_offset_reflows_and_round_trips`). @@ -1543,12 +1621,14 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With a Type tool and exactly one character selected, the canvas shows that character's alternate glyphs in a row beside it, and a click on one replaces the character's glyph, as [Replace characters with alternate glyphs](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/replace-characters-with-alternate-glyphs.html) describes ("Replace a character with on-canvas alternate glyphs"). The row shows at most five alternates, and an arrow at its end opens the Glyphs panel on Alternates for Current Selection when the character has more, as the [reference manual](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=479) describes. A click runs the command the panel's double-click runs, as one undo step, so a letter of an Arabic word keeps the word joined. These rules are VectorCraft's own: the row leaves out the glyph the character is drawn with and puts the default glyph first for a character drawn with an alternate; it stands under a character of horizontal type and on the right of a character of vertical type, or on the other side when the canvas ends there or the Contextual Task Bar is there; Preferences › Type › Show Character Alternates (`showCharacterAlternates`, on by default) turns it off. Tests: `canvas::alternates_bar::tests`, `tests::prefs::show_character_alternates_preference_is_on_by_default_and_saved`. With an OpenType font in the Glyphs panel, the Show menu and the panel menu list the font's glyph categories after Alternates for Current Selection, and choosing one restricts the grid to the glyphs of that kind, as the [Glyphs panel overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/glyphs-panel-overview.html) describes. The categories are Ligatures, Swash, Stylistic Alternates, each stylistic set by the font's name for it (else Set N), Small Caps, Ornaments, Fractions and Figures, each listed only when the font's `GSUB` features give it glyphs; which features make up each category and their order are VectorCraft's own. A font without the chosen category shows Entire Font. `text.glyphCategories` lists them for agents. Tests: `fontdb::gsub::tests` in the text crate, `panels::glyphs::tests::the_show_menu_lists_the_fonts_opentype_categories`, `tests::fontlist::glyph_categories_list_the_glyphs_of_each_kind_of_feature`. The OpenType panel's Stylistic Sets menu offers `ss01`–`ss20` sets present in the selected text's font, using the font's custom labels when available and numbered labels otherwise. Sets can be combined and deselected individually. With mixed fonts, the menu shows the first selected character's font's sets and applies the feature tag to all selected text; a font without that set draws unchanged. The mixed-font rule is a VectorCraft design choice. Behavior reference: [Add stylistic sets to selected text](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/add-stylistic-sets-to-selected-text.html) and the [OpenType specification](https://learn.microsoft.com/en-us/typography/opentype/spec/features_pt). + The OpenType panel menu has a Stylistic Sets submenu after Reset OpenType Features, with the same sets, labels and checks as the panel's Stylistic Sets button; a set chosen there turns on or off for the characters the panel acts on in one undo step, keeping their other features, and the submenu is disabled with no text selected or when the font offers no sets. The 2019 user guide ([the help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf)) has stylistic sets chosen from the OpenType panel menu. The submenu's place in the menu is VectorCraft's own. Tests: `panels::opentype::tests::the_panel_menu_stylistic_sets_submenu_turns_sets_on_and_off`. With Show East Asian Options on, the OpenType panel menu has H or V Style and Roman Italics, as [Format East Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html) describes. H or V Style sets the feature tag `hkna`, which draws kana with the forms the font makes for horizontal type, and with `vkna` for vertical type in vertical type; Roman Italics sets `ital`, the font's italic forms of half-width alphanumerics ([OpenType feature list](https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist)). Each is checked when every selected character has it and turns it on or off for all of them in one undo step; character styles carry both in OpenType Features. Tests: `panels::opentype::tests::kana_style_and_roman_italics_turn_on_and_off`, `features::tests::kana_style_and_roman_italics_are_kept_and_shaped`. `text.setStyle {stroke, strokeWidth}` sets the character stroke's color and weight of the selected type or of a range of its characters (the weight in document points, as `stroke.set` sets it), in the same undo step as the command's other changes. Tests: `tests::textedit::set_style_sets_the_character_stroke`. - **Paragraph alignment:** the shared Paragraph/Properties alignment row leaves every button unselected when the paragraphs it acts on differ. Auto resolves per paragraph; choosing an alignment uses the existing command. Headless paragraph_mixed_alignment_* regressions exercise mixed → Center → Undo, caret/uniform states, Unicode range boundaries, Auto/direction, split runs and grouped text. These regressions and full integration CI pass. Original captures confirm mixed → Center → Undo in the existing alignment-button layout. The [public Paragraph panel guide](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/paragraph-panel-overview.html) lists the seven controls, but does not specify mixed-state rendering. Other paragraph fields remain outside this change; scores and hours unchanged. For Auto Size area type in columns, the bisection for the frame's height runs on the lines of the one-column layout, and its result is checked with at most two layouts of the columns. When the text wraps around objects or does not fit the one-column layout, or when the check fails, the columns are laid out at every step of the bisection, as before. Typing at the start of a story of 50,000 characters in 2 columns took 1,670 ms a keystroke and now takes 292 ms (release build, `auto_height_in_columns_typing_timing`). Exports to PDF, EPS, SVG, EMF, WMF and the raster formats warn about the area type and type on a path that they draw without the text that doesn't fit, and give their ids, as Print and Print Preview do. On a shaped area type frame, Inset Spacing keeps text that far from the frame's edge, holes included, measured from the edge itself rather than along the line; the archived help treats the inset as the space an area type object leaves between its text and the path that bounds it (, ). A rectangular frame keeps its inset from each side as before, and a column's inner edges keep it once. An edge that two contours of the frame share lies inside the frame, so text runs across it with no inset on either side, and a negative text wrap offset does not shrink a wrap object beside such an edge. Tests: `layout::region::inset_on_a_shaped_frame_is_measured_from_its_sloped_edge`, `inset_keeps_text_clear_of_a_hole_s_sloped_edges`, `inset_applies_once_at_a_column_s_edge_and_at_the_frame_s_edge`, `inset_is_not_kept_beside_an_edge_two_contours_share`, `negative_wrap_offset_does_not_shrink_beside_an_edge_two_contours_share`. + Area Type Options › First Baseline offers Em Box Height (`text.areaOptions {firstBaseline: "emBoxHeight"}`), which the help page describes as using the font's em box height (): the top of the first line's ideographic em box, the largest on a line of several sizes, touches the top of the type area inside the inset, in each row/column cell and in vertical type from the frame's right edge. The em box is the one Top-to-Top leading uses (VectorCraft's own measure: an ideograph's cell in the font's vertical metrics, else 0.88 em above the baseline), and Min is the least distance, as with the other kinds. Native files and `.ai` files save and open it; a `.ai` First Baseline kind VectorCraft does not read keeps today's fallback. Tests: `em_box_height_puts_the_first_lines_em_box_top_at_the_type_area_top`, `em_box_height_sets_a_vertical_frames_first_column_at_its_em_box`, `area_options_set_the_em_box_height_first_baseline`, `every_first_baseline_kind_comes_back_with_its_minimum`. An edit copies a thread's story only when it changes one of the thread's frames: with a story of 50,000 characters threaded through 8 frames with a style change at every word, moving another object took 7.8 ms and now takes 0.013 ms, and a frame of a drag took 7.2 ms and now takes 0.012 ms (release build, `threaded_story_edit_timing`). When a story flows through threaded area type, each frame is measured with the whole paragraphs of the story that it needs and a few more, not with the whole rest of the story, and it keeps the same text as before. A story of 1,500 one-line paragraphs (55,892 bytes) through 40 frames was laid out over 2,126,762 bytes of text while the frames were measured, and is now laid out over 21,035 (`thread::tests::many_frames_measure_about_the_text_they_take`). Area type with its lines aligned to the center, the bottom or justified vertically, and type on a path whose first paragraph is aligned Left, Justify Left, Justify All or Auto, are measured the same way: the same story through 40 area frames aligned to the center was laid out over 2,126,762 bytes and is now laid out over 21,035, through 40 paths aligned Left over 2,135,202 bytes and now over 20,583, and through 40 paths aligned Justify All over 2,135,202 bytes and now over 20,583 (same test). Shrink Text to Fit, Dynamic Text, Optical Margin Alignment and Roman Hanging Punctuation on a path, a path aligned to the center or the right, horizontal type on a path whose first paragraph is set right to left or with right-to-left text in the rest of the story, and a frame whose share ends in the story's last paragraph are still measured with the whole rest. A paragraph that continues from one threaded frame into the next has its first-line indent and bullet or number in the frame where it starts; in the next frame its first line starts where its wrapped lines start. In frames that are no longer threaded, copies of a frame and point type converted from one, the first paragraph has its indent and bullet or number again. @@ -1597,6 +1677,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Paragraph panel's Numbered List button, Type › Bullets and Numbering › Apply Numbers and the context menu's Apply Numbers (`text.setFormat {list, number}`, `type.applyNumbers`) make paragraphs a numbered list with the documented presets (1, A, a, I, i, 01, 001, and None, which turns the list off; [Bullets and numbering](https://web.archive.org/web/20250807202418/https://helpx.adobe.com/illustrator/using/bullets-numbering.html), [Create bulleted or numbered lists](https://web.archive.org/web/20260417034638/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/create-bulleted-or-numbered-lists.html)): each paragraph starts with its number and a period, counted through the list paragraphs of the story and its threaded frames, with the text and indents as in a bulleted list; letters go on from Z to AA, and roman numerals go on from III to IV, an empty paragraph is not numbered, and a paragraph in no list starts the count again at 1. More Options in the Bullets and Numbered List presets (`ui.bulletsAndNumbering`) opens the Bullets and Numbering dialog ([Create bulleted or numbered lists](https://web.archive.org/web/20260417034638/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/create-bulleted-or-numbered-lists.html)): a Bullets tab and a Numbers tab with the presets, and the Position group's Alignment, Left Indent and First Line Indent, shown on the type while the dialog is open; OK applies them with `text.setFormat` (Alignment is its `listAlign`) as one undo step, and Cancel puts the type back. Alignment Left starts the marker at the first line's start, and Right ends it where the text starts. The cited page does not say where the marker sits for each choice, so these meanings are VectorCraft's own rule. Paragraph styles and the native file keep the alignment. Tab and Shift+Tab with the caret at the start of a list paragraph (`text.setFormat {listLevel}`), and the Bullets and Numbering dialog's Level field (OK sends it as `listLevel`), move the paragraph down and up the list's nine levels ([Create bulleted or numbered lists](https://web.archive.org/web/20260417034638/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/create-bulleted-or-numbered-lists.html), [Bullets and numbering](https://web.archive.org/web/20250807202418/https://helpx.adobe.com/illustrator/using/bullets-numbering.html)): each level past the first sets the paragraph 18 pt further in, each level counts its own numbers from 1, and a paragraph back at a shallower level goes on with that level's count, through threaded frames too. Elsewhere Tab inserts a tab as before; one Undo takes a level change back, and paragraph styles and the native file keep the level. Convert to Text writes each level's numbers and keeps a deeper paragraph's indent. + VectorCraft's own (the help pages above show no such control; requested in #2473): the Bullets and Numbering dialog's Start at box (`text.setFormat {startNumber}`, and `restartNumbering` for 1) gives a numbered paragraph a number from 1 to 999999999, and the numbered paragraphs after it at its level count on from it, through threaded frames too; off, the paragraphs count on from the one before. One Undo takes it back, the native file keeps it, a paragraph made with Return and a paragraph style do not take it, and Convert to Text and the exports write the numbers shown. Type › Bullets and Numbering › Convert to Text (`type.convertListToText`, `text.convertListToText`) makes the bullets and numbers of the list paragraphs editable characters of their text ([Create bulleted or numbered lists](https://web.archive.org/web/20260417034638/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/create-bulleted-or-numbered-lists.html), [December 2022 release notes](https://web.archive.org/web/20260203094741/https://helpx.adobe.com/illustrator/using/whats-new/2023-1.html)): each marker becomes its characters and a tab at the start of its paragraph, in the marker's font, size and color, the list is turned off, and a left tab stop at the left indent keeps the text after the tab where it started; threaded type keeps the numbers its story counted. While no type is being edited, a press with Shift held makes new type with the horizontal or vertical counterpart of the Type, Area Type or Type on a Path tool chosen, and a press with Alt (Option) held makes it with Type on a Path in place of Area Type or the reverse, in the chosen tool's writing direction; with both keys held, both switch ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)). The pointer shows the tool the press acts as, and the tool chosen stays selected. The Type tool starts a list from the characters [Create bulleted or numbered lists](https://web.archive.org/web/20260417034638/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/create-bulleted-or-numbered-lists.html) names (`text.startList`): a space typed on its own after `1.`, `1)`, `A.` or `A)` at the start of a paragraph in no list makes the paragraph a numbered list in 1, 2, 3 or A, B, C, and a space typed after `*`, `+`, `#` or `>` makes it a bulleted list with the filled dot, the hollow circle, the filled square or the dash (a VectorCraft choice: the page does not say which bullet each character gives). The typed characters are removed, and one Undo puts them back as text with no list. The same characters later in a paragraph, and pasted list characters, start nothing. @@ -1616,6 +1697,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Burasagari ([the help page](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)) leaves a right-to-left paragraph's comma or full stop inside its line, which then ends at a break where it fits with the mark, and in a left-to-right line with right-to-left text and a tab it hangs a mark only when the mark is drawn at the line's right end and the rest of the line fits as drawn; otherwise the line ends at the latest break that fits as drawn. Both are VectorCraft's own rules (`crates/text/src/layout/wrapping_tests.rs`, `crates/text/src/tests/hang.rs`). Scores and estimates are unchanged. 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`). + On the web, Korean and Hindi interface text draws with real glyphs: a web build made with craft-fonts fetches NanumGothic for Hangul (about 2 MB) or Noto Sans Devanagari (about 280 KB) only when the interface language or the interface's own text (a layer or file name, the language picker) needs that script. The frame after the face arrives adds it to the interface fonts, and the frame after that draws the characters painted before it with that face. Sessions in other languages do not download them at startup. After a failed fetch the next try comes about 30 seconds later, and the wait doubles after each further failure, for at most five tries (`crates/text/web-fonts.txt`, `apps/vectorcraft-web/src/fonts.rs`, `apps/vectorcraft-web/src/demand.rs`, `crates/ui-egui/src/ui_fonts.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 (in `GSUB`, or for the width forms `GSUB` or `GPOS`) is disabled. A form other than the default takes away a character's glyph choice, and with a width form Proportional Metrics' `palt` is not applied and the font's pair kerning is off. `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`, `typecmd::area_tests::a_glyph_form_takes_away_the_characters_glyph_choice`, `features::tests::width_forms_turn_off_proportional_metrics`, `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. @@ -1724,6 +1806,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Window › Blend opens the Blend panel: Make, the selected blend's Spacing and Orientation (with no blend selected, the options new blends start with), Reverse Front to Back, Reverse Spine, Replace Spine, Expand and Release, each running its Object › Blend command. Make is dimmed until two or more objects are selected. Spacing and Orientation are dimmed until a blend or two or more objects are selected, and the other buttons are dimmed until a blend is selected. The Blend panel's Create Spine menu (Auto, Always, Never; `object.blend.createSpine`) sets whether new blends get a spine, from the Blend tool, Make and `object.blend.make` alike ([Blend panel overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blend-panel-overview.html)). Auto and Always give every new blend a straight spine, as before; Never makes blends without one, which keep their steps on the straight lines between the keys, have Type and Ramp dimmed, refuse Reverse Spine and spine edits, release without a spine path, and get a spine from Replace Spine. The setting is kept with the preferences and leaves blends already made as they are; Auto as the starting value and keeping the setting across sessions are VectorCraft's own rules. Builds on #5177 by adambelis. Evidence: `tests::blendopts::{create_spine_sets_whether_new_blends_get_a_spine, a_blend_without_a_spine_has_none_to_edit_reverse_ease_or_release, whether_a_blend_has_a_spine_is_saved_and_old_blends_have_one}` and `panels::tests_blend::create_spine_sets_what_new_blends_get_whatever_is_selected`. Blend Options on several selected blends (the Blend Options dialog, the Blend panel's Type, Ramp and Shift, and `object.blend.options`) sets only the values given or set in the dialog, and each blend keeps its own spacing, orientation, type, ramp and shift for the rest instead of taking the first blend's; a spacing mode given without a count keeps the count of a blend already in that mode. `object.blend.options {id}` edits that blend alone; a hidden or locked blend, an object that is not a blend, a value out of range and an unknown orientation are errors that change nothing, and a call that changes nothing records no undo step. A drag of the panel's Ramp or Shift slider previews on the canvas and records one undo step on release, and Type, Ramp and Reverse Spine are dimmed while a selected blend, or the blend of a key selected with Direct Selection, has no spine. Builds on #8022 by ruchirguitar. Evidence: `tests::blendopts::{options_on_several_blends_set_only_the_values_given, options_with_an_id_edit_that_blend_alone, options_that_change_nothing_or_are_refused_record_no_undo_step}`, `dialogs::blend_options::tests::on_several_blends_ok_sets_only_the_fields_changed` and `panels::tests_blend::{a_ramp_or_shift_drag_is_one_undo_step, ramp_and_shift_edit_every_selected_blend_and_keep_their_other_options, ramp_is_dimmed_while_a_selected_blend_has_no_spine, ramp_and_reverse_spine_are_dimmed_while_a_selected_key_belongs_to_a_blend_with_no_spine}`. + The Blend panel, the Object › Blend, Envelope Distort and Gradient Mesh menu items and their commands find each selected object's nearest blend, envelope or mesh by reading the object's place in the tree once, instead of looking up every ancestor by id, and the checks of whether one is selected stop at the first one found. The results, their order and the errors are the same. With Select All of 102,200 objects (100,000 rectangles, 2,000 blends and 200 envelopes in 10 layers), a release build took a median of 16.5 ms of thread CPU time for the Blend check before and 0.5 ms after, and 18.4 ms before and 8.2 ms after to list the selected blends. Evidence: `cmd::live::selected_tests` and `tests::lookups::nearest_finder_*`. With the Blend tool, Escape drops the object clicked first and stops the next click adding to the blend just made, so the next click picks a new first object; the document and the selection stay as they are. Regression tests: `escape_drops_the_blend_tools_first_pick` in `meshblend.rs` and `tests/blendopts.rs`. Objects on Path (#2545): a click with the Objects on Path tool (in Edit Toolbar's Modify section and the Blend tool's flyout; Object › Objects on Path › Attach and the context menu with two or more objects selected choose it) attaches the selected objects to the path clicked, open or closed, in an Objects on Path group with the path at its bottom. The objects go along the path column by column from left to right, spread evenly from its first anchor (the last one sits on the end of an open path), each turned to the path at its attachment point; Pivot and Rotate set where each one attaches and how far it tilts (`object.objectsOnPath.attach`, `object.objectsOnPath.options`), and with Objects on Path groups selected the Properties panel's Objects on Path Options section shows them as a nine-point Pivot grid and a Rotate field with common angles, each change one undo step for every selected group. Editing the path moves the objects, an object moved on its own goes back, objects moved into or out of the group in the Layers panel join or leave the path, and Object › Objects on Path › Expand leaves a plain group. The group saves and reopens live and exports as plain art. With one Objects on Path group selected, the Selection and Objects on Path tools show the Rotate All widget beside its first object: dragging it turns every object about its attachment point by the angle the pointer turns, adding it to the group's Rotate in one undo step, in 15° steps with Shift ([Objects on Path](https://helpx.adobe.com/illustrator/using/objects-on-path.html)). Detach is in its own entry below. Objects on Path Space widget: with one Objects on Path group of two or more objects selected, the Selection and Objects on Path tools show a square handle beyond its last object; dragging it along the path, round its bends, sets the distance between the objects' attachment points in one undo step, the first object staying where it is, and with Alt (Option on macOS) the objects spread from both ends toward the center; the distance shows next to the pointer during the drag, in the document's units ([Rearrange and edit objects on a path](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/rearrange-and-edit-objects-on-a-path.html), [Objects on Path](https://helpx.adobe.com/illustrator/using/objects-on-path.html)). The group keeps the distance (`object.objectsOnPath.options {spacing, start}`) through Pivot and Rotate changes, path edits, copies, saving and reopening, and scales it with the group; by default (`"auto"`) the objects are spread evenly as before. Evidence: `objects_on_path::tests::{space_sets_the_distance_between_the_stops, space_on_a_closed_path_wraps_at_the_first_anchor_and_stops_short_of_the_first_object}` in `crates/doc`, `tests::objects_on_path::space_sets_the_distance_between_the_objects_in_one_undo_step` in `crates/engine`, `objects_on_path::tests::dragging_the_space_widget_spaces_the_objects_from_the_first_one` in `crates/tools`. @@ -1737,16 +1820,18 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Swatches:** names follow the colour model and are unique; Swatch Options (process/spot, Global, Gray/RGB/HSB/CMYK/Web, live preview); editing a global or spot swatch recolours every linked fill, stroke and text run in one undo step; multi-select and delete with confirmation; New Swatch and New Color Group dialogs (a group from the selected artwork's colours); swatches in colour groups convert, separate and count like any other. The Swatches panel selects ranges and whole groups, has a find field, and drags swatches to reorder, regroup or paint art; Add Used Colors, Select All Unused, Merge, Ungroup and Sort by Kind; a CMYK document keeps applied colours in CMYK. Swatch libraries: nine generated colour libraries, seven gradient libraries (among them Organic Fades, soft perceptually mixed multi-stop fades that thin out to transparent, and Holographic, seven opaque linear foils of narrow pastel and pearl bands and seven radial glows that fade out to a clear edge) and three pattern libraries (Geometric Patterns; Grit Textures with eight seamless grain, speckle, stipple, scratch and fleck tiles; and Optical Effects with eight of VectorCraft's own seamless wave, ring, warped-check, stripe, chevron and lens tiles; their swatches bring their patterns) in a library panel, saved as `.vcswatches`, `.gpl`, swatch exchange (`.ase`) or CSS, and loaded from `.vcswatches`, `.gpl` and `.ase` files (`.ase` both ways: RGB, CMYK, Lab and Gray; global, spot and process; groups) and from color books (`.acb`, read only: the RGB, CMYK or Lab colors of a book such as a Pantone book a user owns, named with its prefix and suffix, spot unless it says process, #831); `swatch.library.copyToUser` copies a loaded library into the User Defined folder without replacing a file, and a file with the same extension and bytes as a User Defined library opens as that library. Tints of global and spot colours ("Name 40%") stay linked and separate as a percentage of their plate. Spot colours can be defined in Lab (Spot Colors options). A built-in [Registration] swatch prints on every plate. Right-clicking a swatch in either list or thumbnail view selects it without applying paint and offers Swatch Options…, Duplicate Swatch and Delete Swatch for that item. None, [Registration] and missing swatches disable these actions. Existing active-item multiselection is retained; actions still target only the clicked item. Evidence: `panels::swatches::tests::context_menu` harness tests cover all five views, selection, dialog dispatch, duplicate/delete and Undo. All 39 Swatches tests pass; the regression fails with the menu hooks removed. Rendered headless list and thumbnail menus were inspected, and a fresh local deep CodeRabbit review reported zero findings. Full workspace CI passed on Linux/WSL on the merged branch (all 13 gates), including the test-helper correction for the upstream compile error tracked in #7727; native Windows full CI has two unchanged engine-test failures. Scores and estimates unchanged. Validation on 2026-11-15: native Windows formatting, workspace Clippy and all 39 focused Swatches tests passed. Windows full CI stopped at unchanged engine tests `tests::package::a_confined_package_names_files_outside_the_read_root_by_name` (slash-sensitive report assertion) and `tests::plugins::plugin_storage_behind_a_link_is_left_alone` (storage-link setup returned AlreadyExists). Both cases pass in the Linux/WSL full CI run, which passed all 13 gates. No engine or CI workflow changes are included. + The panel's Delete Swatch and Swatch Options (footer buttons and panel menu), New Color Group and Save Swatch Library treat only None and [Registration] as reserved, so a user swatch or color group whose name starts with `[` can be deleted, edited, grouped and saved; selected names the document no longer holds are left out (`panels::swatches::tests::bracketed_user_swatches_and_groups_can_be_deleted_and_edited`). Dragging swatches onto Delete Swatch deletes them ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=136), Replace, merge, or delete swatches section, lists this drag as one of the ways to delete the selected swatches): a swatch or color group dragged from the Swatches panel, in any view, and released on the Delete Swatch button is deleted through `swatch.delete`, even while nothing was selected and the button is disabled for clicks. A swatch that is part of the selection carries the other selected swatches of its kind with it. VectorCraft's own rules: the drop asks first as a plain click does, and Alt does not skip the question; Cancel keeps everything, and OK deletes them in one undo step; None and [Registration] are never taken; the button is enabled while swatches are selected or while a swatch or group of the active document is being dragged, and it is outlined only while such a swatch or group is held over it, so a paint from another panel, art and a swatch dragged from another document delete nothing. Tests: `panels::swatches::tests::swatches_dropped_on_delete_swatch_are_deleted_after_asking`, `delete_swatch_ignores_other_drags`. Editing, renaming, deleting or merging a global swatch also changes the colors linked to it in graph designs, the art of brushes and the tile that pattern editing's Cancel puts back, in the same undo step as the rest of the art; Default Swatches with replace unlinks them there too. A swatch step in `command.batch` (Delete, Swatch Options, Merge, Edit Color Group) changes the fill and stroke for new art as the command run on its own does, so art drawn later in the batch or after it takes the same paint; a batch that fails, and a canceled batch preview, put back the paints it started with, and a canceled Swatch Options preview leaves them as they were. These swatch commands also change the fills and strokes of the appearance new art takes, and Undo and Redo of the command or the batch put the paints for new art back with the swatches. Spot Colors options (`swatch.spotOptions`) and Default Swatches with replace (`swatch.resetDefaults {replace: true}`) as `command.batch` steps also change the fill and stroke for new art as each command run on its own does: a fill or stroke linked to a Lab spot swatch keeps its link and tint and takes the Lab values or their CMYK equivalent, and one linked to a swatch the replace removes keeps its color and loses the link. Evidence: `swatch_steps_in_a_batch_change_the_new_art_paints_as_commands_do`, `spot_colors_options_in_a_batch_change_the_new_art_paints_as_the_command_does`, `default_swatches_replace_in_a_batch_unlinks_the_new_art_paints_as_the_command_does`, `undo_and_redo_of_a_swatch_edit_put_back_the_new_art_paints`, `swatch_edits_reach_the_paints_of_the_new_art_template`, `a_failed_batch_puts_back_the_new_art_paints_a_swatch_step_changed` and `canceling_a_swatch_options_preview_keeps_the_new_art_paints` in `crates/engine/src/tests/swatches.rs`. Add Used Colors (`swatch.addUsedColors`) and Select All Unused (`swatch.unused`) look colors, swatch names, links, tints and gradients up in hash sets instead of searching every swatch and color for each color or linked paint (New Color Group from artwork too), and New Swatch with several colors (`swatch.new`), New Color Group (`swatch.newGroup`) and Edit Color Group (`swatch.editGroup`) name their new swatches from one set of the names already taken. The new swatches keep their names, order and links, and Select All Unused lists the same swatches. Evidence: `add_used_colors_adds_each_new_color_once_with_free_names`, `add_used_colors_global_links_every_paint_of_a_new_color`, `unused_matches_links_tints_colors_gradients_and_patterns_exactly`, `new_swatches_from_colors_are_numbered_after_names_already_taken`, `new_color_group_numbers_its_colors_after_the_group_and_its_moved_swatches`, `new_color_group_from_artwork_lists_each_color_once_with_free_names` and `edit_color_group_numbers_extra_colors_after_the_names_it_keeps` in `crates/engine/src/tests/swatchcmds.rs`; `free_swatch_names_match_naming_each_swatch_as_it_is_added` and `free_swatch_names_match_new_swatch_names_as_swatches_are_added` in `crates/doc/src/swatches.rs`. + When Add Used Colors and New Color Group link the selected art's paints to global swatches, they look each selected object's groups and layer up in a set of the selected ids instead of searching the whole selection for each one, so linking 20,000 selected rectangles takes 16 ms of CPU time instead of 128 ms (`cargo run --release -p vectorcraft-engine --example link_colors_bench`). The same paints are linked, in the same order. Evidence: `mapping_within_ids_matches_a_search_of_the_ids` in `crates/doc/src/swatches.rs`. - **Colorized images (#1466):** a fill color applied to a selected grayscale or 1-bit image (`paint.setFill`) colorizes it with black, white, a process color or a spot color, and refuses a process color when the image has an alpha channel ([Convert color modes](https://web.archive.org/web/20251220223850/https://helpx.adobe.com/illustrator/desktop/manage-colors/select-and-adjust-colors/convert-color-modes.html), "Colorize Grayscale or 1-bit images"); black and white are accepted there too. The canvas draws each pixel in the color as far as the pixel is dark, with white pixels transparent; PDF export writes the image in the color (a spot color as its ink, Registration in every ink) with the image as its soft mask; Separations Preview and printed separations show it on its color's plates; native files keep the color. SVG writes the fill color through a coverage mask (or a colorized PNG in Tiny 1.2); EPS writes binary coverage as an image mask in the color's ink, and a grayscale image as ink samples scaled by coverage, with white pixels left out at Level 3 and gray midtones written over white. The prompt for deleting several swatches and groups uses the interface language's plural form for the count. Evidence: `deleting_several_swatches_uses_each_count_form` in `crates/ui-egui/src/panels/swatches/tests.rs`. - **Colorized images (#1466):** a fill color applied to a selected grayscale or 1-bit image (`paint.setFill`) colorizes it with black, white, a process color or a spot color, and refuses a process color when the image has an alpha channel ([Convert color modes](https://web.archive.org/web/20251220223850/https://helpx.adobe.com/illustrator/desktop/manage-colors/select-and-adjust-colors/convert-color-modes.html), "Colorize Grayscale or 1-bit images"); black and white are accepted there too. The canvas draws each pixel in the color as far as the pixel is dark, with white pixels transparent; PDF export writes the image in the color (a spot color as its ink, Registration in every ink) with the image as its soft mask; Separations Preview and printed separations show it on its color's plates; native files keep the color. EPS and SVG write the image's own pixels. - **Missing library files:** a persistent swatch or graphic style library panel whose file is gone at startup reopens and stays in the preferences, showing the file's path with Locate Library… (`ui.libraryPanel.locate`), which reads the file from where it is now into the same panel. - **Swatch library and Recolor Artwork parameters:** the `swatch.library.*` commands, `swatch.resetDefaults`, the graphic style library save, load and add, the `recolor.*` commands and `color.harmony`'s `limitTo` refuse parameters of the wrong form, such as `names: "Grays"`, `limitTo: 5` or `includeImages: "false"`. Errors name the parameter, except that a `limitTo` that is not a string, such as `5`, gets an unknown-library error. A `null` counts as left out except for `recolor.apply`'s `model`, which must be a string when given. - - **Color Wheel panel (part of #978):** Window › Color Wheel shows the Fill and Stroke proxy beside a hue ring around a square with saturation across and brightness up. It edits what the Color panel's sliders edit (the active proxy's color, the selected gradient stop or freeform point) through the same paint commands, and a drag is one undo step. Alt paints the other proxy, and Shift steps the ring by 45°. A pick goes from display sRGB into the working RGB space; an RGB, CMYK or Lab color keeps its model, and a Gray color or a tint of a global swatch becomes a process color in the document's color mode. A click gives the ring or the square the keyboard focus, and the arrow keys then step the color; both report their names and values to screen readers, and the Color Picker's color field takes the same keys. Scores and estimates are unchanged. + - **Color Wheel panel (part of #978):** Window › Color Wheel shows the Fill and Stroke proxy beside a hue ring around a square with saturation across and brightness up. It edits what the Color panel's sliders edit (the active proxy's color, the selected gradient stop or freeform point) through the same paint commands, and a drag is one undo step. Alt paints the other proxy, and Shift steps the ring by 45°. A pick goes from display sRGB into the working RGB space; an RGB, CMYK or Lab color keeps its model, and a Gray color or a tint of a global swatch becomes a process color in the document's color mode. A click gives the ring or the square the keyboard focus, and the arrow keys then step the color; both report their names and values to screen readers, and the Color Picker's color field takes the same keys. The panel menu's Box View puts a box in the wheel's place: a color field with a channel strip at its right for Hue, Saturation, Brightness, Red, Green or Blue (Box Channel), on the Color Picker's axes, kept with the preferences (`ui.colorWheel`); the strip and the Color Picker's channel slider take the arrow keys after a click. Scores and estimates are unchanged. - **Colour:** a Color Picker (colour field, H/S/B/R/G/B channel slider, HSB/RGB/Lab/CMYK fields, hex, web-only snapping, out-of-gamut correction); the Color panel shows a selected colour in its own model and, with nothing selected, the new-art defaults in the mode picked last, which it keeps between sessions; Alt-click paints the other proxy; proxies look through groups and show "?" for mixed paint; Invert, Complement, Apply Last Color (`,`) and Apply Last Gradient (`.`) keep the colour model; every paint command feeds the recent colours. The Color Guide has 21 harmony rules, Steps and Variation options and Limit to Library. Adjust Color Balance (its Global mode shifts tints) and Saturate preview live; Edit Colors and Recolor also reach meshes, images and patterns. Recolor Artwork has colour reduction, five recolour methods, presets, Limit to Library, a colour-wheel Edit tab and Edit Color Group; a local Color Themes panel saves five-colour themes. Fill/Stroke chips open swatch and mixer popovers (the Properties panel has the Control bar's Fill and Stroke chips, Stroke link and weight spinner, with nothing selected too), panels have Illustrator's Window menu keys (Align Shift+F7, Transform Shift+F8, Pathfinder Cmd+Shift+F9, Layers F7, Character Cmd+T…; every panel can be given one in Edit › Keyboard Shortcuts), and Eyedropper Options pick up and apply chosen attributes (Alt and Shift+Alt, image pixels). An ICC CMYK profile converts straight into the RGB working space (not through sRGB, so a wider space such as Wide Gamut RGB keeps colours sRGB can't hold) with the colour settings' black-point compensation, on the canvas and in RGB exports alike (the built-in Generic CMYK compensates both ways, so RGB black separated to a rich black displays as black again). Fills and strokes can overprint (Attributes panel, Overprint Black options), and CMYK documents blend in inks on screen, in PDF and when flattening. Document Color Mode converts the art, symbols, pattern tiles and swatches through the colour settings: Gray stays Gray, RGB grays separate into light grays in cyan, magenta and yellow only, darker four-color grays and a rich black, or go on the black plate only with `grays: "black"` (also for `document.open {colorMode}`). Plain Comma and Period, and also Shift+Comma and Shift+Period, apply the last solid color and the last gradient to the active Fill or Stroke proxy in VectorCraft ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html), "Select color fill mode" and "Select gradient fill mode"). Recent Colors keeps the last 30 solid colors applied, newest first and each once, and the list stays the same when another document is opened or made active; a 31st color drops the oldest ([Select colors using the Color panel](https://helpx.adobe.com/illustrator/desktop/manage-colors/select-and-adjust-colors/select-colors-using-the-color-panel.html)). The list lasts for the session. In the Color and Swatches panels the chips wrap onto further rows when the panel is too narrow for one row (`paint.recent`). Tests: `recent_colors_keep_thirty_colors_across_documents` in `crates/engine/src/tests/paintproxy.rs`, `all_thirty_recent_colors_wrap_into_a_narrow_panel` in `crates/ui-egui/src/panels/color/tests.rs`. @@ -1758,6 +1843,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A double-click right of an RGB field switches the Color panel's R, G and B between percent and 0 to 255 ([Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html), Color panel). In VectorCraft the color does not change, Web Safe RGB and the hex field stay in 0 to 255, and the panel keeps the choice between sessions (`ui.colorPanel {rgbPercent}`); the color mixer of the Fill and Stroke chips and the gradient stop dialog follow the same setting. Toggle RGB Percent (`ui.colorRgbPercent`) in the command palette and Keyboard Shortcuts switches the units from the keyboard. Tests: `rgb_percent_switches_the_rgb_fields_between_percent_and_0_to_255`, `rgb_percent_does_not_switch_while_the_rows_are_disabled`, `rgb_percent_comes_back_after_a_restart` and `toggle_rgb_percent_switches_the_units_from_the_keyboard` in `crates/ui-egui/src/panels/color/tests.rs`. View › Proof Setup › Color blindness – Tritanopia-type turns Proof Colors on and proofs the canvas with the tritanopia simulation of Brettel, Viénot and Mollon (1997). The Separations Preview panel's Proof Setup list offers the same target (`view.proofSetup {target: "tritanopia"}`). Grays keep their value. The Separations Preview panel's Gamut Check button reports one color outside the CMYK gamut in the singular and more in the plural, in English and in each language's plural forms (`gamut_check_status_takes_the_plural_form` in `crates/ui-egui/src/i18n/tests.rs`). + The "?" on the Fill and Stroke proxies finds a few selected objects along their cached places in the document instead of walking every object; a large selection takes one walk, as before. The proxies show the same paints and question marks as before, also for an id that a damaged file repeats. On a document of 50,000 rectangles in 500 groups on 5 layers with one object selected, the check takes under 5 µs of CPU time instead of a median of 995 µs in a release build on Linux, so the gain shows on large documents (seven alternating runs, `cargo test --release -p vectorcraft-engine --lib proxy_mixed_timing -- --ignored --nocapture`). - **Document Color Mode outside the layers:** File › Document Color Mode (in one undo step) and `document.open {colorMode}` also convert the colors of graph designs, graphic styles, opacity-mask art, the tile that pattern editing's Cancel puts back and the art of brushes (with a Hue Shift brush's key color); a tint of a global swatch there becomes the converted swatch's color at its tint, as in the art. - **Segments dragged onto the grid (#3835):** with View › Snap to Grid (or Snap to Pixel) on, a straight segment dragged with Direct Selection or Group Selection lands its anchors on the grid, the box round them putting an edge on a gridline on each axis as a moved object's does (Shift keeps the move on its line), instead of the point it was pressed at landing on an intersection and leaving both anchors off the grid; a dragged anchor still lands on an intersection itself, and drawn points and resize handles already snapped (`direct::tests::a_dragged_segment_lands_its_anchors_on_the_grid`). - **Spinner arrows in the shadow and glow dialogs (#5367, #5368):** Drop Shadow's Opacity, X Offset, Y Offset, Blur and Darkness and the Outer and Inner Glow's Opacity and Blur have up and down arrows beside the field, as the other number fields with arrows do: a click steps by one (a unit for distances; Shift ×10, Ctrl/Cmd ÷10), holding repeats, Opacity and Darkness stop at 0 and 100 % and Blur at 0 (`dialogs::effect` test `drop_shadow_and_outer_glow_fields_have_spinner_arrows`). @@ -1768,6 +1854,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Recolor Artwork Add Color and Remove Color tools:** under the display buttons beside the Edit tab's wheel, the Add Color tool adds the color clicked on either wheel to the color group, and the Remove Color tool removes the color whose marker is clicked; a color bar's right-click menu has Remove Color, and the base color can't be removed ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html), [Edit swatch groups using the color wheel](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/edit-color-groups-using-the-color-wheel.html)). An added color is a new row with no current colors and `added: true`; unlike a row made with New Row, it adds its new color to a rewritten color group, after the group's other colors. VectorCraft's own rules: an added color takes the base color's brightness, and with art or a group a removed color's row stays with its current colors and no new color, so that art keeps its colors and the group's swatch at that place is removed. `wheelTool` (`add`, `remove`) is the dialog field. Tests: `the_add_color_tool_adds_a_row_with_no_current_colors`, `an_added_color_joins_the_color_group`, `the_remove_color_tool_removes_a_marker_but_not_the_base_colors` and `a_color_bars_menu_removes_its_color` in `crates/ui-egui/src/tests/recolor.rs`, `apply_params_give_the_group_added_colors_and_keep_its_other_colors` in `crates/ui-egui/src/dialogs/recolor.rs`, and `an_added_empty_row_gives_the_group_its_color_after_the_others` in `crates/engine/src/tests/recolor.rs`. Scores and estimates unchanged. - **Recolor Artwork brightness and hue wheel:** a button under the Edit tab's wheel tools switches the wheel between hue with saturation and hue with brightness; a marker's angle sets its hue, and its distance from the center sets the component the wheel shows ([Recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/recolor-options-overview.html), [archived help, Edit colors](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=144)). VectorCraft's own rules: brightness runs from black at the center to full at the edge, the segmented wheel's five rings become brightness steps, the slider under the wheel edits the component the wheel leaves out (Saturation on the brightness wheel), Add Color takes the hue and brightness clicked at the base color's saturation, the choice holds for both wheels while the dialog is open and the button is off for the color bars, and each opening shows hue and saturation. `wheelAxes` (`hueSaturation`, `hueBrightness`) is the dialog field. Tests: `the_brightness_and_hue_wheel_swaps_the_wheel_axis_and_the_slider`, `a_marker_on_the_brightness_wheel_sets_hue_and_brightness`, `the_add_color_tool_on_the_brightness_wheel_adds_the_brightness_clicked` and `the_segmented_brightness_wheel_has_24_hues_by_5_brightnesses` in `crates/ui-egui/src/tests/recolor.rs`, and `an_added_color_on_the_brightness_wheel_takes_the_base_colors_saturation` in `crates/ui-egui/src/dialogs/recolor.rs`. Scores and estimates unchanged. - **Recolor Artwork Find:** the Assign tab's Find button finds the colors of the selected rows in the art ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html)): while it is on, their art shows as the preview shows it and the rest of the selected art shows dimmed, until a second click ([archived help, Recolor Artwork](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=149)). VectorCraft's own rules: a dimmed color is a 25% tint of its current color (or the nearest lighter tint when that one is a color a selected row lists), a color a selected row also lists is not dimmed, and Find records no undo step. `findColors` is the dialog field. Tests: `find_dims_the_colors_of_the_rows_not_selected` and `find_shows_the_selected_rows_art_and_dims_the_rest` in `crates/ui-egui/src/dialogs/recolor.rs`. Scores and estimates unchanged. + - **Recolor Artwork color groups list:** a list on the right of the dialog shows the document's color groups, and the Show Color Groups button beside the tabs shows or hides it. A click on a group makes it the group being edited, and the rows take its colors. Save Changes rewrites the selected group with the new colors, New Color Group saves them as a new group, and Delete removes the selected group; the Swatches panel shows each change ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html)). VectorCraft's own rules: when the art has colors of the group, Save Changes and OK keep the group's swatches in order, and a swatch no row lists keeps its color; an excluded row leaves its swatch its own color; after a save with art, the rows' new colors take the Global Adjust, which goes back to 0%. `group`, `groupStorage` and `groupAction` are the dialog fields. Tests: `the_color_groups_list_selects_saves_and_deletes_groups`, `a_group_picked_in_the_list_recolors_the_art` and the `saving_a_group_` tests in `crates/ui-egui/src/dialogs/recolor.rs`, and `edit_color_group_with_its_own_colors_records_no_undo_step` and `edit_color_group_with_its_own_color_keys_keeps_the_colors` in `crates/engine/src/tests/swatchcmds.rs`. - **Recolor Artwork New Row:** the Assign tab's New Row button adds a row with no current colors, so current colors can be moved into it and take its new color ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html), [Assign new colors to selected artworks](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/assign-new-colors-to-selected-artwork.html)). VectorCraft's own rules: the row goes above the first selected row (at the top when none is selected) with that row's new color and becomes the selection, and Merge with it as the first selected row moves the other rows' colors into it. The button needs selected art. An empty row recolors nothing, does not count toward Colors, adds no library swatch and gives a rewritten color group no color. While it is empty, Save All Colors and a new color group saved from colors alone leave its new color out, the Edit tab's wheel, bars and chips do not show it and its sliders edit the base color instead, the harmony rules and linked moves leave its new color as it is, and the Color Theme Picker gives it no color. Tests: `a_new_row_goes_above_the_selection_and_takes_merged_colors`, `an_empty_row_gives_the_group_no_color`, `an_empty_row_gives_a_new_group_no_color`, `an_empty_row_takes_no_harmony_or_wheel_color`, `theme_picks_leave_an_empty_row_out`, `save_all_colors_leaves_an_empty_row_out` and `colors_merged_into_a_new_row_take_its_new_color` in `crates/ui-egui/src/dialogs/recolor.rs`, `an_empty_row_recolors_nothing` and `an_empty_row_adds_no_swatch_and_no_group_color` in `crates/engine/src/tests/recolor.rs`. - **Edit Colors parameters:** `edit.colors.saturate` needs a number `intensity`, the value from -100% to 100% that Saturate takes ([Adjusting colors](https://web.archive.org/web/20230128232631/https://helpx.adobe.com/illustrator/using/adjusting-colors.html)), and answers "missing number `intensity`" without one; a number outside the range counts as its nearest end. A value that is not a number, such as `"40"`, is refused with `` `intensity` must be a number, not "40" ``, as in every command that needs a number (`tests::params::a_malformed_required_number_is_not_reported_as_missing`). `edit.colors.adjustBalance` refuses a channel and `color.harmony` refuses `steps` or `amount` that is not a number; both read `null` as a value left out. `tests::editcolors` and `tests::colorguide` cover them. - **Convert to Indexed Color:** Edit › Edit Colors › Convert to Indexed Color… (`edit.colors.toIndexed`) stores the embedded images in the selection as indexed-color PNGs of at most 256 colors. The palette is chosen as for a PNG-8 export, as evenly spaced levels of red, green and blue, or from the document's swatches, with diffusion, pattern or noise dithering; pixels under half opacity become transparent. The dialog previews live, and OK is one undo step. This is VectorCraft's own command and counts toward no score. `tests::editcolors` and `encode::tests_palette` cover it. Scores and estimates unchanged. @@ -1777,8 +1864,11 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Eyedropper sources (#1251):** ordinary and Shift clicks, Shift+Alt appearance append, raster pixels and gradient-stop sampling can read visible locked/template art and sources outside isolation. Sampling leaves the source and selection intact; Alt reverse still uses editable hits, and hidden art stays excluded. Engine/tool/hit regressions cover the editing boundary, color models and one-step Undo/Redo. The general object/image workflow is described in [public HelpX](https://helpx.adobe.com/illustrator/using/tool-techniques/eyedropper-tool.html); the lock/isolation expectations come from the user report and these regressions, without a new full-parity measurement. - **Eyedropper colors in a CMYK document (#2276):** a CMYK image (a four-component JPEG, or an 8- or 16-bit chunky CMYK TIFF) gives its ink amounts as they are, and an RGB image's pixel or an RGB color given to `paint.setFill`, `paint.setStroke`, `paint.sampleColor` or `swatch.new {color}` (hex input and gradient stops included) is separated through the color settings' CMYK working space and intent, as Document Color Mode converts it. With the default Generic CMYK, RGB 83/170/223 separates to C62 M19 Y0 K0, where the profile-free formula gave C63 M24 Y0 K13. - **RGB input to other commands in a CMYK document:** type colors (`text.create`, `text.setStyle`, `text.setRangeStyle`), a Shape Builder hex fill, `paint.editGradient` stops, freeform gradient points, gradient mesh points (the Mesh tool gives a new point the fill's color in its own model), the Symbol Stainer's color and the swatch commands (`swatch.new {colors}`, `swatch.newGroup`, `swatch.editGroup`, `swatch.edit`) separate RGB through the color settings as `paint.setFill` does: with Generic CMYK, `text.setStyle {fill: "#53aadf"}` gives C62 M19 Y0 K0. A color a swatch already has keeps its model, and a swatch color given with `mode` is converted into that mode only. - - **Generic CMYK (SWOP-like):** each ink's 40% and 50% tints gain as [CGATS TR 001](https://registry.color.org/cmyk-registry/cgats_tr_001) gives for SWOP printing, and separations stay within SWOP's [300% total ink limit](https://en.wikipedia.org/wiki/Specifications_for_Web_Offset_Publications). The paper, solid and overprint colors, the black-generation curve and the black point are VectorCraft's own values: RGB black separates to 90% black under neutral cyan, magenta and yellow that fill the ink limit (C75 M68 Y67 K90). + - **Generic CMYK (SWOP-like):** each ink's 40% and 50% tints gain as [CGATS TR 001](https://registry.color.org/cmyk-registry/cgats_tr_001) gives for SWOP printing, and separations stay within SWOP's [300% total ink limit](https://en.wikipedia.org/wiki/Specifications_for_Web_Offset_Publications). The paper, solid and overprint colors, the black-generation curve and the black point are VectorCraft's own values: RGB black separates to 90% black under neutral cyan, magenta and yellow that fill the ink limit (C75 M68 Y67 K90). The ICC profile written for it (embedded in exports) gives the paper as its media white point, and its colorimetric Lab → CMYK table is the inverse of its CMYK → Lab table, without black-point compensation; the perceptual and saturation tables keep compensation. - **Swatches made from a shown color in a CMYK document:** the Color panel menu's Create New Swatch, an Alt-click on the Swatches panel's New Swatch button, the New Swatch dialog for a gradient, a Fill or Stroke proxy or the Gradient panel's thumbnail dropped on the Swatches panel (or Alt-dropped on a swatch of its kind), and the Gradient panel's Add to Swatches and Save to Swatches keep each color's model, as the Color Guide's and Color Themes' saved colors do: an RGB object's color gives an RGB swatch, and a gradient's RGB stops stay RGB. + - **Color Themes Set Active Color:** a button on the Color Themes panel's Create tab makes the selected theme color the current color, the action the [help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=222) describes for creating a color theme. VectorCraft's own rules: the color goes to the proxy in front (Fill or Stroke), on the selection and the default for new art, in its own color model, through `paint.setFill` or `paint.setStroke`; with characters selected with the Type tool, only those characters take it and the default for new art stays as it was, as with a swatch click; a click is one undo step, a click that changes no art adds none, and the button is off without a document. Tests: `set_active_color_*` in `crates/ui-egui/src/panels/color_themes.rs`. + - **Color Themes find field:** on the Color Themes panel's My Themes tab, Show Find Field in the panel menu shows a Find field that lists only the saved themes whose names hold its text; the [help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=255) describes looking up a saved theme by its name this way (printed page 249). VectorCraft's own rules: the menu item is checked while the field shows and is off in a new session; a name matches when it holds the text anywhere, in any letter case, with spaces at either end of the text ignored; colors are not searched; the list keeps its saved order and shows No matches. when nothing matches; a picked theme the field hides stays picked, but Edit Theme, Add to Swatches and Delete Theme are off until the list shows it again; turning the field off lists every theme, and turning it on again in the same session restores its text. The field does not change the saved themes or `colorTheme.list`. Tests: `show_find_field_toggles_the_find_field_on_my_themes`, `the_find_field_lists_themes_whose_names_hold_its_text`, `no_saved_themes_is_not_no_matches`, `a_theme_the_find_field_hides_is_not_acted_on` and `footer_buttons_are_off_for_a_hidden_pick` in `crates/ui-egui/src/panels/color_themes.rs`. + - **Color Themes sliders:** on the Color Themes panel's Create tab, a Color Mode menu (CMYK, RGB, Lab and HSB) shows a rail and a number field for each component of the selected theme color, beside its hex field; the [help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=221) describes changing the selected color's values in these color systems or as hex while making a theme. VectorCraft's own rules: the menu starts in the selected color's own model (HSB for a gray) and keeps the mode picked while the app runs; picking a mode changes no color; the ranges and whole-number steps are the Color panel's (Lab a and b from -128 to 127), a number past the range sets its end and text that is not a number changes nothing; a CMYK edit keeps the color CMYK and a Lab edit keeps it Lab, while RGB and HSB edits make it RGB, and the theme saves and goes to Swatches in those models; an edit works as a hex edit does: with a harmony rule the edited color becomes the theme's base and is selected, and in Custom only the selected color changes. Tests: `the_create_tab_offers_cmyk_rgb_lab_and_hsb_sliders`, `a_slider_edit_changes_only_the_selected_custom_color`, `the_sliders_keep_the_numbers_they_set`, `with_a_rule_a_slider_edit_rebuilds_the_theme_from_the_edited_color` and `cmyk_and_lab_slider_edits_keep_their_models` in `crates/ui-egui/src/panels/color_themes.rs`. - **Sample Color from Screen:** an eyedropper button in the Color Picker and `ui.sampleScreenColor` (which can be given a key in Keyboard Shortcuts) pick a color anywhere on the screen with the system's sampler: `NSColorSampler` on macOS, the XDG desktop portal's [PickColor](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Screenshot.html) on Linux, a still copy of every monitor under a crosshair on Windows, and the EyeDropper API in browsers that have it. The color becomes the fill or the stroke as one undo step, or the Color Picker's color, converted from display sRGB into the working RGB space. On Linux, a session without a portal that has PickColor, a portal that does not return from the call within 25 seconds (VectorCraft's own limit) or leaves the bus before it answers, and a portal that ends the request another way each show a status message and end the wait. On Windows, the copy is read as sRGB, so the colors of HDR and wide-gamut displays are not converted; Escape, a click of another mouse button or switching to another window cancels (VectorCraft's own rules). The BSDs and other browsers have no sampler yet; the button is gray there. - **Color Guide color groups:** with variation cells selected, the Color Guide's Save Color Group to Swatches button saves those cells as one swatch group, and with none selected it saves the harmony colors, as the [help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf) describes saving several selected variations together (printed page 135). The group takes the cells in grid order (row by row, left to right, each cell once), is named after the harmony rule and is one undo step; these are VectorCraft's own rules. A selection lasts until the base, the Color Guide Options, the variation mode, the harmony rule, the library limit or the colors the grid shows (for example after a new swatch while the guide is limited to the document's swatches) change. - **Color Guide colors dragged to Swatches:** a variation cell dragged from the Color Guide onto the Swatches panel's list becomes a swatch of that color, as the [help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf) describes for saving variations as individual swatches (printed page 135). In VectorCraft a harmony strip color drags the same way, a drag carries only the grabbed color (the selected cells stay selected and the selection is not saved), it carries the color the cell shows (snapped to the Limit to Library colors), keeps the color's model and does not paint the selected art; the swatch follows the panel's rules for a dropped color (`swatch.new`, one undo step, a color that is already a swatch is added again under another name, a drop on a color group joins it). These are VectorCraft's own rules. Tests: `a_dragged_guide_color_carries_its_color_and_applies_nothing` and `a_guide_color_dragged_onto_the_swatches_panel_becomes_a_swatch` in `crates/ui-egui/src/panels/color_guide.rs`. @@ -1803,6 +1893,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Under Tints and Tints and Shades, art in black ink alone goes by its ink amount, and a process or gray stroke color's tints and shades stay in that color's model; these are VectorCraft's own rules. Scale Proportionately art is scaled across by the stroke weight and the Width, as Stretch to Fit Stroke Length and Stretch Between Guides art is, on top of the scale the path length gives it, so a 3 pt stroke draws the art three times as wide as a 1 pt stroke. The [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page says Scale Proportionately keeps the art's proportions and does not say how the stroke weight applies; that rule is VectorCraft's own. Evidence: `tests::art_brush_proportional_grows_with_weight` (vectorcraft-brush). Type in a scatter brush's art takes the brush's colorization as its paths do: Tints, Tints and Shades and Hue Shift recolor the characters' solid fills and strokes in each copy the brush draws, and Brush Options' Key Color list, whose first color is Hue Shift's default key, counts the characters' fills and their strokes wider than 0. The Brushes page says that a scatter, art or pattern brush takes its colors from the current stroke color and the brush's colorization method () and does not mention type there; recoloring the characters' paints like the art's fills and strokes is VectorCraft's own rule. The Symbol Stainer mixes the characters' strokes of type toward the stain as it mixes their fills. Evidence: `tests::scatter_colorization_recolors_type`, `tests::art_colors_list_the_most_used_first`, `tests::stain_mixes_type_strokes_too` (vectorcraft-brush). + Scatter Brush Options has Hue Jitter (0° to 180°, 0 by default), VectorCraft's own option: each copy turns the hue of its solid colors, after the colorization, by its own amount up to that far either way. The stroke's path and the brush name fix the amounts, so a stroke draws the same colors every time, and the copies' places, sizes and rotations stay as they are without it. Evidence: `tests::hue_jitter_turns_each_copy_the_same_every_time`, `tests::hue_jitter_of_zero_changes_nothing`, `tests::hue_jitter_turns_after_the_colorization` (vectorcraft-brush), `tests::brushsym::scatter_hue_jitter_saves_and_exports` (vectorcraft-engine). - **Pen tilt, bearing and rotation (part of #764):** Calligraphic and Scatter Brush Options offer Tilt, Bearing and Rotation beside Fixed, Random and Pressure. The Paintbrush records along each stroke how far the pen leans, which way, and how far its barrel is turned (kept with the path, saved, and joined when a stroke continues a path). A Calligraphic value on Tilt goes from value − variation with the pen lying flat to value + variation upright; on Bearing or Rotation it adds variation × the angle over 180°, so Angle on Bearing with a Variation of 180° turns the nib with the way the pen leans. A Scatter value goes from its first value to its second over the same ranges. A stroke without that input draws the brush's own value. On Linux under X11 and XWayland the app reads the tilt and an Art Pen's barrel rotation from XInput2, on macOS it reads them from AppKit's tablet events, and `path.freehand` points and `pointer_gesture` events carry them on every platform. The [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page defines the three options and does not say which way each one runs; that mapping is VectorCraft's own rule. Evidence: `tests::tilt_maps_to_roundness_along_the_stroke`, `tests::bearing_and_rotation_turn_the_nib`, `tests::scatter_values_follow_tilt_and_bearing` (vectorcraft-brush), `tests_brushsym::paintbrush_records_the_pens_tilt_on_the_stroke` (vectorcraft-engine), `tablet::tests::a_pens_tilt_and_rotation_go_into_the_feed` and `mac_tablet::tests::a_pens_tilt_and_rotation_go_into_the_feed` (vectorcraft). Art Brush Options' Width (1% to 1000%) and Pattern Brush Options' Scale (1% to 10000%) each have a slider beside the field, over the same range in whole percents; screen readers name the slider as its row and read the field's value. Art Brush Options' Width has a Fixed or Pressure menu, from the pen tablet options of the Width pop-up menu on the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy). With Pressure, the art is Width wide at the lightest pen pressure and the second width at the heaviest, following the pressure the Paintbrush recorded along the stroke, and half way between them on a stroke without recorded pressure (`brush.options` `width_mode` and `width_max`); a stroke inside the art takes the width at the middle of its object. The page does not say how the pressure maps to the width; taking the Scatter brush's minimum and maximum rule and the stroke rule are VectorCraft's own. The menu also offers Tilt, Bearing and Rotation: the art goes from Width with the pen lying flat to the second width upright, and from Width at −180° to the second width at 180° of the pen's bearing or barrel rotation, as Scatter Brush Options' modes do, and half way on a stroke without that input; the page does not say which way each runs, so that mapping is VectorCraft's own. Evidence: `tests::art_brush_width_follows_tilt_bearing_and_rotation` (vectorcraft-brush). Stylus Wheel is not built. @@ -1818,6 +1909,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Document Info's Spot Color Objects category lists the objects that use spot colors, the category the [Document Info panel](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/document-info-panel.html) page describes as objects using spot color separations. Each object is listed by name with the spot colors it uses. With Selection Only it lists those in the selection, and the Document Info report and Package's report list them too (`document.info {category: "spotColors"}`, `spotObjects`). Taking a solid color or a gradient stop linked to a spot swatch at a tint above 0 and a grayscale image colorized with one, leaving out process colors that look the same, Registration, gradients whose stops are all at an opacity of 0, gradient stops at an opacity of 0 that mix only with other stops at an opacity of 0 or only over stretches with no width, fills and strokes at an opacity of 0, paint that draws nothing by the rules Pattern Objects follows, spot swatches no art uses and spot colors inside patterns, symbols, opacity masks, effects and placed files, are VectorCraft's own rules. A stop at an opacity of 0 next to a stop above it stays listed, since the stretch between them is drawn in its color. Objects counts the listed objects as Spot Color Objects. Tests: `cmd::docinfo::tests::info_lists_the_spot_color_objects`, `spot_color_objects_take_colorized_images_and_skip_clear_gradients`, `spot_color_objects_skip_clear_fills_and_strokes`, `spot_color_objects_skip_spot_stops_only_in_clear_stretches` and `drawn_stops_follow_the_sampled_stretches` (vectorcraft-engine). Document Info's Brushes, Spot Color Objects, Pattern Objects and Gradient Objects categories leave out hidden objects, objects at an opacity of 0 and the objects inside a hidden group or layer or one at an opacity of 0, their characters' paints and colorized images included. With Selection Only an object selected inside such a group or layer is left out too, and Objects still counts every object as before. This is VectorCraft's own rule. Test: `cmd::docinfo::tests::info_skips_paints_on_hidden_and_clear_objects_and_their_members` (vectorcraft-engine). Document Info's Save… writes the category the panel shows, with Selection Only applied, as the [Document Info panel](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/document-info-panel.html) page describes ("Exports the selected category's visible information to a text file"). With All Categories shown it writes every category, which is VectorCraft's own rule (`docInfo.save {category}`). Test: `panels::doc_info::tests::save_writes_the_category_the_panel_shows`. + Document Info's Document category lists the document's transparency settings, as the [Document Info panel](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/document-info-panel.html) page describes: File › Document Setup's grid size, grid colors, Simulate Colored Paper and flattener preset (`document.info`'s `document.transparency`). While the Artboard tool is the current tool, it also lists the width, height and position of each artboard that tool has selected, as the same page describes for the selected artboard (`document.selectedArtboards`). Listing every selected artboard, measuring the position at the top-left corner from the ruler origin of the tool's active artboard, and naming two custom grid colors by their values are VectorCraft's own rules. The panel shows the values in the interface language, and the report keeps them in English. Tests: `cmd::docinfo::tests::info_lists_the_transparency_settings` and `info_lists_the_artboards_the_artboard_tool_selected` (vectorcraft-engine), `panels::doc_info::tests::document_shows_transparency_and_the_artboard_tools_selection` (vectorcraft-ui-egui). Document Info's category menu and headings show every category title in the interface language, Font Details, Linked Images and Embedded Images included, and the Objects category shows every count label in it too: Compound Paths, Text Objects, Placed Documents, Symbol Instances, Gradient Meshes, Blends, Envelopes, Intertwine Groups, Opacity Masks and Objects with Effects. The Document category's Pattern Swatches row and the Objects category's Path Length row are translated in every catalog that has every menu label. `document.info` and the saved report keep the English labels. Showing these labels in the interface language is VectorCraft's own rule. Test: `i18n::tests::document_info_labels_are_in_complete_catalogs` (vectorcraft-ui-egui). Document Info shows the values it makes in the interface language too: the Units, the Raster Effects resolution, each font's file, substitution and embedding permission (or that it is built in or missing), each image's size and linked file, each Repeat object's kind with its instances, rows and columns in the language's plural forms, and gradients named by their kind. Font, face, file, swatch and other names stay as they are, a gradient swatch named like a kind included, and `document.info`, Save… and Package's report keep the English values (`document.unitId`, `fontDetails`, `imageObjects`, `gradientObjects` `kinds`). Showing these values in the interface language is VectorCraft's own rule. Tests: `panels::doc_info::tests::values_follow_interface_language_and_keep_names`, `repeat_value_uses_locale_plural_forms_and_drawn_count`, `i18n::tests::document_info_values_are_in_complete_catalogs` (vectorcraft-ui-egui), `cmd::docinfo::tests::info_exposes_structured_font_details_without_changing_english_rows`, `info_exposes_ordered_images_and_unit_id` and `gradient_kinds_tell_kinds_from_swatch_names` (vectorcraft-engine). The Brushes panel menu's Select All Unused selects the brushes that are not used in the document, as the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy) describes. A brush counts as used when a stroke paints with it in the art (opacity masks included), in symbols, graph designs, pattern tiles or graphic styles, or in the art of a used brush (`brush.unused`). @@ -1830,14 +1922,17 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The [About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html) page describes up to five Pattern brush tiles: sides, inner corner, outer corner, beginning and end. The archived [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page says to add pattern tiles to the Swatches panel and select a swatch from the scroll list for each tile. Pattern Brush Options offers document pattern swatches in all five tile menus, including swatches named like built-in choices. The brush copies each swatch's whole art and tile frame. Side requires art; explicit None on a corner prevents fallback to the other corner's art. After a swatch is deleted, the brush keeps drawing its copied art and shows it as Original. The cited pages do not describe copying the whole art, requiring Side, suppressing corner fallback after explicit None, or showing deleted swatch art as Original. `brush.options` accepts swatch names and an object form for names that match built-in choices, and rejects unknown patterns before editing. Evidence: `tests::brushsym::pattern_tile_choices_copy_whole_swatch_art_and_reject_invalid_side` and `tests::brushsym::pattern_tile_object_selects_reserved_swatch_names` (vectorcraft-engine), `tests::pattern_corner_source_none_leaves_that_kind_of_corner_empty` (vectorcraft-brush), and `dialogs::brush_options::tests::pattern_tile_menus_use_document_patterns_and_side_none_keeps_dialog_open`, `dialogs::brush_options::tests::pattern_options_borrowed_swatch_corner_keeps_its_frame`, and `dialogs::brush_options::tests::pattern_options_selects_swatches_with_reserved_names` (vectorcraft-ui-egui). - **Appearance:** the Appearance panel's selected row drives every paint, stroke, gradient and transparency edit (`item` on the commands); effects apply to one fill or stroke; per-item Opacity popups, whose blend-mode list and opacity slider stay open inside them (#430; the Control bar's Stroke popover too); Mixed Appearances, Layers target dots and basic-appearance rules. Effects can be reordered, moved between items and copied by dragging; Show All Hidden Attributes; clicking an effect edits it in place; the object thumbnail drags onto art; effects render on type, images, symbols, blends, envelopes, meshes and repeats, and per-item raster effects export. Groups, layers and type have their own fills, strokes and effects (Contents and Characters rows); the Layers panel's target circles target layers, groups and objects; Expand Appearance turns fills, strokes, effects and brushes into objects. Fill and stroke paint (Fill, Stroke, None, Apply Last Color and Apply Last Gradient, also on characters selected with the Type tool), the Stroke panel's options, gradient and freeform point edits, Swap Fill and Stroke, Default Fill and Stroke, the Eyedropper, and the Appearance panel's item edits, Clear Appearance, Reduce to Basic Appearance, Remove Item, item reordering and Move Appearance record no undo step when they change nothing. + A Stroke panel edit (`stroke.set` with no `item`) checks each object it collects against a set of the objects already listed, so collecting its targets takes time in step with the number of objects, and the list and its order are the same as before. With 20,000 paths in one group, collecting the targets takes 0.66 ms of thread CPU time on Linux, against 55 ms when each object is looked up in the list, and the whole command takes 60 ms (`crates/engine/examples/stroke_targets_bench.rs`; `cmd::stroke::tests::stroke_targets_match_the_listed_merge`). A Layers panel target circle dropped on the panel's Delete Selection button reduces that layer, group or object to basic appearance (`appearance.reduceToBasic`) in one undo step and deletes nothing, as the [Appearance attributes](https://helpx.adobe.com/illustrator/using/appearance-attributes.html) help page describes for that drag. Which fill and stroke stay (the topmost visible ones), that a layer or group keeps only the rows it had, and that the object's opacity and blend mode stay are VectorCraft's own rules (`panels::layers` test `dropping_a_target_circle_on_the_trash_reduces_it_to_basic_appearance`). The Add New Effect popup (Appearance panel, Properties), the Appearance panel's swatch picker, the Gradient panel's gradient swatches menu and the Image Trace button's list of presets stop at the bottom of a short window, and the mouse wheel or the scroll bar reaches their last rows. A list that fits does not scroll (`a_long_swatch_picker_scrolls_inside_a_short_window`). An image's own fills and strokes draw the shape that a Convert to Shape or Outline Object effect on them gives them (the image's box, or the outline of the image's opaque area or its frame, reshaped by the effects after it), under or over the image as its Contents row says, on the canvas, in exports and through Expand Appearance; new fills and strokes on an image go under it. Without one of those effects they draw nothing, and Use Preview Bounds then measures an image by its frame. Outline Object on an image's own fill or stroke follows the outline of the image's opaque area, and the image's frame when the image has no transparency. Path effects apply to a fill or stroke added to a bitmap object ([archived reference manual, page 561](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=561)), and with Outline Object such a stroke follows the boundary of the art when the image has transparent areas and the image's frame when it has none ([CreativePro article on strokes for placed images](https://web.archive.org/web/20250815214529/https://creativepro.com/add-strokes-placed-images-illustrator/)). VectorCraft's own rules: the opaque area is the pixels at least 50% opaque, and its outline is traced as Image Trace's Black and White mode traces at threshold 128 and fitted with curves. Evidence: `tests::imageoutline` (vectorcraft-effects), `opaque::tests` (vectorcraft-trace), `tests::containers::an_images_stroke_with_outline_object_follows_its_opaque_area` and `tests::containers::an_images_outline_object_stroke_exports_selects_and_measures_along_its_opaque_area` (vectorcraft-engine), `tests::objectfx::an_images_outline_object_stroke_follows_new_pixels_under_the_same_key` (vectorcraft-render). A geometry effect on one of type's own fills or strokes reshapes the whole outline that the fill or stroke paints, on the canvas and in exports; PDF, SVG, EPS and the other vector exports write such type as paths. On type that holds inline graphics, those effects are drawn and exported only when the type has a geometry effect or perspective of its own. A geometry effect on a symbol instance's fill reshapes the filled shapes of the symbol's art and leaves their strokes as they are; one on the instance's stroke reshapes the stroked shapes and leaves their fills as they are. The shapes keep their colors. Only the instance's topmost fill and topmost stroke count, and only while they are visible with an opacity above 0. The canvas and Object › Expand Appearance use the same art, SVG and PDF export bake the same shapes, and Expand Appearance turns the instance into an editable group in one undo step. A group's own fills and strokes in the art take the effects too. An instance inside the art passes the effects on to its own art, and a dynamic symbol's instance reshapes the fills and strokes it paints on the art. How the effects map onto the symbol's art is VectorCraft's own rule. The help page describes effects on one fill or stroke, and the help page describes Expand Appearance (engine `expand::a_symbol_instance_fill_effect_reshapes_its_filled_art_and_expands`, `a_symbol_instance_stroke_effect_reshapes_its_stroked_art_and_expands`, `a_stroke_effect_reshapes_a_stroke_a_dynamic_instance_adds`, `a_fill_effect_reshapes_the_fill_of_a_group_in_the_art`, `only_the_topmost_visible_instance_fill_reshapes_the_art`, `a_nested_symbol_instance_takes_the_outer_fill_effect`, `export_bakes_a_symbol_instance_fill_effect`, `a_fill_effect_on_an_instance_of_a_symbol_that_holds_itself_ends`). Existing documents with a geometry effect on a symbol instance's fill or stroke draw differently: before, the effect drew nothing. + Effect › Pathfinder takes a symbol instance as the art it draws with the geometry effects of its fill and stroke, as they take a path with such effects: the result painted by the instance's art carries those effects, also when the instance has geometry effects of its own and when the instance sits inside another symbol's art. A click where those effects paint the art outside the instance's bounds selects the instance, a fill only when Selection by Path Only is off, and outline mode still takes the instance's bounds alone. A marquee across those shapes selects the instance too, and a marquee across the shape an image's own fill or stroke paints outside its frame selects the image, except in outline mode. A compound shape's area leaves out its members' fill and stroke effects for symbol instances as for paths, since the compound shape paints the area with its own appearance. These are VectorCraft's own rules (engine `expand::pathfinder_takes_a_symbol_instance_fill_and_stroke_effects`, `a_click_where_a_symbol_instance_fill_or_stroke_effect_paints_selects_it`, `a_stroke_effect_reshapes_a_stroke_a_dynamic_instance_adds`, `a_fill_effect_reshapes_the_fill_of_a_group_in_the_art`, `a_click_on_the_grown_fill_of_an_image_in_the_art_selects_the_instance`, `a_marquee_where_a_symbol_instance_fill_or_stroke_effect_paints_selects_it`, `a_marquee_on_the_shape_of_an_image_fill_selects_it`). Before, Pathfinder dropped those effects, and clicks and marquees took only the instance's bounds. Live effects inside a symbol's art (geometry effects, color adjustments and the rest that export bakes) are written where each instance places the art in PDF, print, EPS and DXF, as the canvas draws them: the art is placed first and its effects are applied after, so an instance that scales its art does not scale the distance a Transform effect moves it. Symbols nested in the art, a dynamic symbol instance's own paint changes and the stain an instance's fill gives its art are kept, and the art is stained before its effects apply. A linked instance's PDF link covers its art where the effects draw it. A symbol whose art holds itself stops at the nesting limit, and the symbols' own art keeps its effects. An instance stays an instance in these exports when the objects its art makes once baked (the copies a Transform effect makes included) would take the export's placed symbol art past 16,000,000 objects, or when its baked art would draw deeper than the 128 levels a document may draw; these are VectorCraft's own limits. Art baked for an instance that then stays an instance still counts toward that limit, and while an instance's art bakes, the art's own objects are held in the limit for the instances nested in it. Instances the export leaves out (hidden ones, those in hidden groups, on template layers, and on hidden layers or layers that do not print when the export leaves those out) are not placed and do not count toward that limit. Before, these exports wrote the art without its effects (effects `bake::placing_symbols_bakes_their_art_where_each_instance_places_it`, `placing_symbols_reaches_the_art_of_nested_instances`, `placing_a_symbol_that_holds_itself_stops`, `placing_symbols_keeps_dynamic_instances_changes`, `placing_symbols_keeps_the_instances_stain`, `placing_symbols_counts_the_baked_art`, `placing_symbols_counts_nested_art_once`, `placing_symbols_holds_the_outer_art_while_it_bakes`, `placing_symbols_counts_the_art_it_drops`, `placing_symbols_counts_art_dropped_for_depth_against_later_baked_art`, `placing_symbols_keeps_the_baked_art_within_the_drawn_depth`, `placing_symbols_skips_instances_the_export_leaves_out`; doc `depth::tests::drawn_heights_measure_objects_outside_the_layers`; PDF, print, EPS and DXF `symbol_art_effects_are_written_where_they_draw`, `symbol_art_effects_print_where_they_draw`; PDF `a_stained_instance_keeps_its_stain_when_its_art_has_effects`, `a_linked_instance_keeps_its_link_when_its_art_has_effects`). EMF, WMF and SVG export write the same symbol art the same way: an instance of a symbol whose art, or the art of a symbol nested in it, has such effects is written as that art placed by the instance and then baked, so a square that a Transform effect moves 100 pt right draws 100 pt right of where the instance places it at any scale or rotation, and art the effect moves onto the artboard is written. EMF and SVG clip 9-slice cells and WMF does not, as each places other instances. In SVG those instances use no ``, and instances of symbols without such effects still share one; named objects in a symbol's art take no ids there, as in an instance with its own copy of the art, so two instances do not write the same id; with Hidden Layers on, hidden instances are placed too and written hidden. An SVG instance nested in another instance's art is shared through `` only when the transform it is drawn with, the outer instances' included, keeps the shared art as the canvas draws it, so a nested stroke keeps its weight in a scaled instance. Preserve Editing still embeds the document with its live effects. Before, these exports wrote the art without its effects (metafile `tests::import::symbol_art_effects_are_written_where_they_draw`; SVG `symbols_layers::symbol_art_effects_are_written_where_the_canvas_draws_them`, `a_kept_hidden_instance_is_written_with_its_symbols_effects`, `instances_written_as_their_art_give_its_names_no_id`, `a_nested_instance_is_shared_only_under_the_transform_it_is_drawn_with`; effects `bake::placing_symbols_skips_instances_the_export_leaves_out`). + EMF and WMF export with Use Artboards applies the document's live effects once for all the chosen artboards instead of once for each, and writes the same files byte for byte (metafile `tests::export_regions_writes_what_each_region_writes_alone`; `export_regions_perf` times it). When an export bakes a symbol instance with geometry effects inside the art of another such instance, it counts the art the inner instance bakes to, the copies its symbol's effects make included, against the 262,144 objects of symbol art one export bakes that way; it counted only the symbol's art before its effects. An instance whose baked art would pass that count stays an instance with its effects, and the art baked for it still counts against the instances after it. These are VectorCraft's own limits (effects `bake::nested_reshape_counts_baked_art`, `nested_reshape_refusal_keeps_its_work_counted`, `nested_reshape_refused_siblings_bake_once`, `nested_reshape_counts_successful_descendants_once`). A raster effect (Drop Shadow, Outer Glow, Gaussian Blur and the other effects that paint pixels) on a symbol instance's topmost fill draws on each filled shape of the symbol's art, and one on its topmost stroke draws on each stroked shape, after any geometry effects listed before it, under the same rules as geometry effects: only a visible fill or stroke with an opacity above 0 counts, a group's own fills and strokes in the art take the effect, and an instance inside the art passes it on. Each shape gets its own shadow or glow, which is VectorCraft's own rule. The canvas, Use Preview Bounds and the drawn bounds, SVG and PDF export draw it, and Object › Expand Appearance is enabled for such an instance and makes the effect an image at the document's raster effects resolution, in one undo step (engine `expand::a_symbol_instance_fill_shadow_shadows_its_filled_art`, `a_symbol_instance_stroke_shadow_shadows_only_its_stroked_art`, `a_symbol_instance_fill_shadow_follows_the_fill_offset_before_it`, `a_nested_symbol_instance_takes_the_outer_fill_shadow`, `export_draws_a_symbol_instance_fill_shadow`). Existing documents with a raster effect on a symbol instance's fill or stroke draw differently: before, the effect drew nothing. Object › Expand Appearance turns a symbol instance whose topmost fill or stroke has only raster effects into its art as well, with the effect's image under the art (a shadow or glow) or in its place (a blur, feather or inner glow). A symbol instance inside the art whose topmost fill or stroke has a geometry or raster effect, its own or one the outer instance passes on, becomes its art and image the same way, and so do the instances in that art, within the nesting and symbol art limits; an instance of a missing symbol stays an instance. One Expand Appearance makes at most 1,024 images of raster effects, holding 256 megapixels in all (VectorCraft's own limits); an object or instance whose image would go past them stays as it is, with its raster effects, and the result reports how many with `rasterLeft` and a warning. Within those limits no live instance or raster effect is left from those effects, so the result no longer changes with the symbols; an instance left by the image limits still follows its symbol. The help page describes Expand Appearance turning appearance attributes into objects, and the help page describes expanding an effect into permanent raster data; expanding nested instances this way is VectorCraft's own rule (engine `expand::a_nested_instance_fill_shadow_becomes_an_image_when_the_outer_art_expands`, `an_outer_fill_shadow_expands_the_instance_and_reaches_the_nested_art`, `a_nested_instance_fill_blur_becomes_an_image_when_the_outer_art_expands`, `a_hidden_nested_instance_fill_shadow_makes_no_image`, `a_nested_instance_of_a_missing_symbol_stays_an_instance`, `nested_instance_raster_effects_stop_at_the_image_limit`). Before, an instance whose fill or stroke had only a shadow or glow stayed an instance over the image, and a raster effect on an instance in the art stayed live. @@ -1846,7 +1941,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, also when the clipping path paints a fill or stroke of its own: that fill and stroke draw the shapes their effects give them. 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. + 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, also when the clipping path paints a fill or stroke of its own: that fill and stroke draw the shapes their effects give them. Type used as a clipping path keeps its geometry effects when a group's effect outlines it, and keeps the fill and stroke it was given after the mask was made ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-clipping-masks.html)): its fill still paints behind the clipped art inside the clip and its stroke over it, reshaped with the clip, on the canvas and in SVG and PDF export (the `painted_clipping_type_exports_with_group_effect` tests in `vectorcraft-svg` and `vectorcraft-pdf`). 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. 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. @@ -1859,6 +1954,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur In the Graphic Styles panel, Shift-click selects a range of styles and Ctrl/Cmd-click adds or removes one. A graphic style dragged onto the Graphic Styles panel's New Graphic Style button is duplicated, as the panel menu's Duplicate Graphic Style does, and both put the copy at the end of the list, as the help page describes ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=391)). VectorCraft's own rules: the button takes the drop with no art selected; a dragged style that is highlighted brings the other highlighted styles, copied in panel order in one undo step, and the copies are highlighted; the copy is named ` copy`, with a number when that is taken, and no art is linked to it (`a_style_dropped_on_new_graphic_style_is_duplicated_at_the_end` in `crates/ui-egui/src/panels/graphic_styles.rs`, `tests::styles::duplicate_puts_the_copy_at_the_end_of_the_list_in_one_undo_step`). A graphic style dragged onto the Graphic Styles panel's Delete Graphic Style button is deleted, which the help page gives as another way to delete a style besides the panel menu's Delete Graphic Style; art that used the style keeps its look and is no longer linked to it ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=392)). VectorCraft's own rules: the drop asks first as the button does, and with Alt held it deletes without asking; the button takes the drop with no style highlighted; a dragged style that is highlighted brings the other highlighted styles, deleted in one undo step (`a_style_dropped_on_delete_graphic_style_is_deleted_as_the_button_deletes` in `crates/ui-egui/src/panels/graphic_styles.rs`). + The Appearance panel's thumbnail dropped on a graphic style with Alt held replaces that style with the look of the object the panel shows; the style keeps its name and the art that uses it takes the new look, as the help page describes ([the help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=568)). VectorCraft's own rules: art dragged off the canvas does the same with its first object; the style keeps its place in the list, is outlined while one is held over it with Alt, and the replacement is one undo step; an object already linked to the style with its look changes nothing; without Alt the drop makes a new style (`art_or_an_appearance_dropped_on_a_style_with_alt_replaces_that_style` in `crates/ui-egui/src/panels/graphic_styles.rs`). + A graphic style dragged onto another style in the Graphic Styles panel with Alt held gives that style the dragged style's look; the replaced style keeps its name and the art that uses it takes the new look, as the help page describes ([the help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=568)). VectorCraft's own rules: the dragged style and the art linked to it stay as they are; the replaced style keeps its place in the list and is outlined while a style is held over it with Alt; the replacement is one undo step; a style dropped on itself, or on a style with the same look, changes nothing and records no undo step; without Alt the style moves (`graphicStyle.redefine {name, from}`, `a_style_dropped_on_another_with_alt_replaces_that_style` in `crates/ui-egui/src/panels/graphic_styles.rs`, `tests::styles::redefine_from_a_style_gives_the_style_that_look`). In the Graphic Styles panel's thumbnail and list views, a style with no fill and no stroke, one with only effects or transparency included, shows its preview shape with a black outline, a white fill and a red slash, as the help page describes for the panel's thumbnails ([Graphic styles](https://helpx.adobe.com/illustrator/using/graphic-styles.html)); its effects still draw on that shape. The Control bar's Style picker and chip, graphic style library panels and the large preview on the selected object show the same marker. A fill or stroke row that paints None does not count as a fill or stroke, and a hidden row or one with zero opacity does; these rules, the marker outside the panel's thumbnails and the slash's direction and size are VectorCraft's own (`a_style_with_no_fill_and_no_stroke_shows_an_outlined_shape_and_a_red_slash` in `crates/ui-egui/src/panels/graphic_styles.rs`). Applying a style to several objects, and Redefine Graphic Style, give the objects one shared copy of the style's appearance instead of a copy each; an object that is edited later gets its own copy, and an object whose placed gradients are fitted to its own bounds gets its own. The undo history's memory estimate counts a shared appearance once. Saved files are unchanged (`crates/engine/src/tests/styles.rs`). - **Several text styles at once:** in the Character Styles and Paragraph Styles panels, Shift-click highlights a range of styles and Ctrl/Cmd-click adds or removes one, without applying them; the panel menu's Select All Unused (`charStyle.unused`, `paraStyle.unused`) highlights the styles no type uses (in the layers, opacity masks, symbols, graph designs, pattern tiles and the art of brushes), never the Normal style; Delete, the button or the menu item, deletes every highlighted style but Normal in one undo step (`charStyle.delete {names}`, `paraStyle.delete {names}`). The menu's Duplicate copies every highlighted style in one undo step and highlights the copies. A highlighted row dragged onto Create New Style or Delete carries every highlighted style: dropped on Create New Style it copies them all and highlights the copies, and dropped on Delete it deletes them all but Normal and clears the highlight; a row from outside the highlight carries only its own style. Public reference: [Character and paragraph styles](https://web.archive.org/web/20261015081534/https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). @@ -1898,8 +1995,9 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Fonts:** a font is found by any of its names (family and style in every language of its name table, legacy family/style pairs, PostScript name), so documents from other apps open with the font they name; Find Font and `text.fonts` say for each font whether it was found exactly, by another name, substituted or missing, and how many glyphs are missing. PDF and `.ai` import brings Japanese text back as live type: CID fonts without a ToUnicode map read through the standard CMaps, vertical columns (WMode 1) as vertical type, letter spacing as tracking; a glyph is live type only when the installed font (in the closest style of its family) draws the same glyph, and text in a font that isn't installed comes in as live type shown in the fallback font until the font is installed (exports that draw it — PDF, EPS, EMF/WMF, raster, SVG outlines or embedded fonts — warn that they wrote the fallback font, and Print and Print Preview warn about the type that prints in it; `textAs: outlines` keeps the PDF's embedded glyphs). Two installed versions of one family and style (a font library keeping an old file beside a new one) both load, the first staying the one the family and style resolve to; PDF and `.ai` import tries each version when the glyphs differ, and type set in a version other than that one names it (`CharStyle::font_version`), which layout, the substituted-glyph highlight, Find Font, Package and Document Info follow. Fonts outside the font folders are listed too: those font services such as Adobe Fonts load on Windows, through DirectWrite and, for those only GDI lists, through GDI (#1258), and those apps and font managers register with CoreText on macOS (#579). When a document opens with fonts that aren't available, fonts used only in symbols included, a Missing Fonts dialog lists them after the linked-file questions, with Find Fonts (Type › Find Font on them) and Close. Its Find in Folder… (in Find Font too) searches a folder on several threads, reads only what the font scan reads of font files and skips app packages, the Program Files and ProgramData folders, the system's folders and the app data folders in a home folder; Add Fonts copies the font files the user chooses, suitcase fonts with their resource fork, into VectorCraft's own Fonts folder, which the desktop app and `vectorcraft-cli` read (`text.missingFonts`, `text.findFontFiles`, `text.addFontFiles`). The font scan on Linux also reads the folders fontconfig's configuration lists, such as TeX fonts under `/usr/share/texmf/fonts` (#1548, fixes #1529; not verified on Linux). A variable font's type gets one slider and field per variation axis under the Character panel's Variable Font button, each named as the font names the axis (Weight, Width), so the type can be set between or past its named instances: the settings stay with the characters (`CharStyle::font_axes`, `text.setFormat {fontAxes}` and `text.setRangeStyle {fontAxes}`, clamped to each axis's range; `text.fontList {family, style}` lists the axes), and layout, outlines, the substituted-glyph highlight and PDF and SVG export (`font-variation-settings`, embedded fonts) use the font instanced at them. Another font or style clears them; legacy `.ai` export writes the style and warns that they are left out. The font menu's Font Technology › Variable (under the kind filter, as [Find, apply, and adjust variable fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/find-apply-and-adjust-variable-fonts.html) places Variable in the classification filter's Font Technology section) lists only the families with variation axes, a family with a variable file beside static ones included, and works together with the script, kind, ★ and search filters; it stays set from one opening to the next. Measured by `font_menu::tests::the_variable_filter_lists_only_variable_families`, `font_menu::tests::the_variable_filter_is_named_as_fonts_are`, `tests_axes::a_family_with_variation_axes_is_variable` and `tests_sysfonts::a_family_with_a_variable_file_beside_static_ones_is_variable`. - The font menu's Document filter (beside ★) lists only the families that type in the current document is set in, as the quick filter for fonts used in the document does on the [font browser overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/font-options-overview.html). It works together with the search, script, kind, Variable and ★ filters, Recent Fonts and Show Similar Fonts, steers the closed field's wheel, follows edits and undo while the menu is open, and is shared by every font menu for the session like the other filters. VectorCraft's own rules: hidden, locked, masked, symbol, pattern and graph design type counts, styles no type uses do not, a composite font lists under its own name, a family the document names but this computer lacks is not listed (Find Font reports it), a document without available fonts lists nothing with its own message, and with no document open the filter is unavailable. Measured by `font_menu::tests::the_document_filter_lists_the_families_the_documents_type_uses`, `font_menu::tests::the_document_filter_combines_with_the_others_and_follows_edits`, `font_menu::tests::the_document_filter_counts_type_in_graph_designs` and `font_menu::tests::the_document_filter_on_an_empty_document_or_none`. + The font menu's Document filter (beside ★) lists only the families that type in the current document is set in, as the quick filter for fonts used in the document does on the [font browser overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/font-options-overview.html). It works together with the search, script, kind, Variable and ★ filters, Recent Fonts and Show Similar Fonts, steers the closed field's wheel, follows edits and undo while the menu is open, and is shared by every font menu for the session like the other filters. VectorCraft's own rules: hidden, locked, masked, symbol, pattern and graph design type counts, as does type in the art of a stored scatter brush (art and pattern brushes leave type out when they bend their art, so their type does not count), styles no type uses do not, a composite font lists under its own name, a family the document names but this computer lacks is not listed (Find Font reports it), a document without available fonts lists nothing with its own message, and with no document open the filter is unavailable. Measured by `font_menu::tests::the_document_filter_lists_the_families_the_documents_type_uses`, `font_menu::tests::the_document_filter_combines_with_the_others_and_follows_edits`, `font_menu::tests::the_document_filter_counts_type_in_graph_designs`, `font_menu::tests::the_document_filter_counts_type_in_scatter_brushes`, `font_menu::tests::the_document_filter_follows_a_scatter_brushs_edits_and_undo` and `font_menu::tests::the_document_filter_on_an_empty_document_or_none`. The font menu's Recently Added filter (on its own row under Font Technology) lists only the installed families added in the last 30 days, the newest at the top, as the [user guide](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=486) and the [font browser overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/font-options-overview.html) describe it (`vectorcraft_text::FontDb::recently_added`). It works together with the search, script, kind, Variable, ★ and Document filters, lists only the families every active filter matches, steers the closed field's wheel, and is shared by every font menu for the session like the other filters. VectorCraft's own rules: a family is dated by the creation time of its newest font file on this computer (a file the file system keeps no creation time for, or one dated in the future, does not count), the 30th day is included, families added at the same instant are in name order, the recently used families appear in that order without the Recent Fonts section, Show Similar Fonts orders only the families the filter lists, a family leaves the list when its 30 days end while the menu is open, an empty list keeps the filter on and says no fonts match, and fonts bundled with the app or loaded from documents are never listed. Measured by `font_menu::tests::the_recently_added_filter_lists_new_families_newest_first`, `font_menu::tests::the_recently_added_filter_drops_families_as_their_30_days_end`, `font_menu::tests::the_recently_added_filter_lists_a_font_installed_just_now`, `tests::recently_added::families_added_in_the_last_30_days_are_listed_newest_first`, `tests::recently_added::a_family_is_dated_by_its_newest_valid_file` and `tests::sysfonts::installed_fonts_are_recently_added_by_their_files_creation_time`. + While the samples are shown, the font menu's row under the filters sets the sample size to Small, Medium or Large from inside the menu, as the [font browser overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/font-options-overview.html) and the [user guide](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=485) describe the sample size control; with Enable in-menu font previews off, the row is not shown, as the user guide describes. VectorCraft's own rules: the row sits under the filters and sets Preferences › Type › Font Preview Size (`fontPreviewSize`), so every font menu takes the new row height, the Composite Fonts and Dimension dialogs' included, and the open list stays on the rows it showed; the current size is selected and a click on it changes nothing; screen readers find the three sizes as radio buttons in a group named Font Preview Size; a saved value that is none of the three sizes shows Medium and a click replaces it; the change adds no undo step and leaves a font previewed on the selected type in place. Measured by `font_menu::tests::the_preview_size_row_asks_for_the_size_clicked`, `font_menu::tests::a_preview_size_asked_for_sets_the_preference_and_keeps_the_preview`, `font_menu::tests::the_preview_size_row_is_a_radio_group_showing_the_size` and `font_menu::tests::a_new_preview_size_keeps_the_list_on_its_rows`. The font database looks up a name that is neither a loaded nor an installed family among the other names of the loaded and installed fonts once for each style it is asked in, and keeps the answer until fonts are added or rescanned. Laying out a story of 1,000 paragraphs set in a font that is not installed, with 400 more fonts loaded, takes a median of 56 to 71 ms instead of 409 to 507 ms on Windows 11 (`CRAFT_FONTS_DIR= cargo test --release -p vectorcraft-text --lib missing_font_story_layout_timing -- --ignored --nocapture`). A font family removed while the app runs leaves the font menus when the app scans the font folders again (when its window comes to the front after a font folder changed, or Refresh Font List), also when type had used it: that type then draws in the fallback font and Find Font lists the font as missing, until the font is installed again and the folders are scanned. - **Files (M4):** @@ -1930,8 +2028,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Save as Template writes a PDF-compatible `.ait` as well as a `.vctemplate`, which stays the default: the save panel and the web build's Save as Template dialog list both, and New from Template opens the `.ait` as an untitled document with its layers and art (`file.saveAsTemplate {format: "ait"}`, or a path ending in `.ait`). Save as Template always writes a file named with its template type's extension: `file.saveAsTemplate` saves a path ending in another format's extension (`card.png`) as `card.vctemplate` (or `card.ait`), the desktop save panel does the same with a Save As format's extension typed in it (`card.pdf` is saved as `card.vctemplate`), and `file.saveAs` and `document.save` refuse `ait` with an error that names `file.saveAsTemplate`. A `.ait` is PDF-compatible only: `aiVersion: "7"` is an error for it, and the web build's dialog shows no Version row for it. Exports refuse a `.ait` with an error that names `file.saveAsTemplate`, and `vectorcraft-cli convert in.pdf out.ait` and `run --export out.ait` write the template as `file.saveAsTemplate` does. - - SVG/SVGZ in and out with SVG Options, Preserve Editing, symbols, filters, rich text and physical units (SVG type under a transform or `viewBox` scale opens at the size it draws at, the scale moved into its size, leading, baseline shift and strokes, a stretch, skew or rotation kept as its transform: #396; a top-level group with a clip path, such as a clipped Inkscape layer, opens as a layer with a clipping mask, its name kept: #420; hidden objects written hidden on Save and `convert`, and `data-*` attributes kept as the objects' own data: #522; top-level groups open as layers named from `data-name`, else the id, also when one more group (a transform on all the art, a ``) wraps them, hidden ones hidden, and a file whose art sits loose under a root `` with an id (or `data-name`), as one-layer exports write it, opens with its one layer named from it; nested groups stay groups, except the sublayers VectorCraft writes, marked `data-vc-layer`, and Inkscape sublayers, which open as sublayers in their layer's colour: #372); PDF and PDF-compatible `.ai` in and out (layers, with hidden ones kept hidden with their art and nested ones as sublayers, on pages of up to 64 million operators, art whose layer can't be told going to a hidden, non-printing layer rather than showing or printing: #419; strokes kept live, a fill and a stroke of one outline as one object; a type object's stroke written as each glyph's outline stroked back on the type, so it stays one editable object; lines wrapped in a frame (each wrapped line ending in a space, one left edge, leading and font) back as one area type object, left aligned or justified with its paragraph spacing, where laying it out breaks the lines where the file does; glyphs set apart by gaps wider than a space (a barcode's digit groups) keeping their places; layers stacked as the pages mark them even when one first paints on a later page, art ending a layer's marked content or a clip closing in a later layer kept in its own layer, and layers with no art kept empty: #508; art reaching past a plain PDF's page clipped to its crop box, as PDF viewers show it, each such object in a clip group of its own (a PDF-compatible `.ai` opens whole: #675); a `.ai` on its trim boxes with the bleed boxes round them as the document's bleed, as Crop To › Trim opens a PDF (#1266); masks, editable text with type set along a curve coming back as type on a path, each artboard's art on its own page only, an `.ai`'s white page under its layers left out rather than coming in as art, spot colours, presets, security, marks and bleed, ICC output intents, raster effects, subset fonts, PDF/X, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3). CMYK images keep their ink amounts from PDF import (and from placed CMYK TIFFs) to PDF export: a CMYK JPEG passes through unchanged, others stay CMYK (DeviceCMYK, or ICC-based CMYK in PDF/X-3/X-4) unless the Output settings convert them; the canvas shows them through the working CMYK profile (#320). Overprint is kept from PDF import (opened, the PDF part of an `.ai`, placed) to PDF export: the graphics state's `/OP` and `/op` become the overprint of fills, strokes and type, so a spot colour over a process colour still overprints; a page whose overprint can't be read for certain knocks out with a note, as does `/OPM 0` being read as nonzero overprint (#1388; hand-written fixtures, `pdf/src/tests/import_overprint.rs`). A masked CMYK image (`/SMask`, `/Mask` or a colour key) keeps its inks too, its alpha coming in as a greyscale opacity mask. - - SVG/SVGZ in and out with SVG Options, Preserve Editing, symbols, filters, rich text and physical units (SVG type under a transform or `viewBox` scale opens at the size it draws at, the scale moved into its size, leading, baseline shift and strokes, a stretch, skew or rotation kept as its transform: #396; a top-level group with a clip path, such as a clipped Inkscape layer, opens as a layer with a clipping mask, its name kept: #420; hidden objects written hidden on Save and `convert`, and `data-*` attributes kept as the objects' own data: #522; top-level groups open as layers named from `data-name`, else the id, also when one more group (a transform on all the art, a ``) wraps them, hidden ones hidden, and a file whose art sits loose under a root `` with an id (or `data-name`), as one-layer exports write it, opens with its one layer named from it; nested groups stay groups, except the sublayers VectorCraft writes, marked `data-vc-layer`, and Inkscape sublayers, which open as sublayers in their layer's colour: #372); PDF and PDF-compatible `.ai` in and out (layers, with hidden ones kept hidden with their art and nested ones as sublayers, on pages of up to 64 million operators, art whose layer can't be told going to a hidden, non-printing layer rather than showing or printing: #419; strokes kept live, a fill and a stroke of one outline as one object; a type object's stroke written as each glyph's outline stroked back on the type, so it stays one editable object; lines wrapped in a frame (each wrapped line ending in a space, one left edge, leading and font) back as one area type object, left aligned or justified with its paragraph spacing, where laying it out breaks the lines where the file does; glyphs set apart by gaps wider than a space (a barcode's digit groups) keeping their places; layers stacked as the pages mark them even when one first paints on a later page, art ending a layer's marked content or a clip closing in a later layer kept in its own layer, and layers with no art kept empty: #508; art reaching past a plain PDF's page clipped to its crop box, as PDF viewers show it, each such object in a clip group of its own (a PDF-compatible `.ai` opens whole: #675); a `.ai` on its trim boxes with the bleed boxes round them as the document's bleed, as Crop To › Trim opens a PDF (#1266); masks, editable text with type set along a curve coming back as type on a path, each artboard's art on its own page only, an `.ai`'s white page under its layers left out rather than coming in as art, spot colours, presets, security, marks and bleed, ICC output intents, raster effects, subset fonts, PDF/X, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3). CMYK images keep their ink amounts from PDF import (and from placed CMYK TIFFs and the images in an `.ai` or EPS file's editing data, an alpha channel coming in as a grayscale opacity mask) to PDF export: a CMYK JPEG passes through unchanged, others stay CMYK (DeviceCMYK, or ICC-based CMYK in PDF/X-3/X-4) unless the Output settings convert them; the canvas shows them through the working CMYK profile (#320). Overprint is kept from PDF import (opened, the PDF part of an `.ai`, placed) to PDF export: the graphics state's `/OP` and `/op` become the overprint of fills, strokes and type, so a spot colour over a process colour still overprints; a page whose overprint can't be read for certain knocks out with a note, as does `/OPM 0` being read as nonzero overprint (#1388; hand-written fixtures, `pdf/src/tests/import_overprint.rs`). A masked CMYK image (`/SMask`, `/Mask` or a colour key) keeps its inks too, its alpha coming in as a greyscale opacity mask. + - SVG/SVGZ in and out with SVG Options, Preserve Editing, symbols, filters, rich text and physical units (SVG type under a transform or `viewBox` scale opens at the size it draws at, the scale moved into its size, leading, baseline shift and strokes, a stretch, skew or rotation kept as its transform: #396; a top-level group with a clip path, such as a clipped Inkscape layer, opens as a layer with a clipping mask, its name kept: #420; hidden objects written hidden on Save and `convert`, and `data-*` attributes kept as the objects' own data: #522; top-level groups open as layers named from `data-name`, else the id, also when one more group (a transform on all the art, a ``) wraps them, hidden ones hidden, and a file whose art sits loose under a root `` with an id (or `data-name`), as one-layer exports write it, opens with its one layer named from it; nested groups stay groups, except the sublayers VectorCraft writes, marked `data-vc-layer`, and Inkscape sublayers, which open as sublayers in their layer's colour: #372); PDF and PDF-compatible `.ai` in and out (layers, with hidden ones kept hidden with their art and nested ones as sublayers, on pages of up to 64 million operators, art whose layer can't be told going to a hidden, non-printing layer rather than showing or printing: #419; strokes kept live, a fill and a stroke of one outline as one object; a type object's stroke written as each glyph's outline stroked back on the type, so it stays one editable object; lines wrapped in a frame (each wrapped line ending in a space, one left edge, leading and font) back as one area type object, left aligned or justified with its paragraph spacing, where laying it out breaks the lines where the file does; glyphs set apart by gaps wider than a space (a barcode's digit groups) keeping their places; layers stacked as the pages mark them even when one first paints on a later page, art ending a layer's marked content or a clip closing in a later layer kept in its own layer, and layers with no art kept empty: #508; art reaching past a plain PDF's page clipped to its crop box, as PDF viewers show it, each such object in a clip group of its own (a PDF-compatible `.ai` opens whole: #675); a `.ai` on its trim boxes with the bleed boxes round them as the document's bleed, as Crop To › Trim opens a PDF (#1266); masks, editable text with type set along a curve coming back as type on a path, each artboard's art on its own page only, an `.ai`'s white page under its layers left out rather than coming in as art, spot colours, presets, security, marks and bleed, ICC output intents, raster effects, subset fonts, PDF/X, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3). CMYK images keep their ink amounts from PDF import (and from placed CMYK TIFFs and the images in an `.ai` or EPS file's editing data, an alpha channel coming in as a grayscale opacity mask) to PDF export: a CMYK JPEG passes through with its compressed samples unchanged (its `ICC_PROFILE` segments are removed when `output.profiles` is `none` (except in PDF/A, and in PDF/X-3 and PDF/X-4 files that do not write CMYK colors as DeviceCMYK) and in PDF/X-3 and PDF/X-4 when they are the CMYK output intent's profile and CMYK colors are DeviceCMYK), others stay CMYK (DeviceCMYK, or ICC-based CMYK in PDF/X-3/X-4 when not in the output intent's profile) unless the Output settings convert them; the canvas shows them through the working CMYK profile (#320). Overprint is kept from PDF import (opened, the PDF part of an `.ai`, placed) to PDF export: the graphics state's `/OP` and `/op` become the overprint of fills, strokes and type, so a spot colour over a process colour still overprints; a page whose overprint can't be read for certain knocks out with a note, as does `/OPM 0` being read as nonzero overprint (#1388; hand-written fixtures, `pdf/src/tests/import_overprint.rs`). A masked CMYK image (`/SMask`, `/Mask` or a colour key) keeps its inks too, its alpha coming in as a greyscale opacity mask. In imported PDF type, a space glyph the file draws between two words also keeps the next word where the file has it when the gap beside the space is wide, as VectorCraft's own export draws a tracked space: the space gets tracking of its own, and the wrapped lines of a justified paragraph still come back as one area type object when the word gaps on each line are alike (part of #2384). Letter-spaced PDF type, whether set with character spacing (`Tc`) or glyph by glyph, keeps its word spaces and gains none between its letters: the spacing a line's letters share is taken off each gap before a gap reads as a space. That holds on a line that also shows where its words break, with spaces the file draws or gaps wider than the rest; evenly spaced glyphs alone, which could be words of one letter, keep every gap as a space, as do glyphs set more than half an em apart, such as figures in columns. A function-based PDF shading (type 1) whose colour changes along one axis only, as a browser writes a repeating linear gradient, comes in as a linear gradient over its domain, each hard colour change two stops at one offset; one whose colour changes in two directions comes in as its average colour, with a warning. Either paints only over the shading's domain. Both came in as a flat grey that wasn't in the file (#3621). Each such shading is read once per import, and all of them within one budget of 200,000 function evaluations, so a file filling thousands of paths with long functions still opens in about a second (it took minutes); past the budget they come in as their average colour, then grey, with a warning. @@ -1968,6 +2065,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A symbol instance written as its art, and a blend, mesh, repeat, placed document, intertwine or envelope written as a group of its art, likewise still wraps area type by its bounds when the file is opened, as it did before saving, not by the members of that art: the group starts with the same unpainted rectangle, which takes the object's lock and visibility, and the group keeps the object's name and transparency without options of its own. Area type in that art is above the rectangle, so the rectangle does not wrap it. The rectangle takes its place in the object limit before the art; without room for it, the options are left out with the limit's warning. An object without finite bounds keeps the options on its group. This is VectorCraft's own round-trip rule (`crates/eps/src/ai_editing/tests.rs` `live_art_written_as_a_group_keeps_wrapping_by_its_bounds`, `wrap_bounds_of_live_art_fit_the_object_limit_and_leave_area_type_in_the_art_unwrapped`, `live_art_without_bounds_keeps_its_text_wrap_on_the_group`). In a `.ai` or EPS opened from its editing data, type has its text object's opacity, blend mode and knockout shape flag, whether it is made from the file's text document or taken from the page, and type made from the text document takes its text object's lock. Where such type has transparency and comes in with other art (the rest of its look, or page type and strokes that go with it), a group of them has it. Where the page draws its type, or the strokes around it, with transparency that is neither its text object's nor its text object's combined with that of the objects around it, the page's type and strokes keep their own instead (`crates/eps/src/import/tests_native.rs`). Where the page draws type of no text object over text objects made from the text document, with their words in any case, that type is theirs as the page draws it and is left out; the page's other type of no text object goes only to text objects whose type the text document can't make, or else is left out with a warning. `.ai` editing-data import restores the document's listed graphic styles in panel order and links objects that use a listed style; unsupported appearances keep their drawn look (`crates/eps/src/import/ai/tests.rs`). + Swatches › Open Swatch Library › Other Library… lists `.ai` and `.eps` files in its Swatch Libraries filter and loads another document's swatches ([importing swatches from another document](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=134)): its colors, tints, gradients and pattern swatches, in its order and color groups. Adding a pattern swatch from such a library brings the pattern with its tile and art as a pattern swatch, under the library swatch's name and in its color group. A document with no swatches, and a `.ai` or EPS whose swatches are only the default ones, are refused with a message (`cmd::fileio::tests_aiimport::a_swatch_library_in_a_ai_file_lists_and_adds_its_pattern_swatches`, `a_pattern_from_a_ai_library_keeps_a_color_the_library_lacks`, `swatch_library_documents_without_swatches_or_damaged_are_refused`, `cmd::fileio::tests::the_swatch_library_filter_lists_ai_and_eps_files`). A `.ai` or EPS graphic style library, whose editing data holds the styles and their list but no layers, opens with those styles in list order. Other Library… loads another document's graphic styles ([Apply graphic styles](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/apply-graphic-styles.html)) and lists such a library's styles in a library panel. A `.ai` or EPS read as its PDF part or page because its layers can't be used also gets the styles of its list in place of the default ones (`crates/eps/src/import/tests_native.rs`, `cmd::fileio::tests_aiimport::a_graphic_style_library_in_a_ai_file_without_layers_loads_its_styles`). A `.ai` or EPS symbol library, whose editing data holds symbol definitions and their list but no layers, opens with those symbols in list order, each with its registration point. Other Library… in the Symbols panel's Symbol Libraries Menu imports the symbols of the file you pick ([Create or import symbol libraries](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html)) and lists such a library's symbols in a library panel. A `.ai` or EPS read as its PDF part or page because its layers can't be used also gets the symbols defined before its layers (`crates/eps/src/import/tests_native.rs`, `crates/eps/src/import/ai/tests.rs`, `cmd::fileio::tests_aiimport::a_symbol_library_in_a_ai_file_without_layers_loads_its_symbols`). In a large canvas `.ai` or EPS ([Large canvas FAQ](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/start-a-new-file/large-canvas-faq.html)), or a `.ai` whose page is in larger units, opened from its editing data, VectorCraft reads the symbol definitions in the same units as the layers. When the file opens at its full size, each symbol's art, strokes and effects are scaled with the layers, and each instance keeps its own scale and rotation and draws where and as large as before. A new instance comes in at the symbol's full size, the size of an instance at 100% in the file. A symbol library from such a file comes in at the same size, and opacity masks on the layers that don't move with their object are scaled with the layers too. Editing data that VectorCraft wrote keeps its symbols and those masks at their own size, as its `.ai` save writes them (`tests_native::a_large_canvas_eps_keeps_its_symbols_at_the_pages_size`, `a_large_canvas_ai_keeps_its_symbols_at_the_pages_size`, `a_large_canvas_ai_vectorcraft_wrote_keeps_its_symbols_at_their_own_size`, `a_symbol_library_in_larger_units_comes_in_at_the_pages_size`, `build::candidate_tests::scaling_the_symbols_keeps_their_instances_in_place`, `scaling_a_read_document_scales_unlinked_opacity_masks`). @@ -1976,6 +2074,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur `.ai` and EPS editing-data import reads a text document whose keys are written by name, as files saved for version 11 write them, and the keys that later files write by name among the numbered ones (a font record's version, a paragraph's direction). The type of such a file comes from its text document, so type outside the artboards opens and each text object keeps its own story A run that names its paragraph or character style by the style's number takes that style (`a_text_document_with_named_keys_gives_type_off_the_page_too`, `a_text_document_with_named_keys_takes_a_runs_style_by_its_number`, `crates/eps/src/import/ate/names.rs`). In SVG export without Fewer `` Elements, each character of live type that justification or Mojikumi moves (the letter gaps of a Justify All line without word spaces, the gaps between the characters of a justified Japanese line, closed-up punctuation, the space between Japanese and Latin letters) starts its own positioned ``, and type scaled horizontally on a justified line is stretched to its own width (`crates/svg/tests/it/text_layout.rs`). To find those characters, SVG export lays a type object out a second time only when the second layout can differ from the first: point type with Line-end Punctuation Half Width and no Japanese punctuation or letters, the setting new type gets, is laid out once. Exporting 5,000 such objects takes a median of 109.4 ms instead of 171.5 ms on Windows 11, with the same SVG (`crates/svg/src/export/text/tests.rs`). + SVG export lays each type object out once for all of its writers and draws that one layout in each of them (live text, type on a path, outlines, and inside or outside character strokes). Two checks still lay out a changed copy of the type: the check for glyphs hanging outside the brackets of type on a path with Optical Margin Alignment or Roman Hanging Punctuation on, and the advances a reader gives live text when they differ from the drawn layout. The export also groups the glyphs of type written as outlines or with such strokes by run in one pass, with the same SVG. Exporting 1,000 objects of type on a path, 1,000 of bidirectional type and 300 with an outside character stroke lays type out 2,300 times instead of 4,900 and takes a median of 665 ms of CPU time instead of 893 ms over seven runs each, alternating, on Linux; grouping the glyphs of 300 texts of 1,000 runs by run takes 10 ms instead of 190 ms (`crates/svg/src/export/text/tests.rs`). SVG export (live text), legacy `.ai` saves (text objects), DXF export (`TEXT` entities) and the CSS Properties panel write area type that Shrink Text to Fit scales down at the size it draws at, and scale its tracking, kerning, leading and baseline shifts the same way where the format holds them. Legacy `.ai` saves (version 7) write type with rotated characters (Character Rotation, Touch Type turns) as its outlines, with a warning that it is no longer editable text (unless `outlineText` already asks for every type object as outlines): a version 7 text object has no character rotation ([Adobe Illustrator File Format Specification 7.0](https://www.nationalarchives.gov.uk/PRONOM/fmt/423), §15), and the outlines keep each character's rotation, baseline shift and scale (`legacy_ai::tests::type_with_rotated_characters_is_outlines_that_keep_the_rotation`). Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), its discretionary hyphens (`T+`, `T-`) as soft hyphens and its hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` ([file format specification, version 7](https://web.archive.org/web/20050126105313/https://partners.adobe.com/public/developer/en/illustrator/sdk/AI7FileFormat.pdf), §15.4.6.1, §15.4.10.1 and §22.6). A file whose type sets a line breaking value (`TG`) or Japanese layout rules (`Xu`, `Tu`), which VectorCraft doesn't keep, opens with a warning for each (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_line_breaking_and_japanese_layout_rules_are_warned_once`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`). @@ -1991,6 +2090,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur In a `.ai` opened from its editing data, an object in a pattern's art or a brush's art with an art style VectorCraft reads opens as itself with its effects live, as an object on a layer does, and an object in a pattern's art keeps the id of a graphic style in the file's list (`crates/eps/src/import/ai/tests.rs`). A graph in a `.ai` whose records have the shape and values the published version 7 specification gives ([the specification](https://13thmonkey.org/documentation/fonts/AI7FileFormat.pdf), printed pp. 109–112 and 146–158) opens as a live grouped column, stacked column, line or area graph with its saved art, table, axes and settings, and Graph Data edits it ([the help page](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/visualize-data/add-graph-data.html)); other graphs keep their art as plain objects with a note. Saving to `.ai` writes these records for a graph that reads back as the same graph, and warns that any other graph's data and settings aren't written (`crates/eps/src/import/ai/tests.rs`, `crates/engine/src/cmd/graph/tests.rs`). A line graph drawn with Draw Filled Lines, which draws thicker filled lines when the points are connected ([the help page](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/visualize-data/format-columns-bars-and-lines.html)), opens and saves live with its Line Width through the style record's `drawLinesAsShapes` and `lineShapeWidth` (the specification, printed pp. 147–148: points from 0 to 100, ignored when the lines aren't drawn); widths from 0.01 to 100 pt are kept, and a graph with a wider Line Width is saved as its art with the warning. Blends and envelopes in the definitions of a `.ai`'s symbols, patterns and brushes' art count against the same per-file limits on blend layout and envelope checks as the layers' art, so a file with many definitions does not get those limits again for each one (`crates/eps/src/import/ai/read/directives.rs`). + In a `.ai` or EPS opened from its editing data, a Scatter brush's art comes in turned over from its section, as an Art brush's does: each copy draws the side of the section with y up down the page before the copy's rotation. The `.ai` writer writes Scatter art back the same way (`crates/eps/src/import/ai/tests.rs`, `crates/eps/src/ai_editing/tests.rs`). A `.ai` or EPS whose editing data has brushes opens with the file's Calligraphic, Scatter, Art and Bristle brushes in the Brushes panel in place of the default ones, in the file's order: the Calligraphic size, roundness and angle with their variation, the Scatter size, spacing, scatter and rotation, the Bristle settings, and the Scatter and Art brushes' art (Art brushes in the older and newer forms of their objects). A brush library `.ai` (brushes and no layers) opens from its PDF part with its brushes, so Other Library lists them. An Art brush in None or Tints keeps that colorization, and one in the newer form also keeps its fixed width, Flip Along and Flip Across, and Scale Proportionately, Stretch to Fit Stroke Length or Stretch Between Guides with its guides ([Art brush options](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf), printed page 193). Pattern brushes and brushes that can't be read are left out with a note. Paths with a Calligraphic brush, and paths with an Art brush in the newer form that bends art of solid-filled paths with those options, open as the path with the brush on its stroke, except paths whose brush scales its art proportionately. Paths with an Art brush in the older form, and other brushed paths, still come in as their drawn look (part of #372 and #637; `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). In a `.ai` opened from its editing data, a path or type object with Offset Path, Outline Object or Outline Stroke on the whole object opens as itself with those effects live, in their order and shown or hidden; on a fill or stroke of type they stay on that fill or stroke. Offset Path keeps its Offset, Joins and Miter Limit, and Outline Stroke takes its width from the stroke. An Offset Path with a setting missing, out of range or not read keeps the drawn art, as does a path with a Path effect on one fill or stroke (`crates/eps/src/import/ai/style/tests.rs`, `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). In a `.ai` or EPS opened from its editing data, a Scatter brush whose last 15 numbers start with 1 comes into the Brushes panel in Tints, and each brush art section is read without its frame, an unnamed, unpainted rectangle with no settings of its own at the art's bounds (within 1/1000 pt). A wider frame stays in the art, and an art group with a state or look of its own (hidden, locked, isolated, knockout, an opacity, a blend mode, a name, a mask, a note or an appearance) stays a group (`crates/eps/src/import/ai/tests.rs`). @@ -2010,6 +2110,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur In a `.ai` opened from its editing data, Convert to Shape on a whole path or type object opens as a live Rectangle, Rounded Rectangle or Ellipse effect with its Absolute or Relative size, its corner radius, its place among the object's effects and whether it is hidden. A relative size in the file is added to each side. A relative Ellipse, or a setting VectorCraft doesn't read, keeps the drawn art (`crates/eps/src/import/ai/style/tests.rs`, `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). In a `.ai` opened from its editing data, Bas Relief in an art style takes its Detail, Smoothness and Light direction from the style's settings block, and an object other than type with it opens as itself with the live effect. A settings block that VectorCraft can't read (malformed, another effect's, a value out of range or a key it doesn't know) keeps the object's drawn look (part of #637; [raster effects reference](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/raster-effects-reference.html), [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), [scripting the filter gallery](https://community.adobe.com/questions-712/scripting-support-for-the-filter-gallery-1064646); `crates/eps/src/import/ai/style/tests.rs`, `crates/eps/src/import/ai/tests.rs`). PDF export and `.ai` saves write a page with a side longer than 14,400 pt with a `UserUnit` (PDF 1.6), its longer side divided by 14,400 and rounded up to the next thousandth, so that no side is longer than 14,400 units (ISO 32000-1, Annex C.2); a PDF 1.5 file with such a page is written as PDF 1.6 with PDF 1.5's encryption, PDF/X files and PDF 1.3 and 1.4 files write it in points (in PDF 1.3 and 1.4, a page past 32,767 pt that needs a real number past 32,767 is refused with an error naming it), a page whose short side is 3 pt or longer but would be under 3 units at that `UserUnit` gets a smaller one that keeps the short side at 3 units, and the export's warnings give each such page's size and how it is written (#6382). The Save PDF dialog's "Write pages longer than 200 in at full size in points" (`longPagesInPoints`, on by default; `.ai` saves leave it off) writes such pages in points without a `UserUnit` at every PDF version, in files without a PDF/X or PDF/A standard, so readers that ignore `UserUnit` show them at full size. + Raster export dialogs retain supplied values for their controls, including PNG resolution, background, anti-aliasing and interlacing, and JPEG quality. Omitted values use the dialog defaults; a nonpositive resolution is rejected on confirmation (#8324; `crates/ui-egui/src/dialogs/tests_raster_supplied_options.rs`). Export As PDF with Use Artboards off also opens the Save PDF dialog, without its Artboards section, and writes one page of the visible art's bounds with the dialog's options (`document.exportPdf {useArtboards: false}`; `crates/ui-egui/src/dialogs/tests_export.rs`, `crates/engine/src/cmd/fileio/tests_pdf.rs`). While Alt (Option on macOS) is held, the Save PDF dialog's Cancel button reads Reset, which puts every option back to the chosen preset's settings, passwords included, and leaves the dialog open; letting the key go shows Cancel again (`ui.dialogReset`). [The help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=283) says that holding Alt or Option and clicking Reset returns the options to their defaults. Resetting to the chosen preset's settings, and keeping the preset, path, artboard range and section, are VectorCraft's own rules (`crates/ui-egui/src/dialogs/save_pdf/tests.rs`, `crates/ui-egui/src/dialogs/tests.rs`). `document.exportSelection` run without params (a shortcut) takes the same route after its save panel: a picked PDF opens the Save PDF dialog without its Artboards section, and SVG, the raster formats, EPS, DXF, text and exporter plug-ins with parameters open their options, whose OK writes the selection alone, cropped to it, with the chosen options (`crates/ui-egui/src/dialogs/tests_export_selection.rs`). @@ -2073,18 +2174,22 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - DXF control-point SPLINE import honors its closed flag (#1299 follow-up after #1320 fixed export), including rational curves; open curves whose endpoints meet stay open. Own-fixture regressions cover controls/knots, fit-point fallback and all export versions (`crates/cad/src/import/tests.rs`, `crates/cad/src/tests.rs`); native save/read checked. Circular cubic paths export as native CIRCLE/ARC where stroke semantics permit; R12 weighted strokes remain POLYLINE; a closed four-cubic ellipse, or a circle scaled out of proportion, exports as a native ELLIPSE in R13 and later (an ellipse whose minor-to-major ratio is below 1e-6 is still written as a polyline or spline), and R12 keeps the existing fallback (`crates/cad/src/tests.rs`); an open path of one straight segment exports as a LINE (R12 to R14 strokes with a weight stay polylines, which carry the width) and reads back as the same segment (`crates/cad/src/tests.rs`, `crates/cad/src/import/tests.rs`); DXF Options' Preset menu and `document.exportDxf`'s `dxfPreset: "cnc"` set the CNC / CAM options (version 2000, 1 mm = 1 unit, 256 colors, Maximize Editability with Alter Paths off, Outline Text, placed images and fill hatches left out), and the menu shows Custom once a field changes (`the_cnc_preset_writes_version_2000_in_millimeters_with_type_as_paths_and_strokes_as_lines`, `the_cnc_preset_sets_the_options_that_are_not_given`, `the_cnc_cam_preset_sets_the_fields_and_a_change_shows_custom`); VCarve QA remains pending. - DXF export's Include Placed Images and Include Fill Hatches (`includeImages`, `includeHatches`; VectorCraft's own options, on by default and off in CNC / CAM) leave out placed images with their linked files, without decoding them, and the solid hatch after each filled area's outlines, each on its own, with one note in `warnings` when something was left out; R12 keeps its own notes. An open path's fill outline is closed, as the fill is, in every version (`an_open_path_s_fill_outline_keeps_its_closing_edge`, `fills_without_hatches_keep_their_outlines`, `images_can_be_left_out_with_their_files`, `images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both`, `placed_images_and_fill_hatches_can_be_left_out`, `include_placed_images_and_fill_hatches_follow_the_preset_and_a_change_shows_custom`). - DXF export writes a path of straight segments and circular arcs (a slot, a D shape, a rounded rectangle, a pie) as one polyline whose vertices carry a bulge (group 42) for each arc: an LWPOLYLINE in R14 and later, a POLYLINE with VERTEX entities in R12 and R13, closed when the path is closed, and it reads back as the same outline (#1299, `crates/cad/src/tests.rs`). Such a path was written as one SPLINE (a flattened polyline in R12); a path with any other curve still is. A shallow curve becomes an ARC or a bulge only when it lies on the circle within 5e-4 of its own extent as well as of the radius, and the drawing extents (`$EXTMIN`, `$EXTMAX`) reach the furthest points of every ARC and bulge. + - DXF export with Use Artboards applies live effects and places symbols' art once for all the artboards' drawings instead of once for each drawing; each drawing's bytes, linked images, warnings and notes are the same as before (`drawings_apply_the_live_effects_once_and_match_drawings_written_alone`, `each_artboard_s_drawing_is_the_drawing_of_that_artboard_alone`). - Affinity documents in (AF.1–AF.4): `.af` (Affinity 3) and `.afdesign`/`.afphoto`/`.afpub` (Affinity 1 and 2, container versions 8–12) open and place as editable art: layers and sublayers, groups (pass-through or isolated), artboards (with their names and backgrounds) and Publisher pages side by side, curves with live corners, parametric shapes (rectangles with corner radii, ellipses, polygons, stars, pies, triangles, trapezoids), compound shapes, solid/linear/elliptical gradient fills and strokes (weight, dashes, alignment, scale-with-object), clipping by nesting, vector and pixel masks, artistic and frame text with fonts, sizes, tracking, leading and alignment, placed images (their original JPEG/PNG) and pixel layers (8/16-bit RGB, CMYK), opacity, visibility, locking and blend modes, at the document's resolution in points. Effects, adjustments, brushes and pressure profiles, transparency gradients, master pages, symbol instances (imported as their cached picture), special shapes (cloud, heart, cog…, imported as ellipses) and Affinity-only blend modes are named in the import warning. A file whose native data can't be read opens as its embedded preview with the reason, and that preview can't be placed. Save never writes back over the Affinity file and there is no Affinity export. AF.5 (from DesignCraft's import, storytold/designcraft#291) adds master pages (on a locked layer behind the pages that show them), tables (area type per cell and a line per edge), each paragraph's alignment, indents, spacing and leading, horizontal text scale, outlined text, frame text sized by its text scale, drop shadows and outer glows as live effects (inner shadows as inner glows), outline effects as strokes, colour and gradient overlays baked into the paint, embedded Affinity documents as editable content (their artboards don't become artboards), pixel layers over 64 MP at a reduced resolution and HEIC photos from their stored pixels; automatic leading (size plus the font's line gap) fitted on thumbnails; underlines and strikethrough; strokes whose style is None (every shape stores one) left out, which also brings 6 public files closer to their thumbnails; line breaks inside a paragraph; table cell text centred as Affinity centres it, also where it is taller than its cell; CMYK pixel layers converted through the document's embedded CMYK profile (relative colorimetric with black-point compensation, as each layer's colour settings name), or kept as CMYK images when there is none; outline effects on stroked shapes around their stroke; artistic text whose paragraphs align differently aligned within its longest line, a frame's first baseline at cap height, and frames whose last lines' descenders hang out made tall enough to show them (all measured on a local document's own PDF export: baselines match to 0.1 pt); a local 56-artboard document's mean thumbnail difference went from 16.2 to 11.4, and its pages' mean difference from the owner's PDF export from 12.9 to 9.3. AF.4 adds Affinity 3 artboard recognition and actual-outline clipping, source-backed JPEG/PNG raster tiles, Unicode text-run recovery, stored fallback/exact installed fonts, OpenType feature flags and compound-geometry limits. 51 public CC0/MIT/Apache-2.0 files (33 current `.af`), pinned and sha256-verified (`cargo xtask corpus --affinity`), test native retention and every-board native/SVG/PDF/PSD output for current files; selected files compare their saved thumbnails. No Affinity reopen or independent paired PSD oracle was available; [source audit and complex-font gaps](affinity-validation.md); [scope, provenance and limits](../crates/affinity/README.md). - Placed documents: File › Place of a `.vectorcraft` file links to it by default (`file.place`'s `link`): one locked object showing an artboard of the document (or its art's bounds), read the way placing it without Link reads it, its symbols, patterns and images kept apart from the document's; without Link (or from bytes, not a file) it is an editable copy as before. It stays vectors in every output (SVG, PDF, EPS, EMF, DXF), and so do placed documents inside it, read from their own files up to 8 levels deep (documents that place each other stop there). On screen they draw from bitmaps cached per file and zoom step, shared by every copy and made in the background (a placeholder until ready), so a sheet of them redraws in about a millisecond; exports and prints draw them exactly. Like linked images, a save keeps only a preview of each (JPEG when opaque) unless Include Linked Files; output, and zooming past the preview, read the file again, falling back to the preview with a warning when it is gone or changed. Saves for older versions write them as plain art. Links check, update, relink, Update Links on open, Link Info (the artboard's size), Placement Options, Break Link (also Embed, Object › Expand: the editable copy placing without Link gives, its resources joining the document), Edit Original (the document in a new tab) and the Links panel cover them; saving a document updates the open documents that place it. The native format (v4) keeps data of 8 KB or more after the JSON instead of base64 in it. - Placed documents' bitmaps on screen: when a bitmap made in the background is ready, the desktop app renders the canvas again only where the objects that show its file are, when the frame shown was rendered on the UI thread and that part is at most half the canvas. Bitmaps drawn or made since a frame began are kept for that frame past the 512 MiB budget, up to 2 GiB, so a view showing more than the budget does not make them again in every frame. A bitmap that would take them past 2 GiB is not kept, and its file draws exactly at that zoom. A bitmap that can't be made (the file can't be read and there is no preview) shows the light placeholder and is not asked for again. Each ready bitmap used to render the whole canvas again, and bitmaps past the budget and bitmaps that could not be made were asked for again in every frame (`crates/render/src/tests/placed_document.rs`). - Linked PDF and `.ai` pages: File › Place with Link (the default) places a page of a PDF, `.ai` or `.ait` file read as PDF pages as a placed document, as it links an image, the page and its box (`crop`) kept with the link: Links check, update and relink it, Break Link and Object › Expand give the group placing it without Link gives, every output draws the page's vectors, and Package copies the file. Without Link, or with a password or `textAs: "outlines"`, the page is embedded. An EPS file, a PostScript file or a PostScript `.ai` placed from a file with Link is a placed document the same way, showing the art placing it without Link gives (clipped to its bounding box, or its art's bounds with `crop: "bounding"`); Links lists it as `EPS` or `PostScript`, and a save, Package, Break Link and Object › Expand treat it as they treat a placed PDF page. Package also copies the files that the native document of an EPS file written by VectorCraft links, beside the EPS file's copy, which finds them there by name. Placing one keeps the file linked rather than embedding it, as [the help page](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/eps-and-dcs-file-import-in-illustrator.html) describes; a DCS file stays a linked image (`crates/engine/src/tests/placed_document.rs`, `crates/engine/src/tests/package.rs`). + - File › Open's Import PDF dialog checks Import PDF pages as links when All is picked and clears it when Range is picked: every page of a PDF opened from its file opens linked unless the box is cleared, and a range of pages opens as art unless the box is checked ([the help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=444)). A box checked or cleared by hand keeps that state until the other of All and Range is picked; picking the one already picked, or editing the range, does not change it, and `ui.dialog.set` of `allPages` changes it as the buttons do (VectorCraft's own rules). A file opened without its path, with a password or over the 256 MB that linked pages take still opens its pages as art. The box used to start cleared for All as well (`crates/ui-egui/src/dialogs/tests_import_pdf.rs`). - The place cursor keeps an encrypted PDF, `.ai` or `.ait` file, at a letter page's size (VectorCraft's own size) and without a thumbnail, and a click or drag on it asks for its password, with the Place dialog's Show Import Options on or off; such a file was left out of the cursor before (`crates/engine/src/tests/place.rs`, `crates/ui-egui/src/tests/place.rs`). - File › Place with Bounding Box (`file.place {crop: "bounding"}`) measures the art that shows, with its strokes and effects, as an export does: hidden objects, guides and template layers do not count, a group whose only part on the page or artboard is hidden is not placed, and symbol instances are measured by their art, for `at`, `rect`, the place cursor and `file.place.info` (`crates/engine/src/tests/place.rs`). - The Place dialog has a Show Import Options checkbox after Link, Template and Replace ([Place multiple files in a document](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/place-multiple-files-in-a-document.html)). On (VectorCraft's default, saved with the preferences), each PDF, DXF or text file asks for its import options before it is placed, also in the place cursor; off (`file.place {showImportOptions: false}`), it is placed with the options last confirmed for its format, and only an encrypted PDF asks, for its password. Text Import Options now starts from the options confirmed last (`crates/ui-egui/src/tests/place.rs`). + - Text Import Options' Character Set offers Shift JIS, GB2312, Chinese Big 5, Cyrillic, GB18030, Greek, Turkish, Baltic and Central European beside Unicode and ANSI, the plain-text encodings [the help page](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/import-and-export-text.html) lists for placed text. `file.place {text: {characterSet}}` decodes each with its WHATWG Encoding Standard decoder. The mapping is VectorCraft's own: GB2312 reads as GBK, Cyrillic as windows-1251 (x-mac-cyrillic with `platform: "mac"`), and Greek, Turkish, Baltic and Central European as windows-1253, 1254, 1257 and 1250 on both platforms. A byte-order mark is read as ordinary bytes, a malformed sequence as U+FFFD, and the last set confirmed is remembered (`crates/engine/src/tests/textimport.rs`, `crates/ui-egui/src/dialogs/text_import.rs`). - A Shift-click with the loaded place cursor opens the current file's import options (text, DXF, PDF page or embedded PSD) and OK places it at the click, with Show Import Options on or off and for a cursor loaded by `file.place.queue` ([Place multiple files](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf)). VectorCraft's own rules: a file without such a dialog places as a click does, Cancel leaves the file unplaced, a Shift-drag places at the dragged size, and headless the Shift-click places as a click (`crates/tools/src/place.rs`, `crates/engine/src/tests/place.rs`, `crates/ui-egui/src/tests/place.rs`). - Separations Preview shows placed and embedded raster images on the visible plates, as it shows vector art (#4153): an RGB image's pixels are separated into process inks with the proof setup's intent, a CMYK image shows its own inks, a hidden plate's ink leaves the image, and with one plate visible the image shows that plate's ink as a grey. Raster images carry no spot ink, so a spot plate shown alone shows them as paper; a colorized image shows its color's plates. Emoji and other bitmap glyphs follow the same rule. The plate-filtered pixels and their reduced-size copies are kept apart from the image's own pixels, for each set of visible plates, proof setup and color settings, and with the preview off nothing changes. Evidence: `tests::colorize::separations_preview_shows_an_rgb_images_process_inks`, `separations_preview_shows_a_cmyk_images_own_inks`, `separations_preview_keeps_an_images_pixels_per_plate_set`. Print preview fidelity remains the open gap, so scores and hours are unchanged. + - In the Separations Preview panel, an Alt-click (Option-click on macOS) on the eye of the plate shown alone shows every plate again, spot plates included, as [the help page](https://helpx.adobe.com/illustrator/using/printing-color-separations.html) describes for a second modified click on the eye (`view.separationsPreview {soloToggle: plate}`); an Alt-click on a plate shown among others shows only that plate, as the help page describes for the first one. VectorCraft's own rules: an Alt-click on a hidden plate, on another plate while one shows alone or while no plate is shown shows only that plate, and `only` still shows just the named plate when repeated (`crates/engine/src/tests/colormgmt.rs`, `crates/ui-egui/src/panels/separations.rs`). - Desktop print transport uses `craft-print` for CUPS and modern Windows. Sheet composition, copies, separations and colour management remain in VectorCraft. The Print dialog's Media list also carries the Japanese papers — JIS B4 257 × 364 mm, JIS B5 182 × 257 mm and JIS B6 128 × 182 mm beside the ISO B4/B5 (250 × 353 and 176 × 250 mm, kept so settings and presets saved before them keep their paper), and はがき 100 × 148 mm, 往復はがき 148 × 200 mm, 封筒 長形3号 120 × 235 mm, 長形4号 90 × 225 mm, 角形2号 240 × 332 mm, 角形3号 216 × 277 mm and 四六判 127 × 188 mm; the JSON id or the dialog label names a paper, any case and spacing (`B5 (JIS)` or `b5jis`) (`crates/pdf/src/print/settings.rs`, `crates/pdf/src/tests/print.rs`). The print-preview and physical-device fidelity gaps remain, so print scores and hours are unchanged. - The Print dialog's Document Ink Options list shows an icon before each spot ink's name, and a click on it prints that one ink as process inks (on the Cyan, Magenta, Yellow and Black plates, with no plate of its own) or as a spot ink again, as [the help page](https://helpx.adobe.com/illustrator/using/printing-color-separations.html) describes for single spot colors. Other spot inks keep their plates, and spot gradient stops and DCS images' spot plates follow each ink's choice (`print.setup {settings: {output: {inks: [{name, convertToProcess: true}]}}}`, kept with the document and in print presets; `print.preview` lists every ink as `documentInks`). These are VectorCraft's own rules: Convert All Spot Colors to Process converts every spot ink and dims the icons while keeping each ink's own choice, a converted ink's Print, Frequency and Angle are dimmed and kept, and process inks and Registration have no icon. Evidence: `print::one_spot_ink_converts_to_process_and_the_others_keep_their_plates`, `print::converting_every_spot_ink_overrides_and_keeps_each_inks_own_choice`, `print::a_spot_gradient_stop_prints_its_process_plates`, `cmykimages::a_dcs_image_converts_only_the_spot_ink_chosen`, `tests::print::a_spot_ink_converted_to_process_is_saved_and_listed_without_a_plate`, `dialogs::tests_print::a_spot_inks_icon_converts_it_to_process_and_back`. Print scores and hours are unchanged. - - The Print dialog's Output section has Overprint Black under Convert All Spot Colors to Process, off by default and available with Separations ([Print color separations](https://helpx.adobe.com/illustrator/using/printing-color-separations.html) lists it among the separation options): black art then leaves the inks under it on the other plates (`print.setup {settings: {output: {overprintBlack: true}}}`, kept with the document and in print presets). Solid 100% K or 100% gray fills, strokes and characters (to within half a percent, as Edit › Edit Colors › Overprint Black counts them), and gradients whose every stop (every color point of a freeform gradient) is, overprint; rich, RGB, Lab, spot-linked and lighter blacks are not marked, paints already set to overprint keep that setting, and only the printed copy is marked. These limits are VectorCraft's own rules. Characters set to overprint now also leave the inks below them on printed PDF plates, a type object's own fill in a PDF is drawn with its blending mode, and Edit › Edit Colors › Overprint Black counts a gradient with a stop linked to a spot swatch as a spot black, as it counts a solid one, and a freeform gradient by the color points it draws from. On a plate, an overprinting paint that puts none of that plate's ink down is drawn as nothing; on PostScript plates so is up to half a percent of another ink in a color that counts as black, and any other faint ink stays on the plate. Evidence: `print::overprint_black_keeps_the_inks_under_solid_black_on_separations`, `print::overprint_black_keeps_the_cyan_under_near_and_freeform_blacks_on_postscript_plates`, `print::overprinting_paints_keep_their_faint_ink_on_postscript_plates`, `print::overprinting_type_leaves_the_inks_below_on_separations`, `print::a_type_objects_own_black_fill_overprints_on_separations`, `tests::print::overprint_black_is_saved_with_the_setup_and_in_presets`, `overprint::tests::a_gradient_with_a_spot_linked_stop_is_black_only_with_spot`, `overprint::tests::a_freeform_gradient_is_black_when_every_point_is`. Print scores and hours are unchanged. + - The Print dialog's Output section has Overprint Black under Convert All Spot Colors to Process, off by default and available with Separations ([Print color separations](https://helpx.adobe.com/illustrator/using/printing-color-separations.html) lists it among the separation options): black art then leaves the inks under it on the other plates (`print.setup {settings: {output: {overprintBlack: true}}}`, kept with the document and in print presets). Solid 100% K or 100% gray fills, strokes and characters (to within half a percent, as Edit › Edit Colors › Overprint Black counts them), and gradients whose every stop (every color point of a freeform gradient) is, overprint; rich, RGB, Lab, spot-linked and lighter blacks are not marked, paints already set to overprint keep that setting, and only the printed copy is marked. These limits are VectorCraft's own rules. Characters set to overprint now also leave the inks below them on printed PDF plates, a type object's own fill in a PDF is drawn with its blending mode, and Edit › Edit Colors › Overprint Black counts a gradient with a stop linked to a spot swatch as a spot black, as it counts a solid one, and a freeform gradient by the color points it draws from. On a plate, an overprinting paint that puts none of that plate's ink down is drawn as nothing; on PostScript plates so is up to half a percent of another ink in a color that counts as black, and any other faint ink stays on the plate. A black linked to a swatch the document lacks separates from its own values, so on PostScript plates it counts as an unlinked black (VectorCraft's own rule). Evidence: `print::overprint_black_keeps_the_inks_under_solid_black_on_separations`, `print::overprint_black_keeps_the_cyan_under_near_and_freeform_blacks_on_postscript_plates`, `print::overprint_black_keeps_the_cyan_under_a_near_black_linked_to_a_missing_swatch_on_postscript_plates`, `print::overprinting_near_blacks_linked_to_a_missing_swatch_keep_the_cyan_on_postscript_plates`, `print::overprinting_paints_keep_their_faint_ink_on_postscript_plates`, `print::overprinting_type_leaves_the_inks_below_on_separations`, `print::a_type_objects_own_black_fill_overprints_on_separations`, `tests::print::overprint_black_is_saved_with_the_setup_and_in_presets`, `overprint::tests::a_gradient_with_a_spot_linked_stop_is_black_only_with_spot`, `overprint::tests::a_freeform_gradient_is_black_when_every_point_is`. Print scores and hours are unchanged. - The Print dialog's General section (and the print preset editor) has a link button after Scale W and H, as the Custom scale has one on [the help page](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/print-documents-in-illustrator.html), where turning it off scales the width and height apart. While it is on, typing either percentage sets the other, and turning it on sets H to W. It is on for new settings, dimmed with the fields unless Scaling is Custom or a tiling choice, toggled with a click, Space or Enter, and named with its on or off state for screen readers. W and H take 1–1000% in the fields. The link is kept with the document's print settings and in print presets (`print.setup {settings: {scale: {linked}}}`); settings saved without it read it as off, so they print as before. Its default, the tiling choices and the agent rules are VectorCraft's own. Evidence: `print::the_scale_link_is_on_for_new_settings_and_off_for_a_saved_scale_without_it`, `tests::print::the_scale_link_keeps_width_and_height_equal`, `tests::print::a_scale_saved_without_the_link_keeps_its_width_and_height`, `dialogs::tests_print::the_scale_link_keeps_scale_width_and_height_equal`, `dialogs::tests_print::a_print_preset_keeps_the_scale_link`. Print scores and hours are unchanged. - A PDF, PDF-compatible `.ai` or `.ait` opened from its pages or its editing copy opens with the File Info that its XMP packet and its document information dictionary give: the title (`dc:title`, its `x-default` item first, else Info `Title`), the author, description, keywords, copyright status, notice and URL, and the created and modified dates, the XMP packet's value where both give one (`crates/pdf/src/tests/file_info.rs`, `crates/engine/src/tests/fileinfo.rs`). An SVG opens with the title of its root ``. The title is File Info's alone (`DocMetadata::title`): the document's name stays the file's name with its extension, a file that gives no title leaves File Info with that name, and exports (PDF, SVG, PNG, EPS, `.ai`) and native saves carry it; changing the title in File Info sets the document's name as before (#3626). - PDF export and PDF-compatible `.ai` and `.ait` saves write the document's File Info created date as the file's creation date, or the time of writing when the document has none, and the time of writing as its modification date; the page information mark still prints the time of writing (`crates/engine/src/tests/fileinfo.rs`, `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/marks.rs`). @@ -2108,7 +2213,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - File › Revert also drops what was started for the content it discards: a file being read for Place, for the place cursor or dropped on the canvas, a bitmap being read for Paste, and a paste waiting at its Swatch Conflict dialog are not placed or pasted in the reverted document, and the status bar says the document was reverted. Edits made while a file is read, a Revert that fails or that a batch rolls back, and a Revert of another document leave the read to finish as before (`crates/ui-egui/src/placing/tests.rs`). - The pixels of a PNG, JPEG, GIF or WebP file that Place decodes to check them are kept in the image store the renderers share, so the canvas's first frame with the placed image draws them without decoding the file again on the UI thread: File › Place, a file dropped on the canvas, a click or drag of the place cursor, `file.place`, and Paste of such an image. A CMYK JPEG is still decoded when it is first drawn (`crates/ui-egui/src/placing.rs`, `crates/render/src/tests.rs`). - A photo whose EXIF orientation turns or flips it (a camera held upright or upside down) is placed and opened upright, as it was taken; the image is stored as it is seen (#4284). A quarter turn swaps the resolution's axes, so the image keeps its physical size. TIFFs read without the image decoder (grayscale with extra channels, CCITT Group 3, CMYK with one plane per ink) follow their Orientation tag too, and a turned CMYK JPEG or TIFF keeps its inks, at the 8 or 16 bits the file has, as a CMYK TIFF. - - PDF export writes a CMYK image that keeps its numbers in an `ICCBased` color space holding, byte for byte, the CMYK profile the image carries (a CMYK TIFF's tag 34675, or a CMYK JPEG's `ICC_PROFILE` APP2 segments) when `output.profiles` is `all` or `taggedSource`, and in PDF/A-2b, PDF/X-3 and PDF/X-4 unless it is `destination` ([the help page](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/pdf-marks-bleeds-and-color-output-options.html)). This covers a CMYK JPEG embedded as it is, one the Compression settings resample or compress again, a TIFF written again, and an image written with its mask as its soft mask. With `none`, and in PDF/X-1a, the image is DeviceCMYK and a JPEG's own profile is left out, so PDF/X-1a export writes a CMYK JPEG that carries a profile. Pixels the Output settings convert are never tagged with the profile of their old numbers. A profile tags an image only when its size, signature, class, CMYK color space and tag table are well formed and it is at most 16 MiB (VectorCraft's own limit). Transparency in a tagged CMYK document blends in the document's CMYK profile; when the file holds no space of that profile it blends in DeviceCMYK, or keeps its RGB space in PDF/A, and never in an image's own profile (`crates/pdf/src/tests/cmykimages.rs`, `export::writer::tests`). + - PDF export writes a CMYK image that keeps its numbers in an `ICCBased` color space holding, byte for byte, the CMYK profile the image carries (a CMYK TIFF's tag 34675, or a CMYK JPEG's `ICC_PROFILE` APP2 segments) when `output.profiles` is `all` or `taggedSource`, and in PDF/A-2b, PDF/X-3 and PDF/X-4 unless it is `destination`, except in PDF/X-3 and PDF/X-4 when that profile is the CMYK output intent's, or when `none` makes every CMYK color DeviceCMYK, which it does only without a CMYK destination of another profile (#1954) ([the help page](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/pdf-marks-bleeds-and-color-output-options.html)). This covers a CMYK JPEG embedded as it is, one the Compression settings resample or compress again, a TIFF written again, and an image written with its mask as its soft mask. With `none`, and in PDF/X-1a, the image is DeviceCMYK and a JPEG's own profile is left out, so PDF/X-1a export writes a CMYK JPEG that carries a profile. In PDF/X-3 and PDF/X-4 with `none` and a CMYK destination of another profile, a CMYK image that keeps its numbers keeps its own profile, and one the conversion changes is untagged. Pixels the Output settings convert are never tagged with the profile of their old numbers. A profile tags an image only when its size, signature, class, CMYK color space and tag table are well formed and it is at most 16 MiB (VectorCraft's own limit). Transparency in a tagged CMYK document blends in the document's CMYK profile; when the file holds no space of that profile it blends in DeviceCMYK, or keeps its RGB space in PDF/A, and never in an image's own profile (`crates/pdf/src/tests/cmykimages.rs`, `export::writer::tests`). - When the Output settings convert an image's colors ([the help page](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/pdf-marks-bleeds-and-color-output-options.html)), PDF export leaves out an image whose pixels can't be decoded or written in the destination's colors, with the warning "an image couldn't be converted to the Output destination and is missing from the picture", in every standard, instead of writing it in its own colors. This covers a CMYK image with more than 2^26 pixels, the most VectorCraft reads CMYK inks for, and a color image that could be embedded as it is but is more than VectorCraft decodes. A color image whose pixel data can't be read is left out with the warning "an image couldn't be decoded and is missing from the picture", as without a conversion. Gray images, whose pixels are not converted, images in a file that converts no colors, and a gray or RGB image that an sRGB destination would convert from its ICC profile (it keeps the profile, with a warning) are written as before, and an image that can't be written at all still gets the warning that it couldn't be decoded (`crates/pdf/src/tests/cmykimages.rs`, `crates/pdf/src/tests/compression.rs`). - PDF export with `output.profiles` set to `none` (Don't Include Profiles) writes no image with the ICC profile it carries, as [the help page](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/pdf-marks-bleeds-and-color-output-options.html) describes for that setting: gray and RGB PNG, JPEG and TIFF images embedded as they are, resampled or compressed again, and CMYK JPEG images. A JPEG kept as it is loses its `ICC_PROFILE` APP2 segments, its other segments and compressed samples unchanged. PDF/A-2b, PDF/X-3 and PDF/X-4 files keep the profiles they tag images with. Left unset (the default, `"default"`, listed as Default in Save PDF), the setting writes device colors while gray and RGB images keep their profiles, as before; that default is VectorCraft's own rule (`a_set_dont_include_profiles_removes_image_profiles`, `a_set_dont_include_profiles_takes_a_cmyk_jpegs_profile_out`). - PDF import keeps the CMYK profile of an image in a four-component `ICCBased` color space, whose stream holds the profile ([ISO 32000-1, §8.6.5.5](https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf#page=157)), byte for byte with the image's ink amounts, so PDF export can write the image in it again. A CMYK TIFF carries it as tag 34675, whatever the image's Decode array and bit depth ([ICC.1:2010, Annex B](https://www.color.org/specification/ICC1v43_2010-12.pdf)). A CMYK JPEG kept as it is carries it in `ICC_PROFILE` APP2 segments in place of a profile of its own, with its compressed samples unchanged, and one whose segments can't hold it is stored as a CMYK TIFF carrying it. A profile that isn't well formed, isn't of CMYK colors or is over 16 MiB (VectorCraft's own limit) leaves the image's inks as they are, untagged. DeviceCMYK and DeviceN images carry no profile, and a CMYK TIFF's tag 34675 is read up to 16 MiB. EPS and PostScript import does not keep one: PostScript defines no `ICCBased` profile stream (`crates/pdf/src/tests/cmykimages.rs`, `cmyk::tests`). @@ -2122,6 +2227,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - An image that SVG import stores again as PNG keeps the ICC profile its TIFF, PNG, JPEG or WebP file carries, as Open and Place keep it, as a PNG `iCCP` chunk, when the profile's color space is the stored samples': gray for gray samples, RGB for RGB ones (). By default, SVG reads an image's colors in the profile built into the image (). A profile of another color space, one too short to be a profile, and the profile of a TIFF whose pixels its own reader converts to RGBA (one with an alpha or other extra channel, or CCITT Group 3) are left out, and the image is still imported (`a_raster_written_again_as_png_keeps_its_icc_profile` in `crates/svg/tests/it/image_orientation.rs`). - SVG import leaves out an SVG shown as an image that it can't read (text that isn't XML, an SVG without a size) and goes on with the images after it, as SVG 2's error processing describes (). Only images that decode count toward the 256 nested SVG images an SVG may show, so an image after many broken ones is imported. Every nested SVG image read, decoded or not, counts toward VectorCraft's own limits of 1,024 reads and 512 MB of text per import; past them, nested SVG images are left out with a warning (`crates/svg/tests/it/import_details.rs`). - SVG import decodes each image data URL (RFC 2397, ) of an `` or `` once, in the imported SVG and in the SVGs shown as its images, however many `` elements, filters or SVG images show it; every use gets the same image. The data URLs of one import decode to at most 512 MB together, VectorCraft's own limit: decoding stops where a URL would pass it, and that image is left out with a warning (`crates/svg/src/import/files.rs`, `crates/svg/tests/it/import_details.rs`). + - SVG import hashes the bytes of each raster image for its image key once per import, however many `` elements or `` elements with the same data URL or linked file show them; the other images get the same key, and the keys, stored images and links are the same as before. With one 3.4 MB PNG data URL shown by 500 `` elements, importing took a median 1,883 ms of thread CPU time when every image was hashed and 28 ms with the keys kept, on Linux with other builds running (`crates/svg/src/import/importer.rs`). - SVG import measures what an SVG expands to before the SVG reader builds it: every copy a `` shows (), chains of ``s included, and the style values each copy gets from its `style` attribute and from the style sheet rules that match it. An SVG that expands to more than 999,999 elements (500,000 on the web) or to more than 64 MB of copied style values is refused with an error, and so is a loop of `` references that would be copied without end. The declarations the import's own style cascade keeps count toward the 64 MB too, once for each element a rule matches, including those of rules the reader drops, such as ones with `:not()`. Matching the style sheets' selectors against those elements may take at most 50,000,000 tests; past that the SVG is refused, so a selector that never matches can't keep the import busy. These limits are VectorCraft's own. An SVG shown as an image, from a data URL or a linked SVG file, counts toward the same limits as the SVG showing it, and one past any of them refuses the whole import (`crates/svg/src/import/budget.rs`, `crates/svg/tests/it/import_details.rs`). - SVG import reads the files that a linked SVG file's own `` elements link to, relative paths from that file's folder (), as it reads the imported SVG's links: a raster stays linked, an SVG file imports as vector art, and one that can't be read gets the placeholder, its link and a warning. SVG 2 tells a viewer not to load these links (); reading them is VectorCraft's own rule. The same href in SVG files of two folders names two files. A link that leads back to an SVG file showing it gets the placeholder and a warning, and reading the links of linked SVG files stops at the nesting depth cap and at 1,024 reads and 512 MB per import, the same limits decoded nested SVG images have, counted separately from them. The text of every linked SVG file read counts, and so does every file read for the links of a linked SVG file, raster or SVG; rasters the imported SVG links to don't. Once either limit is passed, no file linked from a linked SVG file is read and its image is left out with a warning, and an SVG file the imported SVG links to is still shown, without the files its own links name, with a warning. Another href to an SVG file already read, spelled differently or in another SVG file, does not read it again, unless a link back or the depth cap changes what it shows there (`crates/svg/tests/it/import_details.rs`, `crates/svg/src/import/files.rs`). - File › Place and a file dropped on the canvas refuse a PNG, JPEG, GIF or WebP file whose pixels can't be read, such as one cut short by a download or a sync still running, and the status bar shows "Couldn't place : the image's pixels can't be read". Paste and Relink refuse such an image too, and Update Links, or Open when it reads the file again, counts it as missing. A JPEG cut short still places when its pixels can be decoded (`file.place`, `crates/engine/src/tests_place.rs`). @@ -2136,6 +2242,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Missing linked files can be looked for in a folder and its subfolders: Find in Folder… in the Linked File Not Found dialog and in the Links panel menu lists the files with each one's name, those with the size and contents saved with the link first, and relinks the files chosen, copying an image's file into the document's folder when asked, without replacing a file there (`links.findFiles`, `links.relink {copy}`). In the Links panel it looks for the selected linked files when any are selected. - The Links panel's Relink… opens a Relink dialog whose Replace menu picks which links take the new file: Selected Instances (the selected images, as before), All Instances (every image linked to the same file), Missing Links from This Folder (then every other missing link whose file name is in the new file's folder) and Each Link Separately (a file for each selected link in turn). Each relinks as one undo step (`links.relink {scope}`, `ui.relinkDialog`). Relink to Folder… stays as it is. - The Links panel menu's Copy Info ([Links panel](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/links-panel-in-illustrator.html)) copies the selected link's file name to the clipboard (`links.copyInfo`). VectorCraft's own rules: with several rows selected it copies one name per line in the order the panel shows them, an embedded image gives the name its row shows, and the item is off with no row selected. + - The Links panel menu's Unembed… works on several selected embedded images at once and writes them all to one chosen folder ([Embed and unembed images and files](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/manage-linked-and-embedded-files/embed-images-and-files.html)): it asks for a folder once, writes a file for each image there and links each image to its file in one undo step (`links.unembed {ids, folder}`). VectorCraft's own rules: each file keeps the format its image is stored in (or PNG when that format is not one of VectorCraft's raster file formats) and is named after the image, a taken name gets a number (`Name 2`) and a file already in the folder is never replaced, linked rows in the selection are left as they are, and when one image can't be written the files already written are removed and nothing is unembedded. On the web each image is downloaded instead. Evidence: `unembed_to_a_folder_writes_each_image_and_links_it_in_one_undo_step`, `unembed_to_a_folder_that_fails_leaves_no_file_and_no_change`, `unembed_writes_several_images_to_one_picked_folder`. - Linked files inside symbols, graph designs, patterns and opacity masks are saved with their paths relative to the document, as linked files in the layers are, so they are found after the document and its files move to another folder together; on open each of those links takes the path where its file was found. Update Links, and opening with Update Links: Automatically, read a modified file again for that art too, and saving a document refreshes its placed copies inside symbols and patterns of the other open documents. Evidence: `links_outside_the_layers_find_their_files_after_the_folder_moves`, `update_links_reads_files_again_inside_symbols_patterns_and_masks`, `saving_a_document_refreshes_its_placed_copies_inside_symbols_and_patterns`. - A linked file that is missing when a moved document is saved keeps the folder its relative path names, instead of a relative path worked out from the out-of-date absolute path, also for a `.ai` file another app wrote (such as `src/`), so the file is found once it is back in that folder. Evidence: `a_missing_link_keeps_its_relative_path_when_the_moved_document_is_saved`, `links_of_an_imported_file_are_found_by_their_relative_folder`, `a_missing_link_of_a_moved_document_keeps_its_relative_place`. - On Windows, a document opened from a mapped network drive finds its links stored with the share's own path (`\\server\share\…`), as the same document opened from the share does; links on other computers stay missing. @@ -2158,6 +2265,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Import and export, later 2026-10-13 merges: SVGs that move objects with a CSS transform (`translate(100px, 0)`, `rotate(45deg)`) or style type with the `font` shorthand import as drawn (#1565); SVG symbols whose shapes use percentage lengths import at the size and place they are drawn, the percentages being of the symbol's `viewBox` (#1596); Inkscape's flowed text (`flowRoot`) opens as area type in its rectangle, a paragraph per `flowPara`, instead of being dropped, and a region that can't be read is left out with a warning (#1569, fixes #1568); the warning for an unsupported SVG filter names the filter, its primitives and the object, and says the object is drawn without it (#1599, fixes #1598); the pages of an Inkscape multi-page SVG become artboards, named by their labels (#1603, fixes #1601); SVG export with CSS classes or style entities stays fast in documents with many distinct styles (#1567); PDF and `.ai` import: evenly letter-spaced or tightened type on a path keeps its length along the path instead of closing up to the font's advances (#1586), and type on a path whose stroke is written glyph by glyph comes in as one text object with its stroke, not one object per glyph (#1585); the ICC profiles embedded in JPEG, TIFF and PSD exports have every tag on a 4-byte boundary (ICC.1 §7.1.2), so strict readers accept them (#1589, fixes #1584); GIF, PNG-8 and other indexed exports find each pixel's palette colour through an index instead of a scan, with identical output (#1576); a zero-length subpath draws its round cap as a dot and its projecting cap as a square, so dots in imported `.ai` and SVG files show (#1619, fixes #1613). - Files and untrusted input, 2026-10-14 merges: EPS import: a stitched shading keeps its hard colour changes (#1654, #1653). WMF/EMF import refuses an oversized embedded PNG or JPEG from its header, before any pixels are decoded (#1776). PDF open no longer takes exponential time on a crafted name tree with shared nodes when it looks for the editing data (#1781). The size limits on a native file's embedded data also apply to files read from memory, not only streamed ones (#1783). Saving over a private file on Unix no longer leaves a readable temporary copy beside it while the file is written (#1778). An Export for Screens suffix can no longer place files outside the export folder (#1777). Package refuses a folder where it would overwrite the open document or one of its linked files (#1786). ruzstd 0.9.1 fixes a decompression bomb (RUSTSEC-2026-0344) reachable from EPS/`.ai` and Affinity import (#1807). File Info dates are stamped only after a save succeeds, so a failed save no longer changes them (#1774). Linked files that change during a drag are updated after the drag instead of being missed (#1773). - EPS import: `readhexstring` and `readline` read the data left in a file in one pass instead of one byte per call, with the same bytes, result and next unread byte as before (about nine times less reader time on 6 MB of hex image data and on 8 MB of lines). + - EPS import: `token` on a string, `search` and `anchorsearch` read their strings in place instead of copying the rest of the string on each call, with the same results, errors and operation count as before. Walking a 512 KiB string by what each call leaves takes 16 ms instead of 518 ms with `token` and 1.0 ms instead of 27 ms with `search`, and a 64 KiB string 2.2 ms instead of 10 ms with `token`; on a 4 KiB string the difference is under 0.1 ms (release build on Linux under load from other builds, median of 7 alternating runs, `cargo test --release -p vectorcraft-eps --lib tests_strings::string_walks_timed -- --ignored --nocapture`). - **Fields, search and window, 2026-10-14 merges:** Fields commit what was typed when you click away or move to another field, as Enter does; Escape still discards it (#1787). Up and Down move through the command search results and Enter runs the highlighted one (#1798, #1757). Slider rails show on Medium Dark (#1808, #1662). On Windows the custom title bar's window stays truly borderless, so the pointer lines up with what is drawn on systems where the hidden caption offset it (#1791, #1758; awaiting the reporter's confirmation). - **Tools, panels and type, later 2026-10-14 merges:** the Transform panel's, Properties panel's and Control bar's X, Y, W and H show and edit the bounds of the anchor points selected with Direct Selection, and a whole-object selection is unchanged (#1839, fixes #1824). With Snap to Grid on, anchors and objects snap to the grid even when Snap to Pixel is also ticked: the grid wins (#1840; #1816 stays open until the reporter confirms). A marquee with the Selection or Direct Selection tool also selects the unlocked ruler guides it crosses (#1836). The toolbar shows no group labels by default (a preference brings them back) and runs on in one or two columns; the All Tools drawer lists the tools by flyout group with their shortcuts, has a menu (Reset, Basic, Advanced) and a Show section for the Fill/Stroke, Coloring, Draw Mode and Screen Mode controls (`toolbar.show`, #1751). An action clicked in the Actions panel stays selected, so Play Current Selection and Delete Selection act on it (#1853, part of #1629; editing actions and action shortcuts remain). Redo pressed during a drag keeps the drag as a step instead of losing the redone edit (#1856, #1719). Preferences are written as soon as OK is pressed, so they survive a session that doesn't end with a normal quit (#1857; #1747 stays open until the reporter confirms). New and Redefine Character Style take the format of the selected text range, also while typing (#1634). Type inside symbols, pattern tiles, graph designs and opacity masks gets its layout bounds back when a native file opens, so warped type in a symbol looks the same after save and reopen (#1833, #1738). Editing, renaming, deleting or merging a global swatch reaches the art of opacity masks, and a swatch used only in a mask is no longer listed as unused (#1830, #1735). On macOS, Save As, Save a Copy and the first Save show their sheet again; the Format menu on the sheet (#866) is withdrawn until the format can be set before the sheet opens, and #866 is open again (#1855; #1800, #1831 and #1518 stay open until confirmed on a Mac). - **Files and untrusted input, later 2026-10-14 merges:** SVG import applies style sheet rules with `:not()` selectors, with their nesting bounded (#1799, #1557), no longer stalls on a style sheet with many stacked descendant selectors over deep nesting (#1834, #1703), and reads an SVG's linked files within the automation roots in force again (#1870). DXF export writes the VPORT record's view direction once (group code 36 was written twice, which strict readers reject, #1789). A deeply nested file no longer overflows the stack: nesting is capped at 32 objects (deeper groups are merged with a warning; SVG past 256 elements and PDF past 256 nested arrays are refused), symbols and patterns that use themselves open without the offending instance or paint, and a document nested more than about 40 deep can no longer be saved to a file that won't open again (#1852). PDF and `.ai` files nested deeply inside compressed streams, page trees holding themselves and functions or colour spaces built on themselves no longer crash the app (hayro 0.8; the import runs on a 16 MB thread, #1871); a decompression bomb or impossible predictor parameters are refused (#1873, #1700, #1701); a brush whose art draws the brush again through a symbol or pattern no longer crashes the app, and graph designs, Affinity, DXF, metafiles and plug-ins were probed with hostile input (#1872). Hostile EPS, Affinity and native files can no longer run memory or CPU away through ASCII85 data, PostScript objects holding themselves, flat-colour pixel layers or far and overlapping data offsets (#1863: #1715, #1714, #1704, #1699), and the save fallback for folders that refuse a rename keeps the old file's content until the new one is in (#1695). A file whose ids sit at their largest value no longer breaks new objects (#1718); a failed `command.batch` puts each document back whole, its file, history and a drag in progress included (#1697); a control request that timed out before the app took it never runs later, and the reply says which case it was (#1725, [control-protocol.md](control-protocol.md)); the Eyedropper and recolouring refuse an image too large as RGBA before decoding it (#1717) (all #1862). A save or export that fails is reported in a dialog that names the file and stays until closed, with the document left modified and the old file untouched (#1685); a browser download that can't start fails the save instead of marking it saved (#1693); a file that finishes opening waits while a dialog is open, so Save As options can't save the wrong document (#1694) (all #1865). krilla is built without its text shaping, so the unmaintained rustybuzz and ttf-parser don't ship (#1874, #1730); the CI gate compiles the web app for wasm, and the web's SVG nesting cap (34) follows from its 1 MiB stack (#1875). @@ -2199,14 +2307,17 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A subpath keeps its anchors in chunks of up to 256 anchors, and the versions of a path share the chunks they have not changed. Editing one anchor copies only the chunk that holds it, so its undo step keeps that chunk instead of a copy of every anchor; adding or deleting an anchor copies the chunk it is in and rebuilds the subpath's table of chunks. When the renderer looks for the anchors that moved, it compares only the chunks the edit copied. Moving one anchor of a selected open path of 10,000 or 200,000 anchors (`path.moveAnchor`, `path.setHandle`, `path.moveAnchors` or a nudge) keeps at most 48 KiB in the undo step and in the redo step, where it kept a copy of every anchor at 56 bytes each (counted in the engine's tests). Files are written and read as before, each subpath's anchors as one list. Opening a document keeps the layouts it makes for its type objects, up to 128 MiB, and the first frame uses them instead of laying those objects out again. It does not keep a layout with bitmap or color glyphs or a text object with a gradient. The frame uses a layout only for a text object equal to the one laid out, and only while the fonts and the hyphenation exceptions have not changed. It uses each layout once. The renderer drops the rest when a frame that used one ends, and all of them after eight frames that use none. The frames of a threaded story are laid out while the file is read, and the first frame lays them out again. The pixels are the same. On Windows at 1600 × 1200, in medians of seven interleaved rounds of a local example, counted in the main thread's CPU cycles because other builds were running: with 5,000 point type objects in view the first frame takes 409 million cycles instead of 894 million and the open 816 million instead of 665 million, so the two together take 1,225 million instead of 1,559 million; with one area type object of 500 paragraphs the first frame takes 697 million instead of 1,193 million and the open 535 million instead of 568 million. Type › Show Hidden Characters keeps the marks it places on each text object from one frame to the next. The canvas lays a text object out again when an edit changes it or its threaded story, or when the last frame that showed the marks did not draw it, and it lays out all type in view again when the fonts or the hyphenation exceptions change. With 1,000 two-line labels in view, drawing the marks takes 0.8 ms per frame in a release build instead of 19.7 ms. + With a Type tool active, the in and out ports of the selected area type and type on a path, and the highlight of a selected story's other frames after Select All, use each frame's layout from the last frame instead of laying the frame out again. A frame is laid out again when its text object changes, or when the fonts or the hyphenation exceptions change. With 200 selected area type frames of about 400 characters, one of them being edited, the Type tool's overlays take 0.27 ms per frame instead of 121 ms; with a 5-frame story selected they take 0.016 ms instead of 2.0 ms (release build on Linux, medians of seven runs, measured while other builds were running). A selection with more than 100,000 points to outline shows its bounds instead of each object's outline and anchors. Paths count their anchors. Area type and type on a path count the anchors of their frame or path, and point type counts six: its box's corners and the ends of its baseline marker. Images, symbol instances, placed documents, and area type or type on a path in perspective count the four corners of their box, and gradient meshes and envelopes count their points and the ends of their mesh lines. The hover highlight leaves out an object past that count, and such an object shows its bounds as the key object. With 32,768 type objects, images, symbol instances, gradient meshes or envelopes selected, the selection's outlines and anchors add fewer than 100 vertices to the canvas's mesh (#2460). The canvas keeps the selected objects' outlines, anchors and handles from one frame to the next as one mesh. It builds an object's marks again when the object, its layer color or its selected anchors change. A pan moves the kept outlines and handles and places the anchor squares again. Each subpath and handle gets its triangles the first time it is in view. A frame with a new zoom or rotation draws the marks one shape at a time and keeps nothing, and the next frame at that view builds them. The pixels are the same, apart from two small differences: a kept outline's corner of exactly 90 degrees in a rotated view can keep its miter or cut corner after a pan, and kept vertices can move by rounding errors. On Windows at 1440 × 900, in a release build, with 2,000 selected circles of 50 anchors each in 10 fill colors, an idle frame takes 12.8 ms instead of 59.9 ms with the Selection tool and 29.8 ms instead of 192.1 ms with Direct Selection (medians of five runs). A frame during a zoom takes about what it did: 86.7 ms instead of 80.0 ms with the Selection tool. Delete, Cut, Group, Ungroup, Make and Release Compound Path, Make Clipping Mask, Send to Current Layer, Duplicate, Copy in the Move, Rotate, Scale, Reflect and Shear dialogs, Transform Each with Copy and each move of an Alt-drag take time in proportion to the size of the document (#1429). Cut, and Clear with `ids`, take the removed objects out of the selection in one pass over the selected objects. With 50,000 objects selected and all of them cut, that step takes 5.07 to 5.91 ms instead of 544 to 630 ms, with 20,000 it takes 1.75 to 1.87 ms instead of 91.7 to 97.2 ms, and with 2,000 it takes 0.120 to 0.148 ms instead of 0.940 to 0.955 ms (release build, 7 wall-clock runs of each, measured while other builds were running). + Cut with direct-selected anchors or segments removes the objects selected whole and the paths it leaves with no segment in one pass over each layer or group that holds them, and then removes the compound paths left with no members, instead of removing each one on its own. The document, the selection, the clipboard and the undo step are the same as before. With 2,000 of 10,000 squares on one layer selected whole and two anchors of another picked, Cut walked the document's tree 10,005 times and now walks it 8 times, and takes a median of 11 ms of CPU time instead of 573 ms (release build on Linux, seven alternating runs of each in one process, `cargo test --release -p vectorcraft-engine --lib -- --ignored --nocapture direct_selection_cut_timing`). Tests: `cmd::edit::tests` in `crates/engine/src/cmd/edit/tests.rs`. In the web build the status bar's render and UI times are measured with the browser's `performance.now()`, and the Layers panel stops rendering row thumbnails in a frame once they have taken 8 ms. On the desktop, the Layers panel renders a row's thumbnail on its thumbnail thread when the row's paths, and the paths of its opacity masks that are not disabled, hold more than 2,000 anchors in all. It already did this for the first thumbnail of a row of more than 200 objects. Until its first thumbnail is ready, the row shows boxes at the bounds of up to 41 of its paths, each in its path's solid fill or stroke color or in gray, when its own paths, without its opacity masks, hold at most 2,000 anchors in all, and an empty white box otherwise. With one path of 200,000 anchors, the first frame after the panel opens takes 2.4 ms instead of 393 ms (release build, median of three runs). The same 2,000-anchor limit counts each glyph of type as 4 anchors, each point of a gradient mesh as 1 and every 100 pixels of an image as 1, and a symbol instance or a placed document counts the objects and anchors of the art it shows. A placed document whose file has not been read yet, or a symbol nested more than 8 deep (one that holds an instance of itself, for example), gets its first thumbnail on the thumbnail thread, and so does a row whose art takes more than 20,000 steps to count (each object, subpath, text run and symbol looked at is one step). The first frame after the panel opens takes 2.4 ms instead of 19.8 ms with 5,000 glyphs of point type, 1.8 ms instead of 343 ms with one instance of a symbol of a 200,000-anchor path, 2.0 ms instead of 11.0 ms with a 100 × 100 mesh, and 2.1 ms instead of 274 ms with a placed document of a 200,000-anchor path (release build, median of three runs). When the Layers or Links panel shows another document's rows, the thumbnail thread drops the row thumbnails it has not started for the documents not shown, and it drops all of them when the Layers or Links panel is open after the last document closes. Those rows ask for their thumbnails again when their document shows again, and the thumbnails already made are kept. With 150 rows of 20,000-anchor paths waiting for another document, the 8 rows of such paths of the document shown get their thumbnails in 153 ms instead of 3,265 ms (debug test build, median of three runs). + The Links panel keeps its `links.list` rows and Link Info in one shared cache, and a frame that fetches nothing new reads that cache without copying the rows. The cache is replaced when the document or its revision changes, the Show, Sort or Show DCS Transparency Interactions option changes, or the files are looked at again every 2 seconds, and, while an image is selected, when Link Info opens or closes or the first selected image changes. With 2,001 images a frame's cache step takes 0.2 µs instead of 1.79 ms, and with 10,001 images 0.2 µs instead of 12.2 ms (test build, median of 7 wall-clock runs of 1,000 frames, measured while other builds were running). In the web build, while a pan, zoom or rotation changes the view of a document whose last canvas render took more than 8 ms, the canvas draws the last frame moved with the view, and it renders the art again once the view has been still for 0.2 s. An Alt-drag with the Selection, Direct Selection, Group Selection, Rotate, Scale, Reflect or Shear tool copies the selection on its first move, and the moves after it transform those copies; the previews of the Move, Rotate, Scale, Reflect and Shear dialogs with Copy and Preview on copy the selection once in the same way (#1429). An Alt-drag of objects in perspective with the Perspective Selection tool, and an Alt-drag of a plane widget with that tool or the Perspective Grid tool, copy the objects on the first move, and the moves after it move those copies (#1429). @@ -2241,6 +2352,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Pattern fills in Expand:** Object › Expand with Fill turns a pattern fill into the pattern's tiles in a clip group shaped like the object, with the fill's opacity and blend mode, and the object's other fills and strokes stay above or below it in paint order, in one undo step (`object.expand`). - **Gradient options for type in Expand:** the Expand dialog enables its gradient options for type, symbol art included, only when the outline of at least one character, ruby character, underline or strikethrough gets a gradient that Fill turns into art. A gradient that repeats or reflects in more than 256 runs across a character's outline, VectorCraft's own limit, stays a gradient after Expand (`object.expand.info`, `crates/engine/src/tests/objexpand.rs`). +- **Expand with Alt (Option):** choosing Object › Expand… in the in-window menu bar with Alt (Option on macOS) held expands the selection at once, in one undo step, with the choices OK last expanded with in the Expand dialog ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/expand-objects.html) describes this shortcut for a gradient), and the dialog opens on those choices. VectorCraft's own rules: the shortcut applies to every expandable selection, the choices are kept until the app quits, the dialog's defaults apply before the first OK, and when none of the choices has something to expand in the selection the dialog opens instead (`ui.expandDialog`'s `immediate`). - **Type with transparency or effects:** type at less than 100% opacity, in a blend mode other than Normal, or with raster effects such as a drop shadow keeps its glyph outlines between frames, as opaque type does, and is laid out again when it is edited or the fonts change. At 2880 × 1800 on 8 threads, a page of 1,000 type objects takes 13 ms a frame instead of 23 ms at 80% opacity, 31 ms instead of 41 ms in Multiply and 16 ms instead of 26 ms with a drop shadow, with the same pixels. @@ -2253,6 +2365,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Live objects in documents with many symbols:** a live object, or an object with effects, that shows symbols or patterns is not walked again in a later frame to find them while the document's symbols and patterns stay the same. One that shows a placed file is walked in every frame. At 1000 × 1000 pixels, a page of 2,000 envelopes around instances of the last 2,000 of 10,000 symbols takes 30 ms a frame, and 83 ms when every frame walks them again, with the same pixels. - **Control bar and task bar on large paths:** the Control bar and the contextual task bar read the first selected object in place each frame instead of copying it; the task bar copies the object only when it is a basic shape, for its Shape Properties. With one selected open path of 200,000 anchors, an idle frame with both bars shown takes 3.8 ms in a release build instead of 8.0 ms (medians of five interleaved runs). Tests: `the_control_bar_label_follows_edits_undo_documents_and_selection`, `the_task_bar_follows_the_active_document`, `the_task_bar_follows_edits_and_undo`. +- **Panels on large selections:** the Properties, Transform, Brushes, Appearance, Transparency and Image Trace panels read the selected object where the document holds it each frame instead of copying it, and the Transparency panel removes the mask from a copy of the object only when it draws the object's thumbnail again. With one selected open path of 200,000 anchors, an idle repaint uses 72.9 µs of CPU time in a release build instead of 88.4 µs for the Properties panel, 27.5 µs instead of 37.2 µs for the Appearance panel and 19.6 µs instead of 29.8 µs for the Transparency panel with its thumbnails shown (medians of seven interleaved runs). Tests: `first_selected_is_the_node_the_document_holds`, `first_subject_is_the_node_the_document_holds`, `panels_show_the_selected_object_after_an_edit_and_after_undo`, `state_holds_the_documents_node_and_the_object_thumbnail_leaves_out_the_mask`. - **Paste of many objects:** Paste leaves pasted copies as they are when no resource has another name or color in the document and the objects link no graphic style. It looks up the pasted type in one walk of the tree. A paste and undo of 20,000 rectangles in 200 groups uses 49.2 ms of CPU time in a release build instead of 59.4 ms, and of 5,000 point type objects 25.3 ms instead of 29.4 ms (medians of seven interleaved rounds, each round the CPU time of a 61-paste run minus a 1-paste run, divided by 60). Tests: `crates/engine/tests/it/paste_many.rs`. - **Type drawn as glyph outlines:** under a geometry effect, in EMF and WMF export, in DXF export when it is written as outlines, flattened with Convert All Text to Outlines, and inside an envelope, type keeps its underline and strikethrough, the weight and dashes of its character strokes when it is scaled, and the placement of its gradients and patterns, as the canvas draws it. A group's or layer's own fills and strokes also paint the underline and strikethrough of the type in it. @@ -2321,6 +2434,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Changed plug-in gradients lose spot plates (G17):** a gradient that a filter or importer changes loses each stop's swatch link, tint and process `plates` together, in fills and strokes, and keeps the stop's color, offset, opacity and midpoint; a gradient returned unchanged keeps all three. Regressions: `crates/plugins/src/objects/tests.rs` (`changed_gradient_fill_and_stroke_drop_spot_plates`, `unchanged_gradient_paint_keeps_spot_plates`). Scores and hours unchanged. - **Plug-in data kept with the document (G17):** a filter writes JSON of at most 1 MiB with `documentData` (one undo step with its objects; `null` removes it) and reads it back in `_context.documentData`, which no other filter is given. It is the document's foreign data (`unknown.pluginData`, by plug-in id), as the perspective grid is, so the native file keeps it with no section of its own; an exporter is given the whole document, so it can read every plug-in's. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_export.rs` (the exporter), `crates/doc/src/plugin_data.rs`, `crates/plugins/src/objects/tests.rs`. Scores and hours unchanged. - **Heavy filter plug-ins (G17):** a filter's manifest may ask for `"budget": "heavy"`: 1 G instructions (20 times a light run's) and 300 s a run, for routing, packing or simulation. Install Plug-in… and File › Open ask the user first, `plugin.install` needs `allowHeavy: true` (`plugin.inspect` tells beforehand), the Additional Plug-ins Folder skips such filters, and the plug-in store keeps the answer. Its dialog has no Preview; the app runs it on a thread of its own with a progress window (Cancel, Continue in Background) and applies the result as `plugin.run` with the same parameters, one undo step, unless the document or the plug-in changed meanwhile. Regressions: `crates/plugins/tests/abi.rs`, `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`, `crates/ui-egui/src/tests/plugin_runs.rs`. Scores and hours unchanged. +- **Plug-in instruction budget preference (G17, VectorCraft's own setting):** Preferences › Plug-ins & Scratch Disks › Plug-in Instruction Budget (`pluginInstructionBudget`) is Normal by default, which keeps the 50 M instructions a light filter run gets, or Large, which gives each object filter run 250 M plus the 4,000 per input byte, with the 60 s time budget, Cancel and the other limits unchanged. A heavy filter keeps its 1 G and 300 s with either choice; live effects, exporters and importers keep their own budgets. A change applies to the next run of an installed filter; `prefs.set` refuses any other value, and a saved file with another value reads as Normal. Regressions: `crates/plugins/tests/abi.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/src/tests/prefs.rs`, `crates/ui-egui/src/prefs_dialog/tests.rs`. Scores and hours unchanged. - **Safe Mode for plug-ins (G17):** `vectorcraft --safe-mode` and `vectorcraft-cli --safe-mode ` start without plug-ins. When a launch stopped while a plug-in was loading or drawing its first live effect, the next launch names that plug-in, without saying it caused the stop, and offers Disable and Continue, Start Normally or Start in Safe Mode. Help › Safe Mode lists the disabled plug-ins with Enable on Re-launch, which takes effect at the next launch, and the app bar and the window title show Safe Mode. The help page (https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf, pages 65 to 69) describes the same choice between diagnosing and starting normally, a Safe Mode with the problem item off and the rest of the app working, and turning the item back on at the next launch. In Safe Mode no plug-in loads or runs, and a live-effect plug-in draws its object's geometry unchanged while the object keeps the effect, which the Appearance panel marks "(Safe Mode)" with the plug-in's id in its tooltip and `effect.list` marks `skipped`; Expand Appearance refuses such an object. The web build keeps no plug-ins between page loads and has no marker. Each desktop launch with preferences keeps a marker in the `Launch` folder next to them; `vectorcraft-cli` and a desktop launch without preferences keep none, so a stop there leads to no choice at the next launch. Disabled plug-ins are listed in `Plug-ins/disabled.json`. `plugin.safeMode` reports Safe Mode and the disabled plug-ins, and `plugin.setEnabled` changes the list. Regressions: `crates/plugins/src/safe_mode.rs`, `crates/plugins/tests/safe_mode.rs`, `crates/engine/tests/plugin_safe_mode.rs`, `crates/ui-egui/tests/safe_mode.rs`. Scores and hours unchanged. - **Hang report and Copy Troubleshooting Info:** when the desktop app's interface thread stays in one part of a frame for 3 s (VectorCraft's own value), a watching thread writes a hang report to the log and to `logs/hang-report-.txt`, and removes the file when the interface answers again. A later launch that finds a report no process holds writes it to the log, keeps it as `logs/hang-report.1.txt` and, unless another start-up message is showing, says so in the status bar. Help › Copy Troubleshooting Info (`help.copyTroubleshootingInfo`) copies the platform facts, the recent commands and frame times, and the reports of this session and the last one. Regressions: `apps/vectorcraft/src/hang_watch/tests.rs`, `crates/ui-egui/src/hang_beacon.rs`, `crates/ui-egui/src/troubleshooting.rs`. Scores and hours unchanged. - **A disabled plug-in whose update stays in the store is turned on:** when `plugin.install` writes a module that lists permissions to the `Plug-ins` folder, its grant can't be written, and the folder can't be returned to the old module (or, on a first install, the new module can't be removed), the folder holds the new module, so a disabled plug-in is turned on, by id and by stored file, as for any install the folder holds. The old grant, or none, doesn't cover the new module, so the next start skips it until it is approved. Regressions: `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. @@ -2343,6 +2457,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **The command sweep sends file and folder params into its temp folder by the command catalog:** the sweeps in `crates/engine/tests/command_sweep.rs` take each command's file and folder keys from the catalog (`cmd::location_keys`, the same key list the plug-in call rules use, less the keys that name part of the document in a command), read every key a params description names (`{path | name …}`, `{folder? (…)}` included) and its schema's params, and send every string under such a key, in arrays and in objects inside them (`paths: [{ids, path}]`), as a location in the temp folder, so a command added later is swept and checked without editing the sweep. `diffPath` counts as a file key, and Slice Options' `url` and Export for Screens' `folders` do not. Regressions: `sweep_cases_name_files_only_inside_the_temp_folder` and `sweep_cases_send_the_file_keys_of_the_command_catalog` in `command_sweep`, `location_keys_come_from_the_command_catalog` in `cmd::plugin_call`. Scores and hours unchanged. - **A drag ended by a command with Real-time Drawing off:** when Undo, Redo, a filter that calls commands or a plug-in command that calls commands ends a drag whose preview Real-time Drawing off has not applied yet, the preview is applied first and kept as an undo step of its own, as releasing the drag keeps it; a preview that fails cancels the drag. The filter or plug-in command is then given the objects where the drag left them. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/engine/src/tests/prefs.rs`. Scores and hours unchanged. - **The warning of a preview applied when a command ends a drag:** a preview that Real-time Drawing off left unapplied, and that Undo, Clear History or another command applies before it runs, keeps its warning: the command's result carries it as `previewWarning`, and as `warning` when the command has none of its own, and the status bar shows it, as releasing the drag shows it. Typing kept as its own step when a tool's drag begins, or when Cmd lends the Selection tool, shows its applied preview's warning in the status bar too. Regressions: `settling_a_deferred_preview_keeps_its_warning` and `settling_typing_for_a_tool_shows_its_preview_warning` in `crates/engine/src/tests/prefs.rs`, `settled_warnings_join_the_result` in `crates/engine/src/session/execute.rs`. Scores and hours unchanged. +- **Typing kept when a dialog or a panel previews, with Real-time Drawing off:** a dialog's Preview, a panel's live slider, the Effect Gallery's preview, the font menus' preview, a paint for the characters the Type tool selected and an inline graphic inserted while typing first apply the typing that Real-time Drawing off left unapplied, as an undo step of its own, and the status bar shows that typing's preview warning. The Character, Paragraph and Tabs panels, Bullets and Numbering, Justification and the inline graphic then act on the characters the Type tool selected in the typed text. When the typing can't be kept, the status bar shows the error and the dialog's preview does not start. Regressions: `settling_typing_for_a_dialog_returns_its_preview_warning` in `crates/engine/src/tests/prefs.rs`, `ending_deferred_typing_for_another_edit_keeps_the_typing` in `crates/engine/src/tests/textedit.rs`, `inserting_while_deferred_typing_keeps_the_typing` in `crates/engine/src/tests/inline.rs`, `settled_typing_tests` in `crates/ui-egui/src/dialogs/form.rs`, `stack_preview_keeps_typing_in_progress` in `crates/ui-egui/src/dialogs/effect_gallery.rs`. Scores and hours unchanged. - **Plug-in progress, Cancel and log lines (G17):** at plug-in API level 2 a plug-in with the `progress` permission imports `env.vc_progress`, `env.vc_cancelled` and `env.vc_log`. A heavy filter's and an export's progress windows show its progress as a percentage bar, their Cancel reaches it through `vc_cancelled`, a light filter with `progress` and no `commandAllowlist` runs in the background with the same progress window when it runs at once or OK runs it with Preview off, and its log lines go to the app's log with its id, capped per line and per run. Installing checks every import and names the one it refuses. Regressions: `crates/plugins/src/host.rs`, `crates/plugins/tests/abi.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`, `crates/ui-egui/src/tests/plugin_runs.rs`. Scores and hours unchanged. - **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. - **Painted effects refuse gradient stop plates without a spot link (G17):** a gradient stop with process `plates` in a painted live effect's fill or stroke must link to a spot swatch of the document itself; a stop with no link, a `null` link or only the gradient's own `swatch` refuses the whole result, and so does a link to a process swatch or Registration, also when a cached result's swatch stops being a spot swatch. `lastError` names the stop's `plates`. Regressions: `crates/plugins/src/painted/tests.rs`, `crates/plugins/src/effect.rs` (`cached_painted_plates_refuse_after_spot_becomes_process`). Scores and hours unchanged. @@ -2630,6 +2745,10 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov A VectorCraft addition, not a feature of the reference app (it has no command for this), so no area score moves. Object › Plug-ins › Type Tools › Release Type on a Path… splits each selected type on a path into point type holding the same text and the plain path it was set on, or keeps only one of them (#5532). The path keeps its exact shape (open or closed, anchors and handles, the object's transform), layer and place in the stacking order, with no fill and no stroke since type paths carry no paint of their own. The text keeps its runs, character and paragraph attributes and becomes point type on one straight line whose baseline starts where the first character sat on the path; Type on a Path Options don't apply to point type and are dropped. Keep Original leaves the type on a path and adds the released objects above it. Other objects are left alone and a selection with no type on a path makes no undo step; otherwise the run is one undo step, the released objects are selected, and the dialog's Preview works as Type on a Path Options' does (#5360). Tests: `cmd::addons::typetools::tests::release` in `vectorcraft-engine` (each mode, Keep Original, mixed and empty selections, closed, open, curved and flipped paths, transformed and grouped type, multi-style and unicode text with a centred paragraph, empty type, undo and redo, preview, cancel and commit, bad params refused), `release_type_on_a_path_previews_cancels_and_runs_on_ok` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Type Tools add-on › Release Type on a Path. +## Unit Converter add-on (2026-11-14) + +A VectorCraft addition, so no area score moves. Object › Plug-ins › Unit Converter opens a panel with one number field per unit of Preferences › Units › East Asian Type (pt, picas, in, mm, cm, px, ft & in, m, yd, ft, Q, Ha), as proposed in #5528. A length typed in any field, with units and arithmetic as every number field reads them, updates the others as it is typed; text that does not read leaves them as they were. From Selection reads the selection's width and height as the Transform panel measures them, Width or Height picks which one the fields show, and Apply sets that side of the selection through `object.setBounds` as the Transform panel's W or H field does (its reference point, Constrain Width and Height Proportions and its Transform Object Only, Pattern Only or Both choice) as one undo step, with no step when the size is already that length. Each field's copy button copies its value, with its unit when Copy with Units is on. Agents use `addon.units.convert` and `addon.units.selectionSize`, which change nothing in the document (`docs/mcp.md`). Tests: `cmd::addons::units::tests` in `vectorcraft-engine` (every unit, number-field syntax, preview bounds and selected anchors, bad params and unknown keys refused), `addons::units::tests` in `vectorcraft-ui-egui` (typing, From Selection and a changed selection, Apply with the Transform panel's reference point, proportions, pattern choice and a symbol's registration point, copy, screen-reader names) and `command_sweep`. + ## Cutting Tools add-on: Stencil Bridges (2026-11-12) A VectorCraft addition, so no area score moves. Object › Plug-ins › Cutting Tools › Stencil Bridges… cuts strips of a set width (0.01 to 1000 pt, 2 by default) out of the selected art so that a stencil cut from it keeps its islands, such as the inside of an O or a hole in a shape, attached to the sheet ([stencil islands and bridges](https://en.wikipedia.org/wiki/Stencil)). Every island is joined to the sheet, directly or through another island, by the shortest crossings that fit, then gets more bridges spread around it up to the count asked for (1 to 16); bridges run vertically, horizontally or along the shortest crossing among 12 directions 15° apart. The art is measured by the area its outlines enclose (hidden objects left out), type by its glyph outlines without converting the type, and becomes one compound path with the gaps cut; the selected objects that make up the art go to a new hidden layer, Stencil Original, or are replaced, and selected objects with no outlines stay where they are. Art with no islands is left as it is with a message and no undo step, islands the cut result still encloses are counted and reported, and the run is one undo step. Tests: `addons::stencil::tests` in `vectorcraft-pathops` (an O, two holes, nested islands, curved outlines, width, direction, the shortest crossing at an angle, more bridges per island and their spacing, narrow islands, slivers, outlines that touch at a corner, the curve tolerance, open outlines, limits and the work budget), `cmd::addons::cutting::stencil::tests` in `vectorcraft-engine` (the hidden layer and undo, replacing, width with units, type, hidden group members, objects with no outlines, the result's paint, kind and place in the stacking order, no islands, narrow islands, bad params refused), `stencil_bridges_opens_its_dialog_and_runs_on_ok` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Cutting Tools add-on › Stencil Bridges. @@ -2668,6 +2787,10 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov A trim reads the selection through a set and changes it once at the end, instead of going through the selected objects once for each trimmed path and each piece, with the same resulting selection as before. With 2,000 selected lines each split in two, the selection update took 7.7 ms and now takes 0.2 ms (the whole command about 75 ms); with 7,000 lines it took 96 ms and now takes 0.7 ms. The times are wall-clock medians of 7 runs while other builds shared the CPU. Test: `the_selection_after_a_trim_is_the_one_changing_it_one_id_at_a_time_gives` in `cmd::addons::pathtools::trim::tests` in `vectorcraft-engine`. +## Path Precision Tools add-on: Smooth Bridge (2026-11-15) + +A VectorCraft addition, so no area score moves. Object › Plug-ins › Path Precision Tools › Smooth Bridge… (`addon.pathtools.bridge`) joins two selected circles into one closed outline, like two drops of liquid pulling apart: the outline goes around each circle on its side away from the other and along two concave arcs, one on each side, each touching both circles from outside, so the outline runs on smoothly from each circle into the bridge and every anchor is smooth. The arcs' radius is a percentage of the smaller circle's radius (1 to 1000%, 100% by default); a larger radius makes a wider, gentler bridge, and circles farther apart make a narrower one. Overlapping and touching circles are joined at every radius; one circle inside the other, or circles too far apart for the radius (the arcs would not reach both circles, or would cross), is refused with a message, which suggests a larger radius only when one up to 1000% would bridge them. The outline replaces the two circles, painted as the upper one, or with Keep Originals goes directly above the upper circle and the circles stay. One undo step; the dialog previews on the canvas. Tests: `bridge::tests` in `vectorcraft-pathops` (equal and unequal circles, overlapping and touching ones, unequal ones at large radii, the neck's width, the arcs tangent to both circles at every anchor, far apart and nested circles refused, circles told from other paths), `bridge::tests` in `cmd::addons::pathtools` in `vectorcraft-engine` (the outline in place of the circles or above them, one undo step, the radius, unequal overlapping circles up to the largest radius, refused selections and parameters with and without a larger radius suggested, locked and hidden circles), `smooth_bridge_opens_its_dialog_previews_and_runs_on_ok` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Path Precision Tools add-on. + ## Document Tools add-on: Save a Timestamped Copy (2026-11-01) A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Document Tools › Save a Timestamped Copy writes a copy of the document named `_YYYY-MM-DD_HH-MM.` (the date and time in UTC, through chrono; `-2`, `-3`… added when that name is taken) next to the document, or into a folder picked (the folder picker) when it was never saved, in the document's own format or another save format. It writes through File › Save a Copy's save, so the document keeps its path, title and modified state, no undo step is made, and the write stays inside the automation roots in force. It is off on the web, which has no clock. Tests: `cmd::addons::document::tests` in `vectorcraft-engine` (the name and place, numbered names, the document unchanged and its content in the copy, an unsaved document needing a folder, other formats, bad params refused, automation roots), `addons::document::tests` in `vectorcraft-ui-egui` (the submenu, beside the document, the folder picked or cancelled) and `command_sweep`. Commands: `docs/mcp.md` › Document Tools add-on. @@ -2803,6 +2926,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | Date | Change | Summary | |---|---|---| +| 2026-11-16 | minor | Layers panel: an Alt-drag copies a row above or below its own place (`layer.move` with `copy` and that row as the target), so the top layer dragged up, the bottom layer dragged down and a document's only layer are copied (#8237). Scores and estimates unchanged. | | 2026-11-16 | minor | Layers panel: rows or the selected-art square dragged over the list show the copy cursor while Alt is held, as the drop then copies, and the grabbing hand otherwise (#8217). Scores and estimates unchanged. | | 2026-11-16 | minor | Gradient panel: the strip under the ramp, where a click adds a stop, shows the white arrow with a plus on Windows and X11, where the system copy cursor showed as the plain arrow (#8241). Scores and estimates unchanged. | | 2026-11-16 | minor | Properties panel: while the Type tool edits text, the Character section shows the font family and style and the Variable Font button of the first selected character (or of the character before the caret), not those of the text object's first run (#8189). Evidence: `panels::properties::tests::character_section_shows_the_type_tool_selections_style`. Scores and estimates unchanged. | @@ -2824,6 +2948,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | 2026-11-12 | minor | `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints (its strokes' miter tips, and strokes a Transform effect moves, included), after its glyphs grown by half its strokes' weight; `.ai` import evidence updated (#6824); scores and estimates unchanged. | | 2026-11-12 | minor | Explicit editing-data import keeps a single artboard beyond a capped 14,400 pt PDF page (#6865), with a warning; automatic mode stays unchanged. Scores and estimates unchanged. | | 2026-11-12 | minor | Glyphs review (#6084): Entire Font uses the selection's version and variable axes for previews and alternate applicability. The default cell can reset an unlisted glyph choice when GSUB lists no alternates. Encoded Latin and other ordinary characters insert unchanged even if their glyph also has Arabic positional provenance; Arabic presentation forms retain base-letter insertion. Remove a redundant charmap scan from unlisted-glyph checks. Scores and estimates unchanged. | +| 2026-11-12 | minor | #6625 cap/join follow-up: hidden-fill and no-fill stroke hits must respect their cap/join geometry; focused CPU regressions passed. Existing fill-stack evidence, scores and estimates unchanged. | | 2026-11-09 | minor | Glyphs review (#6084): positional alternates with no supported feature are accepted as glyph choices in both panel views; Entire Font's unlisted-glyph and name-ownership behavior is retained. OpenType style options keep only a valid last on-value when enabling a set. Contradictory old glyph-choice evidence corrected; scores and estimates unchanged. | | 2026-11-07 | minor | Type core: the Glyphs panel's Alternates for Current Selection applies the OpenType feature that draws a variant to the selected letter alone, so an Arabic word stays joined (`salt=2`; the style commands take `tag=N`), and Show › Entire Font lists the glyphs no character maps (#5514; [Replace characters with alternate glyphs](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/replace-characters-with-alternate-glyphs.html)); evidence added; scores unchanged. | | 2026-11-12 | minor | UI chrome: a numeric-field focus click released more than 1 pt from its press keeps the caret; a tap within 1 pt still selects the whole value (#6659, follow-up to #1326); scores and hours unchanged. | @@ -2844,6 +2969,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | 2026-11-14 | minor | Symbols panel context menu: right-click on a symbol in thumbnail or list view displays a context menu (Place Symbol Instance, Edit Symbol, Duplicate Symbol, Delete Symbol, Break Link to Symbol, Select All Instances), selecting the symbol first if unselected; scores and estimates unchanged. | | 2026-11-11 | minor | Bundled content: built-in Inventory Icons symbol library (Sword, Shield, Potion, Key, Gem); symbol libraries evidence updated; ~38% → ~40%; more built-in symbol libraries remain. | | 2026-11-11 | minor | Guides and snapping: a Shift move slides the selection along its line onto a ruler guide by its edges and centre, as a move without Shift does (#4312); a guide a nearly parallel line only reaches a long way off pulls nothing. Score and hours unchanged (estimated). | +| 2026-11-11 | minor | #6625: path and compound-path interior hits follow enabled non-None fill rows, including lower fills beneath a top None row; hidden-only interiors miss; zero-opacity fills remain selectable. Scores and estimates unchanged. | | 2026-11-10 | minor | Automation: MCP tool count 33; headless `command_list` lists `UI_COMMANDS` (`ui: true`); eight prompts; effect-id vs command-id clarified (#6460); scores and hours unchanged. | | 2026-11-10 | minor | Type advanced: the Edit Custom Dictionary dialog, #4936; evidence added; the Check Spelling dialog remains; scores and hours unchanged. | | 2026-11-10 | minor | File formats: in a `.ai` or EPS opened from its editing data, an envelope of type opens live where it draws as its drawn art and the layers with it draw as the page (the envelope weighed as the art it draws); elsewhere, and where a text or visibility variable binds its type, it keeps its drawn art, with a note (#3179); evidence updated; scores and hours unchanged. | diff --git a/docs/three-d.md b/docs/three-d.md index 4f8d4003b5..4826df3552 100644 --- a/docs/three-d.md +++ b/docs/three-d.md @@ -469,8 +469,8 @@ The public [Map artworks on 3D object](https://helpx.adobe.com/illustrator/deskt page describes graphics: art kept with the document and placed on single surfaces of a 3D object, and the [3D and Materials panel options](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/3d-materials-panel-options.html) page lists Graphics and Add Materials and Graphics on the Materials tab. VectorCraft maps graphics onto -Extrude & Bevel's front and back caps, the plane of the Plane type (Rotate), and the swept side of Revolve, which the -public page's example of a label on a bottle describes. +Extrude & Bevel's front and back caps and its side (its walls and bevels), the plane of the Plane type (Rotate), and +the swept side of Revolve, which the public page's example of a label on a bottle describes. - The panel's **Materials** tab shows the document's graphics as thumbnails. A graphic is a document symbol, as the public page allows existing symbols to be used. **Add as Single Graphic** keeps the selected art as a new @@ -479,9 +479,9 @@ public page's example of a label on a bottle describes. - Clicking a thumbnail maps that graphic onto the front of the 3D effect of each selected object (`threeD.mapGraphic`), in one undo step. A graphic larger than the object starts scaled down to fit inside it. - Below the thumbnails the tab lists the graphics mapped onto the first selected object. The selected one shows - its Face (Front or Back; Plane and Revolve show no Face, as a plane has only a front and Revolve's graphics go - on its side), X and Y (the offset of its center from the center of the - object's bounds, in the face's plane), Scale (a percentage of the symbol's size) and Rotation + its Face (Front, Back or Side; Plane and Revolve show no Face, as a plane has only a front and Revolve's graphics + go on its side), X and Y (the offset of its center from the center of the + object's bounds, in the face's plane, or on a side from its middle unrolled flat), Scale (a percentage of the symbol's size) and Rotation (counterclockwise), and **Remove Graphic** takes it off. Each change is one undo step. - While the tab is open, a blue handle sits on the center of each mapped graphic whose face is turned toward the viewer. Dragging a handle moves that graphic over its face, previewed while the pointer is down and recorded as @@ -522,6 +522,20 @@ These rules are VectorCraft's own: or point, takes none. A graphic larger than the half of the side seen from the front starts scaled to fit it. The panel shows no handle for a Revolve's graphics; X and Y move them. Expand Appearance keeps every face of a surface with graphics. +- On Extrude & Bevel a graphic on the Side lies on the walls and bevels, unrolled flat. X runs along the art's own + outline (the front cap's edge, or with a bevel carved into the shape the walls' outline), through its corners and + around its curves: 0 is where the outline's top crosses the vertical line + through the middle of its bounds, and X grows clockwise around the outline as the front is seen, so the graphic + reads the right way round from outside. Y runs from the front cap's edge toward the back cap's, measured from the + middle: across each bevel step along its slant, and across the walls along the depth. Both are lengths before + the twist and the taper, which carry the graphic with the side. The side is cut at the anchor of the outline + nearest half way around from X = 0. On a compound shape the graphics go on its longest contour, and on an object + with several solids (a fill and its stroke's outline, or the members of a group or layer) they go once, on the + side of the solid with the longest outline. Each piece of the side that shows its outside to the viewer draws the + part of the graphic that falls on it, shaded as the piece is, with the same cutting and seams as on Revolve; a + piece of a stroke's face cut where it passes through a wall draws the part within its own outline. A graphic larger than the + part of the side unrolled about X = 0 that does not reach its cut starts scaled to fit it. The blue handle sits on the graphic's center while that point is on a + piece the viewer sees, and dragging it moves the graphic over the visible part of the side. - The symbol's fills and strokes are drawn as filled areas, a stroke as its outline, and their gradients and patterns are placed with the graphic. Images, hidden objects, guides and clipping paths in the symbol are left out, and clipping groups draw their art unclipped. Instances @@ -530,15 +544,16 @@ These rules are VectorCraft's own: - Without perspective, the graphic maps exactly. With perspective, straight lines stay straight and each curve is cut into 8 cubic pieces before it is mapped. The part of a graphic at or behind the eye is left out. - An object takes up to 64 graphics. One graphic draws up to 4,096 fills and strokes, and the graphics of one 3D - effect draw up to 400,000 path elements together (on Revolve, 400,000 points after the curves are cut, and up to + effect draw up to 400,000 path elements together (on Revolve's side and Extrude & Bevel's, 400,000 points after the curves are cut, and up to 2,000,000 once they are cut at the faces, with up to 64,000,000 points cut together, and the copies of their paints in the parts take up to 256 MiB per object, apart from those of the surfaces). Commands refuse a graphic past either limit. A loaded file draws the object without a graphic past the first limit, and without all of its graphics past the second. -- A hollow Extrude & Bevel has no caps, so its graphics are not drawn until Cap is turned on again, and - `threeD.mapGraphic` refuses to map a new one onto it. Changing the type to Inflate drops the graphics, and - changing between Extrude, Plane and Revolve keeps them, except that Plane and Revolve drop the graphics on the - back cap; on Revolve the front's graphics go on its side. +- A hollow Extrude & Bevel has no caps, so the graphics on its caps are not drawn until Cap is turned on again, + and `threeD.mapGraphic` refuses to map a new one onto a cap; its side takes graphics. With a depth of 0 the object + is a plane, and `threeD.mapGraphic` maps graphics onto its front only. Changing the type to Inflate drops the + graphics, and changing between Extrude, Plane and Revolve keeps them, except that Plane and Revolve drop the + graphics on the back cap and on Extrude & Bevel's side; on Revolve the front's graphics go on its side. - `effect.apply` and `effect.setParams` refuse a graphic that names a symbol the document does not have, unless the effect already holds a graphic of that symbol. A graphic whose symbol is deleted is no longer drawn. Renaming a symbol renames it in the graphics that use it, in the layers, in the art of symbols, patterns, graph designs, brushes and opacity masks, and in graphic @@ -553,7 +568,7 @@ uses: `rotationX`, `rotationY`, `rotationZ`, `perspectiveAngle` (degrees), `shad `lightHeight` (degrees), `lightSoftness` (%), `ambient` (%, to 200), `lightBehind`. Lengths are points and scale with the object (Scale Strokes & Effects). Commands validate the shape and the parameters before the document changes. All four also take `lights`: null (the default, use the earlier single-light fields), or an array of one to ten objects. Each object takes `color` (opaque `#rrggbb`, white), `intensity` (0..100%, 80), `rotation` (-180..180 degrees, 125.26), `height` (0..90 degrees, 30), `softness` (0..100%, 0), and `behind` (boolean, false). Omitted settings use those defaults. An explicit list replaces the earlier single light; `ambient` and `shade` remain shared. Set `lights` to null to return to the single-light fields. Invalid lists, counts, keys and values are rejected before editing; malformed loaded lists fall back to the earlier light safely. All four take `shadow` (boolean, false), `shadowPosition` (`behind` or `below`), `shadowDistance` (0..100%, 0) and `shadowBounds` (10..400%, 100) ([Shadows](#shadows)); values out of range are rejected before editing. `threeD.extrude`, `threeD.rotate` and `threeD.revolve` take `graphics` ([Graphics](#graphics)): an array of up to 64 objects, each -with `symbol` (the name of a document symbol), `face` (`front` or `back`, default `front`; `threeD.rotate` and +with `symbol` (the name of a document symbol), `face` (`front`, `back` or `side`, default `front`; `threeD.rotate` and `threeD.revolve` take `front` only), `x` and `y` (points, default 0), `scale` (1..10000%, default 100) and `rotation` (-360..360 degrees, default 0). Other keys, values out of range and graphics on the other 3D effects are rejected before editing. All four take `render` ([3D and Materials panel](#3d-and-materials-panel)): an object whose `mode` is `shaded` (the @@ -567,11 +582,11 @@ and [Create 3D objects](https://helpx.adobe.com/illustrator/desktop/special-effe pages, and the archived Extrude & Bevel option list (depth 0–2,000, cap on/off, bevel height, bevel extent in or out, perspective). No Adobe software, assets, presets or bevel shapes were used. -- **Materials** (base and Adobe Substance), graphics on Inflate and on Extrude & Bevel's walls and bevels, - shadows of lights after the first, and **ray-traced rendering** are not built: shading uses directional - lights, in the paint of the fill or stroke the solid is built for ([Fills and strokes](#fills-and-strokes)), and - only the first light casts a shadow ([Shadows](#shadows)). Graphics map onto planar faces and Revolve's side only - ([Graphics](#graphics)). +- **Materials** (base and Adobe Substance), graphics on Inflate, shadows of lights after the first, and + **ray-traced rendering** are not built: shading uses directional lights, in the paint of the fill or stroke the + solid is built for ([Fills and strokes](#fills-and-strokes)), and only the first light casts a shadow + ([Shadows](#shadows)). Graphics map onto planar faces, Extrude & Bevel's side as one surface unrolled flat, and + Revolve's side only ([Graphics](#graphics)). - The bevel shapes and their names are our own; custom bevel paths are not supported. - Visibility is a painter's algorithm: faces of a closed solid turned away are left out, and the rest are drawn back to front, with a flat cap or flat back turned toward the viewer drawn after all of them. Concave solids diff --git a/docs/type-parity.md b/docs/type-parity.md index 5317d1e4cc..d6b9ff54ba 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -50,7 +50,7 @@ against Illustrator's public documentation; **estimated** unless noted. | Roman Hanging Punctuation | done | Paragraph panel menu › Roman Hanging Punctuation, `text.setFormat {romanHangingPunctuation}` (#2756): per paragraph, Optical Margin Alignment's punctuation and amounts without the letters; paragraph styles carry it. Evidence: `tests::roman_hanging_punctuation_hangs_punctuation_but_not_letters`, `typecmd::area_tests::roman_hanging_punctuation_is_set_per_paragraph_and_saved_only_when_on` | | Hyphenation… and Justification… options | done | Eleven Indian languages use attributed patterns and preserve syllables in both composers (#4947). Hyphenation… (`ui.hyphenation`, `text.setFormat`) sets each paragraph's Words Longer Than, After First, Before Last, Hyphen Limit, Hyphenation Zone (Single-line Composer only) and Hyphenate Capitalized Words, and paragraph styles carry them (#2310). Justification… (`ui.justification`, `text.setFormat`, #2755) sets Word Spacing, Letter Spacing and Glyph Scaling (Minimum, Desired, Maximum), Auto Leading and Single Word Justification; Desired applies to every line, justified lines and the Every-line Composer use the ranges. Vertical type isn't glyph scaled. Auto Leading also sets the Leading the Character panel shows for Auto type, the leading Alt+↑/↓ (`type.step`) steps from, per paragraph, and the lines Fill with Placeholder Text counts. Evidence: `crates/text/src/tests/justify.rs`, `dialogs::justification::tests`, `tests_prefs::auto_leading_steps_and_fills_from_the_paragraph_auto_leading`, `panels::character` test `leading_field_shows_the_paragraph_auto_leading` | | Tab stops and leaders; Tabs panel | partial | Tabs panel and stops with leaders in the model (`text.tabs.set`); a stop drags from where the press landed (#1458); leaders fill the tab's gap, repeated on a grid so they line up from line to line (#1877); Ctrl-dragging a stop (Command on macOS) moves all the stops together; in right-aligned area type the text before a line's last tab sits at its stops, from the left edge, and the text after it against the right edge, as Illustrator's own layout in a user's `.ai` sets a price list (evidence: `tests::right_aligned_area_type_sets_the_text_after_its_last_tab_against_the_edge`; centred lines are still aligned as a whole); in justified area type the text up to a line's last tab keeps its spacing and its tabs their stops, and the text after the last tab takes the line's room to the far edge, VectorCraft's own rule (evidence: `tests::justify::a_justified_line_with_a_tab_spreads_the_text_after_it_to_the_edge` and the other tab tests in `crates/text/src/tests/justify.rs`) | -| Hidden characters (Show Hidden Characters) | done | `type.hiddenCharacters` | +| Hidden characters (Show Hidden Characters) | done | `type.hiddenCharacters`: marks spaces, tabs, nonbreaking and narrow nonbreaking spaces, the spaces of a set width, discretionary hyphens, forced line breaks, paragraph ends and the story's end, in horizontal, vertical and right-to-left type and on a path; the mark shapes are VectorCraft's own. Evidence: `canvas::tests::hidden_characters_*` | | Spell check (Check Spelling, Auto Spell Check, custom dictionary) | done | the engine (#4936): `text.spelling.check` lists the unknown words of the document's type, each run in its Language, at the bytes `text.editRange` changes, and `text.spelling.suggest` gives suggestions, both from craft-proof, each paragraph on its own (English from the first dictionary it finds: a Hunspell dictionary in the user's dictionaries folder, the SCOWL dictionary built in from craft-i18n, a system Hunspell dictionary, and last the public-domain Moby word list built into it; other languages from the dictionaries craft-proof finds for them). The custom dictionary commands are done: `text.spelling.addWord`, `removeWord` and `changeWord` (Add, and Edit Custom Dictionary's Add, Delete and Change), and `text.spelling.dictionary` lists the words, saved to `Custom Dictionary.txt` beside the preferences; Ignore All: `text.spelling.ignoreAll` skips a word in the active document while it is open. Auto Spell Check is done: Edit › Spelling › Auto Spell Check (`edit.autoSpellCheck`, off at first, saved with the view settings) draws a red wavy line under the unknown words of the visible type, leaves out type with effects, and follows edits, the custom dictionary and Ignore All. A right-click on an underlined word lists the words its dictionary suggests (each replaces it in one undo step, `text.editRange`), or No Suggestions, then Ignore All and Add to Dictionary, and a right-click on type has Spelling › Auto Spell Check, checked while it is on. Edit › Edit Custom Dictionary… lists the custom dictionary's words, with an Entry field and Add, Delete and Change, applied on Done (Cancel leaves the dictionary as it was). The modal Check Spelling dialog is done: Edit › Spelling › Check Spelling… (`Cmd+I`, `ui.checkSpelling`) opens a modal dialog displaying the unrecognized word in sentence context ("Not in Dictionary"), a list of suggestions with double-click or selection to replace ("Change to" field), and action buttons: Ignore, Ignore All, Change (one-step Undo/Redo via `text.editRange`), Change All (batched across occurrences in a single undo step), Add to Dictionary (`text.spelling.addWord`), Done and Cancel, with keyboard navigation (Tab between controls, Enter to Change or Done, Escape to close). Evidence: `crates/engine/src/tests/spelling.rs`, `crates/ui-egui/src/canvas/tests.rs` (`auto_spell_check_*`), `crates/ui-egui/src/tests/contextmenu.rs` (the right-click), `crates/ui-egui/src/dialogs/custom_dictionary.rs` (the dialog), `crates/ui-egui/src/dialogs/check_spelling.rs` (the Check Spelling dialog). | | Smart Punctuation, Change Case, Find & Replace | done | Type › Smart Punctuation… opens a dialog with the ff, fi, ffi and ff, fl, ffl ligatures, Smart Quotes, Smart Spaces, En, Em Dashes, Ellipses and Expert Fractions, Replace In and Report Results, which lists the count of each replacement; ligatures and fractions are written only where the font has a glyph for them. Evidence: `tests::menucmds::smart_punctuation_ligatures_spaces_and_fractions_are_counted`, `smart_punctuation_skips_ligatures_and_fractions_the_font_lacks`, `smart_spaces_keeps_one_space_after_a_period`, `dialogs::smart_punctuation::tests::menu_item_opens_the_dialog_and_ok_reports_the_counts` | | Alt + numeric-keypad codes while typing (Windows: `Alt+0176` → °) | partial | #5108: on Windows the character Windows posts when Alt comes up after keypad digits is typed at the caret like any other, in the typing's undo step, and the keypad digits typed with Alt run no shortcut. With NumLock off the keypad keys (Insert, End, arrows, Clear, Home, Page Up/Down without the extended-key flag) count as digits too and don't move the caret (`windows_alt_codes` unit tests; neither NumLock on nor off has been tried on a Windows machine yet). `type.insert {code}` (Windows Alt+0 code, Windows-1252 for 128–159) and `{unicode}` (hex code point) insert a character by its code (`menucmds::insert_a_character_by_its_code`). macOS and Linux have no such system convention and egui reports a keypad digit as the top-row digit, so there it does nothing; a floating panel window doesn't receive the character | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index bac3440fc0..67f4d80405 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,9 +1,11 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (Layers panel: Alt over the list shows the copy cursor while rows or the selected-art square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selected-art square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > +> Selection update (2026-11-11): path and compound-path interiors follow enabled non-None fill rows, including lower fills beneath a top None row (#6625). Hidden-only interiors miss; zero-opacity fills remain selectable. Cap/join follow-up (2026-11-12): hidden-fill and no-fill stroke hits must respect cap and join geometry; focused cap/join CPU regressions passed. Scores and estimates unchanged. +> > Vector Halftone preview update (2026-11-10): temporary dot selection marks are hidden, and the bounding box stays available (#6369). > > **Eraser fill update (2026-11-11):** filled open paths without a visible painted stroke retain fill outside the sweep or Alt-drag marquee (#6582); stroked paths retain main behavior; scores and estimates unchanged. @@ -60,6 +62,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | 2026-11-09 | minor | Document Setup and Character panel Language lists: Nepali, Konkani and Sindhi complete #4943; Assamese and Sanskrit are already present from #5946. Names in all 27 catalogs come from [CLDR locale language-name data](https://github.com/unicode-org/cldr/tree/main/common/main). The public [language assignment documentation](https://helpx.adobe.com/illustrator/using/spelling-language-dictionaries.html) describes the Character panel Language menu, but does not establish that these five languages are listed there; inclusion and a single Sindhi entry remain maintainer decisions. Scores unchanged | | 2026-11-14 | minor | G5: Tech Circuit adds three original procedural brushes (Circuit Trace, Bus Lines, Terminal Nodes); ten built-in brush libraries. G5 remaining estimate 3–13 h (estimated); parity scores and headline totals unchanged. | | 2026-11-14 | minor | Layers panel: right-clicking a layer/group/object row shows a context menu with Options…, Duplicate, Delete, Lock/Hide Others, Locate Object, and Collect for Export — matching standard desktop layer panel conventions. Scores unchanged. | +| 2026-11-16 | minor | Layers panel: an Alt-drag copies a row above or below its own place, so the top layer dragged up, the bottom layer dragged down and a document's only layer are copied (#8237). Scores and estimates unchanged. | | 2026-11-16 | minor | Layers panel: rows or the selected-art square dragged over the list show the copy cursor while Alt is held, as the drop then copies, and the grabbing hand otherwise (#8217). Scores and estimates unchanged. | | 2026-11-16 | minor | Gradient panel: the strip under the ramp, where a click adds a stop, shows the white arrow with a plus on Windows and X11, where the system copy cursor showed as the plain arrow (#8241). Scores and estimates unchanged. | | 2026-11-13 | minor | Pencil cursors: the continuation cursor (a short rising line) shows over an open end of a selected path before any press, freehand too, and while a continuing stroke nears another selected path's open end it connects to; the straight-line cursor is a short level line; a continued path, a straight line too, shows the closing cursor and closes within Close Paths When Ends Are Within of its other end, and with Alt at the release. Scores and estimates unchanged. | @@ -169,6 +172,7 @@ tools, never checked side by side) isn't captured row by row. | Cmd/Ctrl lends the last-used selection tool | done | the path being drawn continues afterwards; with Direct Selection (the default until a selection tool is chosen) a Cmd drag moves an anchor of the path being drawn, moves a straight segment or bends a curved one, one undo step each, and a Cmd-click away from art ends the path; with Selection the hidden bounding box of the path being drawn takes no press, so the drag moves the path (#4980); anchors or segments the lent Direct Selection picks are what Copy and Cut take, as with Direct Selection chosen, while Copy with the Pen's own last anchor selected takes the whole path (#6123) | | Click an open path's end to continue it; click another path's end to join | done | #776 | | Rubber Band preview | done | Preferences option | +| P while the Pen draws a path ends the path, as Escape does | done | the [help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/preview-paths-drawn.html) describes P with the preview off; VectorCraft's own rules: it does the same with Rubber Band on, a click on the active Pen's button and `tool.select` do the same, and the Pen stays chosen | | Auto Add/Delete on a selected path; Shift or the preference disables it | done | | | Pen cursors (new path ×, continue /, close o, add +, delete −, convert ^) | done | the nib is a fountain-pen nib, tip on the hotspot, with the slit widening into the breather hole and the heel clipped square to its axis; bitmap tests at 1× and 2× pin the nib and the new-path asterisk, and in-app screenshots compare the Pen with Direct Selection | | Node-editing cursors: Direct Selection's white arrow with a hollow or filled square over an anchor (path unselected or selected); the Reshape Segment cursor over a curved segment (Direct Selection, Anchor Point, the Pen with Alt); the Anchor Point caret for the Pen with Alt; Group Selection's plus (also Direct Selection with Alt); a filled arrow while dragging that turns hollow on a snap; a double arrowhead for an Alt-drag copy | partial | as the public manual describes them, drawn in code; no cue over handles (none documented) | @@ -192,6 +196,7 @@ tools, never checked side by side) isn't captured row by row. | Layers panel: a layer whose Layer Options › Print is off shows its name italic (#5739) | done | the panel row and its drag ghost; a printing layer stays upright, and Print on again restores it; `panels::layers` test `a_layer_that_does_not_print_has_its_name_italic` | | Layers panel: Alt-drag shows the copy cursor (#8217) | done | rows and the selected-art square dragged over the list show the copy cursor while Alt is held and the grabbing hand otherwise, following Alt mid-drag; on Windows and X11 the copy cursor is the white arrow with a plus (the panels' add cursor, #8241); over the trash and New Layer, which ignore Alt, the hand stays; guide rows keep theirs; `alt_shows_the_copy_cursor_while_rows_are_dragged`, `drag_cursor_shows_a_copy_only_where_the_drop_copies` | | Gradient panel: add-stop cursor under the ramp (#8241) | done | the white arrow with a plus (the Group Selection glyph) over the strip under the ramp, handed to the OS on Windows and X11 (winit shows the plain arrow for the system copy cursor there), the system copy cursor elsewhere; over the ramp itself the arrow stays; `panels::gradient` test `the_strip_under_the_ramp_shows_the_add_cursor` | +| Layers panel: Alt-drag copies a row beside itself (#8237) | done | with Alt, rows held over one of their own rows copy above or below it, and the bottom layer dropped in the empty space under the list copies below itself, so the top layer dragged up, the bottom one dragged down and a document's only layer are copied; a move onto its own place, or a copy inside itself, still does nothing; `panels::layers` tests `alt_dragging_the_top_layer_up_or_the_bottom_layer_down_copies_it`, `a_lone_layer_alt_dragged_up_or_down_is_copied`; engine test `a_copy_goes_above_or_below_a_row_it_copies` | | Blend spine Anchor Point conversion and handle editing (#2544) | implemented | symmetric handles, independent drag/retraction, visible-handle policy and selection/stacking covered by tool and engine regressions; Windows native canvas checks and screenshots reviewed in PR #2643 | | Several blend spine points picked and dragged together (#5285) | done | with Direct Selection, Shift-click picks more points of a selected blend's spine or takes one away, as on a path; dragging any picked point moves them all, and the key objects on them, in one undo step (`object.blend.spine.moveAnchor {with}`); a marquee picks the spine points inside it on the topmost selected blend, and with Shift adds or takes them away | | Add/Delete/Anchor Point tools; Anchor Point tool drags segments to reshape | done | #2267: a click on a handle end retracts that handle and leaves the anchor a corner with the other one; Shift held at the press on an anchor moves it, handles and all (Shift kept down: at 45° steps) instead of pulling out handles | @@ -213,6 +218,7 @@ tools, never checked side by side) isn't captured row by row. | Behaviour | Status | Notes | |---|---|---| +| Path and compound-path interior selection follows enabled non-None fill rows | done | #6625; lower visible fill beneath a top None row stays selectable; hidden-only/None interiors miss; zero-opacity, edge, Outline/path-only and hole controls in `crates/engine/tests/path_fill_hits.rs`; hidden-fill and no-fill stroke cap/join CPU regressions passed | | Deleting segments or anchors that disconnect an ordinary path creates independent selected objects | done | #3380, deletion only: first piece retains its ID, styles and transforms carry over in sibling order, bounds-fitted gradients keep their original placement, and one Undo restores the original. Existing multi-subpath paths and compound members stay intact. `delete_path_pieces` covers transformed/styled rectangles, cubic handles and Undo/Redo. Endpoint highlighting remains open. | | Click/Shift-click anchors; marquee toggles with Shift | done | #483 | | Align selected anchors to their bounds or the artboard; repeating an alignment that moves nothing keeps Undo, Redo and saved state | done | #1180 follow-up; engine regressions include rounding-only moves and unchanged handles; #1641 (fixes #1636): Align and Distribute act on the anchors selected with Direct Selection, the points of one path aligning to each other and Distribute spacing them | @@ -242,7 +248,7 @@ tools, never checked side by side) isn't captured row by row. | Live Corners widgets (radius readout, Alt-click cycles kind, double-click the Corners dialog) | done | a Direct Selection click on a widget selects its corner (#1239), and with every corner selected a Shift-click on a widget picks that corner alone instead of deselecting it (#5188); a press-and-drag on a widget of a path selected whole still rounds every corner (#908), and adding widgets to the selection by Shift-click (#1232) is missing; the bounding box hides while a widget is dragged with the Selection tool (#1229); a round corner next to a curved side curves smoothly instead of sticking out of the shape (#1512); a corner rounds until its cut reaches its neighbours' cuts, so one corner of a square alone reaches the whole side (#2332) | | Corners between curved sides (#1144), Relative rounding | done | #1144 closed; Relative rounding in the Corners dialog (Relative / Absolute, radius as a percentage of each corner's maximum, kept as the shape is resized; `object.setLiveShape` `relativeRadii`, #3091, `tests_livecorners::relative_corner_rounding_keeps_fraction_on_resize`) | | Pie widgets on a live ellipse: drag one to set Pie Start or End Angle, double-click one to make the ellipse whole | done | Selection tool, with the bounding box showing | -| A shape just drawn shows its bounding box and Live Shape widgets with the shape tool still active, and the selection can be moved and turned without switching tools | done | #5477: Rectangle, Rounded Rectangle, Ellipse, Polygon and Star keep the selection's bounding box, corner widgets and pie widgets on show while they draw nothing; a drag on a corner or pie widget adjusts it (arrows step the corner kind, Escape cancels), a press on the selection's centre point (Attributes › Show Center) moves the selection — the Selection tool's move arrow, snapping and Alt copy — a press just outside a corner of the box turns it about the centre (the Selection tool's rotate zone and cursor), and a press anywhere else draws (so a second shape drawn from the first one's centre moves the first: press elsewhere or deselect first). Public descriptions: [Live Shapes](https://helpx.adobe.com/illustrator/using/live-shapes.html) (live shapes adjust without switching tools) and [CreativePro, Working with Live Shapes](https://creativepro.com/?p=23921) (a widget shows in every corner on release; drag one toward the centre to round). The bounding-box handles show but scale only with the Selection tool, so a press on a corner still starts a new shape there; double-clicking a widget opens nothing with a shape tool. Tests `a_shape_tool_drags_the_selected_shapes_widgets` and `a_shape_tool_moves_the_selection_by_its_centre_point_and_turns_it_from_a_corner` | +| A shape just drawn shows its bounding box and Live Shape widgets with the shape tool still active, and the selection can be moved and turned without switching tools | done | #5477: Rectangle, Rounded Rectangle, Ellipse, Polygon and Star keep the selection's bounding box, corner widgets and pie widgets on show while they draw nothing; a drag on a corner or pie widget adjusts it (arrows step the corner kind, Escape cancels), a press on the selection's centre point (Attributes › Show Center) moves the selection — the Selection tool's move arrow, snapping and Alt copy — a press just outside a corner of the box turns it about the centre (the Selection tool's rotate zone and cursor), and a press anywhere else draws (so a second shape drawn from the first one's centre moves the first: press elsewhere or deselect first). Public descriptions: [Live Shapes](https://helpx.adobe.com/illustrator/using/live-shapes.html) (live shapes adjust without switching tools) and [CreativePro, Working with Live Shapes](https://creativepro.com/?p=23921) (a widget shows in every corner on release; drag one toward the centre to round). A drag on one of the box's handles scales the selection as the Selection tool's handles do. A double-click on a corner widget of a selected live rectangle or polygon shows and selects the Transform panel where it is (closed, docked, floating or in an icon column; a second double-click keeps it on show), and leaves the tool, the selection and the document as they were; a double-click on a pie widget, off the widgets, with Show Corner Widget off or with Line Segment does nothing, and the Selection tool's double-click on a corner widget still opens the Corners dialog. Public description: [Live shape properties](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/live-shape-properties.html) (a double-click on a corner widget of a selected live shape opens the Transform panel). Tests `a_shape_tool_drags_the_selected_shapes_widgets`, `a_shape_tool_moves_the_selection_by_its_centre_point_and_turns_it_from_a_corner`, `a_shape_tool_scales_the_selection_by_its_bounding_box_handles`, `a_double_click_on_a_corner_widget_shows_the_transform_panel`, `a_double_click_on_a_corner_widget_with_a_shape_tool_asks_for_the_transform_panel` (engine), `a_corner_widget_double_click_with_a_shape_tool_requests_the_transform_panel` (MCP: the `pointer_gesture` reply's `requests` carry `{"panel": "transform"}`) and `a_tools_panel_request_shows_the_panel_and_a_second_keeps_it_shown` (UI) | | Isolation mode by double-click (groups and single objects), breadcrumbs, Esc to exit | done | Single paths, compound paths, images, meshes and placed files isolate too ([helpx: Isolate objects](https://helpx.adobe.com/africa/illustrator/desktop/manage-objects/select-objects/isolate-objects.html)); locking or hiding the layer (or a group) around the isolated object afterwards keeps clicks and marquees off it, as outside isolation mode (#5309) | | "Magnetic" moves of selected anchors with a modifier (#955 request) | missing | not a feature of the reference app as documented; under discussion | | Coinciding anchors of overlapping objects: the selected object's anchor is taken, also under another object | done | #1508 | @@ -405,6 +411,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po |---|---|---| | Effect > Warp Options: style previews, orientation choices and percent controls | done | #1760; focused input, mixed-style and history checks passed; original captures reviewed. No geometry or optional Properties changes. | | Command search: Up and Down move through the results, Enter runs the highlighted one | done | #1798 (#1757) | +| Help › VectorCraft Help… and F1 show in-app search for tools, menu commands, and built-in tutorials. Tool results mark their toolbar location; command results show their menu path and shortcut without running them; tutorial results show their steps. Home clears the search, Back returns to the results, and Escape in the search field closes the panel. | partial | [Public source](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/learn-with-discover-panel.html); `help.discover`, `help.discover.search`, `help.discover.choose`, `help.discover.back`; `menus::tests::help_f1_opens_discover_without_a_document`. Articles, Quick Actions, and Discover preferences are not implemented. Menu-path text instead of a menu location marker is VectorCraft's current guidance. | | Learn panel: Window › Learn and Explore tutorials on the app bar open it; For you holds a Quick skill guide card, Skills lists VectorCraft's own skills with progress rings that fill and counts of tutorials finished, a tutorial shows its numbered steps with a check box each that marks the step done once its sample is open, a finished tutorial has a check mark, Back goes up a level; a tool's name in a step is a link that marks the tool where the toolbars show it (its button, its group's flyout, a torn-off strip, a toolbar made with New Toolbar or the All Tools drawer) without choosing it; View more opens the tutorial's practice sample as a new untitled document, Finish tutorial then marks it finished with all its steps, and Next Up shows the next tutorial in the same skill; Reset progress clears the progress (no video) | done | [the help page](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/learn-skills-quick-skill-guide.html); `learn.list`, `learn.tab`, `learn.skills`, `learn.skill`, `learn.show`, `learn.back`, `learn.locateTool`, `learn.openSample`, `learn.markStep`, `learn.finish`, `learn.next`, `learn.resetProgress`; the mark's look and 3-second lifetime, marking steps by hand, keeping the progress in the preferences and Reset progress are VectorCraft's own rules; `panels::learn::tests`, `toolbar::tests` | | Pathfinder panel: a group selected alone counts its nested shapes, so an expanded stroked object keeps the Shape Modes enabled | done | #1642 (#1635) | | Selected Grid Repeat shows row, column and corner handles and spacing sliders; bounding-box handles take priority where they meet | done | #2691, `tools/src/repeat_grid.rs`; [public behavior reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-grid-repeat-options.html); drags preview and commit `object.repeat.options` as one undo step, Escape cancels; a selected Radial Repeat shows an instances handle below it (16 px of drag per instance, 1 to 1,000) and a radius handle on its circle the same way (`tools/src/repeat_radial.rs`; [public behavior reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/create-radial-repeats.html)), and a splitter on its circle that hides the instances it is dragged back past while the others keep their places, and shows them again when dragged forward (its place half a step past the last instance shown and its limit of one instance shown are VectorCraft's own rules) | @@ -430,7 +437,8 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Live trace result bounds and selection highlights exclude the retained bitmap; source-image views retain it | done | All TraceView modes and rotated result bounds regression-covered; ordinary hidden group behavior retained | | Image Trace panel: the Preview checkbox before Trace chooses whether a setting change traces the selected Image Trace object again at once | done | Per the public documentation, Preview shows the result of the current settings and Trace traces with them (). Preview is on by default and kept with the UI preferences; Reset to Default leaves it. Off, changes wait in the panel until Trace applies them as one undo step, or until Preview is turned on again. Changes stay with the object they were made for while another object is selected, and come back when it is selected again. `imageTrace.preview {on?}`, `ui.set {imageTracePreview}`; `panels/image_trace.rs` headless tests (`with_preview_off_a_slider_change_waits_for_trace`, `turning_preview_on_traces_the_changes_that_waited`, `preview_turned_on_with_nothing_selected_traces_when_the_object_is_selected_again`, `settings_that_wait_stay_with_their_object`, `settings_that_wait_come_back_when_their_object_is_selected_again`, `settings_that_wait_are_dropped_when_their_object_changed_since`, `preview_is_kept_with_the_preferences_and_reset_to_default_leaves_it`) | | Toolbar without group labels by default, one or two columns; All Tools drawer by flyout group with shortcuts, its menu (Reset, Basic, Advanced) and Show section | done | #1751; a preference brings the labels back; `toolbar.show` sets the Fill/Stroke, Coloring, Draw Mode and Screen Mode controls | -| Actions panel: ≡ › Save Actions… saves the current set with all its actions to a file and ≡ › Load Actions… adds a saved set ([Manage a set of actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/manage-a-set-of-actions.html)) | partial | `ui.actionSet.save`, `ui.actionSet.load`; `panels/actions.rs` tests. The file is VectorCraft's own `.vcactions` JSON; Clear and Replace Actions remain | +| Actions panel: ≡ › Save Actions… saves the current set with all its actions to a file and ≡ › Load Actions… adds a saved set ([Manage a set of actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/manage-a-set-of-actions.html)) | partial | `ui.actionSet.save`, `ui.actionSet.load`; `panels/actions.rs` tests. The file is VectorCraft's own `.vcactions` JSON; Clear Actions remains | +| Actions panel: ≡ › Replace Actions… puts the set of a saved file in place of every set in the panel ([the help page](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html)) | done | `ui.actionSet.replace`; `panels/actions.rs` tests. The file is read as Load Actions… reads it; the item asks no question first | | Actions panel: ≡ › Reset Actions asks first; OK replaces the sets in the panel with the default set and Append adds the default set after them ([the help page](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/manage-a-set-of-actions.html)) | done | `ui.actionSet.reset`; `panels/actions.rs` and `dialogs/tests.rs` tests. The default set is VectorCraft's own Default Actions set | | Actions panel: ≡ › Load Actions… also reads action sets saved as `.aia` files ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html)) | partial | `actionSet.read`, `ui.actionSet.load`; `tests/actionset.rs`, `panels/actions.rs` tests, `import_fuzz`. Steps with a label and no recorded values come in as menu commands that run with no values and open no dialog, matched by label, and Set Selection steps come in as Select Object steps; the other steps, recorded menu items included, are left out and counted | | Actions panel: ≡ › Action Options… renames the selected action and sets its function key and color ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html)) | partial | `ui.action.options`; `panels/actions.rs` tests (part of #1629). Button Mode shows the color | @@ -449,10 +457,11 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Control bar: Paragraph: link and Align left/center/right while type is selected (#5372) | done | After the Character controls, as the public documentation has the Control panel format paragraphs ([Paragraph panel overview](https://helpx.adobe.com/illustrator/using/formatting-paragraphs.html), [Align text](https://helpx.adobe.com/illustrator/using/align-text.html)); the link opens the Paragraph panel in a popover, as Character: does with the Character panel. The bar trims from its right end: X/Y/W/H, Distribute, Align, area type vertical alignment, then these buttons, then the link. The three-button set is our choice for room; all seven alignments are in the popover. `panels/paragraph/tests.rs` headless tests (`the_control_bar_shows_the_paragraph_alignment_of_the_selected_type`, `the_control_bar_trims_its_paragraph_section_after_the_controls_to_its_right`) | | Pathfinder shape results keep their source names and SVG IDs | done | #1293; Minus Front keeps the back name, Minus Back the front name; Unite/Intersect/Exclude use the backmost named input; compound output carries it once; geometry and paint unchanged | | Attributes fill-rule controls with a compound member selected | done | Edits the compound's rule; direction still edits only the member; rendered-hole and Undo/Redo regression tests (#1197) | -| Info panel follows the tool in use: W and H show the change in x and y, with the distance and the angle, while the selection moves or the Gradient tool draws a vector; the Scale tool's percentages; the center and angles of a Rotate, Reflect or Shear tool drag; the Zoom tool's magnification; the Paintbrush's brush. W and H follow Use Preview Bounds, several selected objects show only the paint and type they share, and Show Options names a tint or a gradient swatch | done | `info.readout`; `Tool::readout`; behavior from the Info panel overview in the [archived user guide](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=76); number formats, the rows shown between drags and the Direct Selection and Group Selection readouts are VectorCraft's own | +| Info panel follows the tool in use: W and H show the change in x and y, with the distance and the angle, while the selection moves, the Gradient tool draws a vector or a Pen drag pulls out an anchor's handle; the Scale tool's percentages; the center and angles of a Rotate, Reflect or Shear tool drag; the Zoom tool's magnification; the Paintbrush's brush. W and H follow Use Preview Bounds, several selected objects show only the paint and type they share, and Show Options names a tint or a gradient swatch | done | `info.readout`; `Tool::readout`; behavior from the Info panel overview in the [archived user guide](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=76); number formats, the rows shown between drags and the Direct Selection and Group Selection readouts are VectorCraft's own | | Make Compound Path on a group (such as outlined type) keeps its backmost path's paint; compound paths joined into one keep their holes | done | #1537 | | Symbol libraries: Window › Symbol Libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, User Defined, Other Library…, Save Symbols…) and the Symbols panel's Symbol Libraries Menu button and its menu's Open Symbol Library / Save Symbol Library…; a click on a library symbol adds it to the document's Symbols (one undo step, it becomes the current symbol), Shift/Cmd-clicks select for Add to Symbols, and a symbol dragged onto the canvas is added and placed where it is dropped | done | [public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), [placing from a library](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html); `window.symbolLibrary`, `window.symbolLibrary.other`, `ui.saveSymbolLibrary` (dialog `saveSymbolLibrary`), `window.userSymbolLibrary1`…`10`; `panels::tests_symbol_libraries`; five built-in libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons; original, generated in code) | | Brush libraries: Window › Brush Libraries (Art Ribbons, Ink and Wash, Calligraphic Nibs, Bristle Brushes, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, Dry Media, Tech Circuit, User Defined, Other Library…, Save Brushes…) and the Brushes panel's Brush Libraries Menu button and its menu's Open Brush Library / Save Brush Library…; a click on a library brush adds it to the document's Brushes (one undo step, it becomes the current brush, and selected paths take it in the same step), Shift/Cmd-clicks select for Add to Brushes, a brush dragged onto a path is added and applied to it and one dragged onto the Brushes panel is added; thumbnails render with the library's patterns and symbols | done | [public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel overview](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html); `window.brushLibrary`, `window.brushLibrary.other`, `ui.saveBrushLibrary` (dialog `saveBrushLibrary`), `window.userBrushLibrary1`…`10`; `panels::tests_brush_libraries`; ten built-in libraries (original, generated in code) | +| Brushes panel menu › Options of Selected Object…: changes the selected brushed paths' brush settings on those paths only, leaving the brush and its other strokes as they are; the brush type's options dialog opens without the Name row (and without an art brush's scale and direction options or a pattern brush's tiles), and OK sends only the values changed in it | done | [Modify brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/modify-brushes.html), [Brushes panel overview](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html); `brush.objectOptions`, `ui.brushObjectOptions`; which fields a path can set is VectorCraft's own choice (calligraphic, scatter, art and pattern brushes; not bristle); `options_of_selected_object_*` tests in `crates/engine/src/tests/brushsym.rs` and `crates/ui-egui/src/dialogs/brush_options/tests.rs`, brush tests in `crates/brush/src/tests.rs` | | Symbols panel: New Symbol opens Symbol Options (Name) before making the symbol; Alt-click skips it | partial | #1560 (#1566); Registration 9-point grid in Symbol Options (`symbol.new` / `symbol.place`); Export Type (Graphic / Movie Clip) and Enable Guides for 9-Slice Scaling (scaled instances keep their corners; in symbol editing mode the guides are drawn over the art and the Selection tool drags them); Symbol Type (Dynamic Symbol / Static Symbol, new symbols dynamic; #4938); Align to Pixel Grid (`alignToPixelGrid` on `symbol.new` / `symbol.options`: the art snaps at the symbol's natural size and instances at that size stay on whole points; [Aligning symbols to pixel grid](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=28)) | | Dynamic symbols: an instance changes the fill, stroke, opacity and blend of objects in its symbol's art and stays linked; Reset in the Properties panel's Quick Actions and the Symbols panel menu (Reset Symbol Instance) | partial | #4938; `symbol.instance.setAppearance` (by child-index path) and `symbol.instance.reset`; redefining keeps the changes, Break Link bakes them; Direct Selection of a path, compound path or type object inside an instance, with the Fill/Stroke controls setting its solid fill or stroke, is on canvas; on-canvas editing beyond a solid fill and stroke, and `.ai` read and write, remain | | Pathfinder Trim, Merge and Crop remove strokes; Merge joins same-fill objects whatever their strokes | done | #1570 (#1572) | @@ -478,6 +487,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Status bar: a click on the info field opens a Show menu that chooses its readout: Artboard Name, Current Tool (the default), Date and Time, Number of Undos (undo and redo counts) or Document Color Profile; kept with the UI state | done | `view.statusBarShow`; [public behavior reference](https://web.archive.org/web/2014/https://helpx.adobe.com/illustrator/using/workspace-basics.html); `the_status_bar_info_field_shows_the_chosen_readout`, `a_click_on_the_info_field_opens_the_show_menu`, `the_status_bar_show_choice_is_checked_and_saved`. The menu labels are VectorCraft's own | | Background Export: a progress dialog with the file name, the artboard count and a bar (busy for one artboard and for formats made in one go), Cancel (Esc) and Continue in Background; it opens after 0.4 s and never over another dialog. A cancelled export writes no file | done | #2564; on the shared `vectorcraft_doc::cancel` token (#2546), so a cancelled render keeps no half-drawn pattern tile or effect raster. The bar moves between artboards, not within one. Save As, Export for Screens and Export Selection don't show it yet | | Swatch, graphic style and symbol library panels: each library opens in a panel of its own, several at once, that floats, groups, docks and closes like any panel; opening an open library brings its panel forward; Previous / Next Library change the library in place; the panel menu's Persistent reopens the panel at startup with its view and find field (a library loaded from a file is read again; when its file is missing the panel reopens showing the file's path with Locate Library…, and the status bar names the file) | done | #2603; panel ids `library::`, `ui.libraryPanel {panel, library?, view?, showFind?, persistent?}`, `ui.libraryPanel.locate {panel, path?}`; the library panels have no sort option, as before | +| Raster export dialogs retain supplied values for their controls and apply defaults only to omitted values | done | #8324; `tests_raster_supplied_options` checks PNG resolution, background, anti-aliasing and interlacing through `file.export.png`, JPEG quality, omitted defaults, and invalid resolution rejection | | DXF export/import preserves intended curve closure | done | #1299; R13–2018 closed SPLINE bit set/read; an open curve ending at its start stays open; knots and control points unchanged; circular cubic paths export as native CIRCLE/ARC where stroke semantics permit; DXF Options' Preset menu and `document.exportDxf`'s `dxfPreset: "cnc"` set the CNC / CAM options (#5500) | | macOS save sheet: choose the format from a menu | done | #866; the save panel is VectorCraft's own `NSSavePanel` with its Format menu set before the sheet opens (`apps/vectorcraft/src/mac_save_format.rs`); #1855 had withdrawn the menu that was added after the sheet began, which made Save As, Save a Copy and the first Save show no sheet | | Preferences: every option acts | partial | 2 stored but unused (#394, audited 2026-10-30): Scratch Disks, Legacy vector clipboard; the rest act (Units › East Asian Type since 2026-10-31; Open Documents As Tabs: cleared, new documents open in floating windows). General › Corner Radius drives the Rounded Rectangle tool and follows its ↑/↓ (2026-10-24) | @@ -500,6 +510,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Set Corners… (also a button in the Anchor Inspector's Corners section: Radius in any unit, Corner kind, Anchors: All, Odd-Numbered or Even-Numbered, counted from each path's first anchor; Angle: from … to …°, only the corners whose sides meet at an angle in that range; Preview) cuts corners on the chosen anchors of every selected path, one undo step | done | #5546, #5545; `addon.pathtools.cornerSet` (`every`, `minAngle`, `maxAngle`), `crates/ui-egui/src/addons/pathtools/set_corners.rs` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Trim at Crossings Tool (also in the Scissors tool's group in both shipped toolbars, after the Knife, and listed there in the All Tools drawer; a toolbar edited before keeps its saved layout until Reset Toolbar; no shortcut until one is set in Edit › Keyboard Shortcuts › Tools; the Knife's cursor, drawn as a knife with the blade's point on the hotspot) removes stretches of paths between the places where they are crossed, on any editable path, selected or not: a click removes the stretch under the pointer, a drag removes every stretch its rectangle touches, and an Alt-drag removes every stretch its freehand line crosses; one undo step each; Escape during a drag removes nothing; hovering shows in red the stretch a click would remove, and a drag that reaches few paths shows what its release would remove | done | `addon.pathtools.trim` (in `crates/engine/src/cmd/addons/pathtools/trim.rs`), `crates/tools/src/addons/trim.rs` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Expand Dashes into Paths turns each selected path's dashed stroke into separate open paths, one per dash, laid out as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off; one undo step | done | #4922; `addon.pathtools.expandDashes` (in `crates/engine/src/cmd/addons/pathtools.rs`, using the renderer's dash layout) and its tests; not a feature of the reference app, so it is not scored | +| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Smooth Bridge… (Radius as a percentage of the smaller circle's radius, Keep Originals; Preview) joins two selected circles into one outline with two concave arcs that touch both circles, in place of the circles or above them; one undo step | done | `addon.pathtools.bridge`, `crates/pathops/src/addons/pathtools/bridge.rs`, `crates/ui-egui/src/addons/pathtools/bridge.rs` and their tests; a VectorCraft addition, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Tangent Circle… draws the circles that touch two selected paths or compound paths at a radius, or three of them, each touching the outlines without crossing them; Radius (two shapes), a Circle menu (All or one by number) and Preview; one undo step | done | `addon.pathtools.tangentCircle` (in `crates/engine/src/cmd/addons/pathtools/tangent_circle.rs`, geometry in `crates/pathops/src/addons/pathtools/tangent_circle.rs`) and its tests; a VectorCraft addition, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Effect › Path Effects lists its live effects (Dashes to Geometry, Add Anchors, Extend Path, Close Path, Smooth Anchors, Retract Handles, Reverse Direction, Simplify Anchors, Split at Anchors), each with the effect dialog's live Preview except Reverse Direction, which has no options, and listed in the Appearance panel like any effect | done | `addon.path.*`, `crates/effects/src/addons/path.rs`, `crates/ui-egui/src/addons/pathtools.rs` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools selects its four tools (Anchor Eraser Brush, Extend Path, Measure & Inspect, Parametric Shape), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped, opens the Anchor Inspector panel (the selected anchor's X/Y and handle lengths and angles as fields; Make Smooth, Make Corner, Equalize Handles, Remove Points Keep Shape, Add Points, the three ways to close) and the Parametric Shape panel (kind, count, W/H, rotation, the kind's own values and corner radius of the selected parametric shape, or of the tool's next one), and runs Add Points at / Split at Crossings and Convert to Parametric Shape; the Parametric Shape Tool draws ten re-editable kinds from the centre (↑/↓ and ←/→ change their numbers while dragging) and edits a selected one with handles; a double-click on the brush or Extend Path tool opens its options | done | `addon.pathtools.*`, `crates/tools/src/addons/`, `crates/ui-egui/src/addons/pathtools.rs`, `crates/ui-egui/src/addons/pathtools/shape.rs` and their tests; not a feature of the reference app, so it is not scored | @@ -582,6 +593,7 @@ before release (#6373). [Paint faces and edges](https://helpx.adobe.com/illustra | 2026-11-12 | minor | Remove Background for a selected image in the Contextual Task Bar, Properties › Quick Actions and the Control bar, which runs at once with its defaults. Scores and estimates unchanged. | | 2026-11-12 | minor | Live Paint Bucket fills faces crossed in one drag (#6373). Scores and estimates unchanged. | | 2026-11-12 | minor | Save refusal follow-up (#6146): changed format opens its Save options; unchanged format retains original options. Focused UI regressions passed, including the format-change case that failed before the fix; native panel acceptance pending. Scores and estimates unchanged. | +| 2026-11-12 | minor | #6625 cap/join follow-up: hidden-fill and no-fill stroke hits must respect their cap/join geometry; focused CPU regressions passed. Existing fill-stack evidence, scores and estimates unchanged. | | 2026-11-11 | minor | Ruler origin: the corner drag snaps as a drawn point does, onto the art's and the artboards' anchors, centres, edges and paths, and with Snap to Point along the ruler guides; scores and estimates unchanged | | 2026-11-11 | minor | macOS canvas cursor delivery (#2292): while the host owns the cursor it sets it again on every pass, so the tool's cursor stays after the pointer moves (#6362); `mac_cursor` ownership test updated; scores and estimates unchanged. | | 2026-11-11 | minor | Eyedropper copies effective character dimensions between transformed text objects (#6404); scores and estimates unchanged. | @@ -591,6 +603,7 @@ before release (#6373). [Paint faces and edges](https://helpx.adobe.com/illustra | 2026-11-11 | minor | Eraser: fixed and varied tips and the Alt-drag marquee cut fill-only open contours and compound holes as areas; stroked open paths retain main behavior (#6582). Scores and estimates unchanged. | | 2026-11-11 | minor | Files that record no units (PDF, EPS or `.ai` without ruler units, raster images, metafiles, Affinity files, importer plug-ins) open and revert in Preferences › Units › General instead of points; native, SVG and DXF files and `.ai`/EPS ruler units are kept (#5820). Scores and estimates unchanged. | | 2026-11-11 | minor | Blob Brush: while painting, the preview of a round tip is the outline of the area the stroke adds, round at both ends, as the stroke it commits (#4343). Scores unchanged (estimated). | +| 2026-11-11 | minor | #6625: path and compound-path interior hits follow enabled non-None fill rows, including lower fills beneath a top None row; hidden-only interiors miss; zero-opacity fills remain selectable. Scores and estimates unchanged. | | 2026-11-10 | minor | Symbol libraries: Inventory Icons joins Basic Shapes, UI Frames and Map Markers as a fourth built-in library (Sword, Shield, Potion, Key, Gem; no default 9-slice). | | 2026-11-10 | minor | Held numeric spinner arrows keep stepping past the click timeout and stop on release (#6307). Scores and estimates unchanged. | | 2026-11-10 | minor | Vector Halftone Preview leaves the dots unobscured and keeps the selection box (#6369). Scores and estimates unchanged. |