From d156bd4da6846eba861c6204fca4cf77cece4e6d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 10:55:15 -0800 Subject: [PATCH 01/31] =?UTF-8?q?Packaging=20Tools:=20Make=20=E2=80=A6=20L?= =?UTF-8?q?ine=20gives=20paths=20a=20fold=20line=20role=20that=20their=20s?= =?UTF-8?q?watch=20carries?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Object › Plug-ins › Packaging Tools is a new built-in add-on for the dielines of boxes and other folded packaging. A path, compound path or live shape is a fold line when its top stroke is painted with the swatch of a line role: Cut, Crease, Partial Cut or Perforation. Each document has a role table (`packagingRoles`) that names the swatch of each role. By default the swatches are named after the roles. Native files keep the table and the strokes. PDF prints a role line on its swatch's separation when the swatch is a spot color, as the default role swatches are. SVG, DXF and HP-GL keep the stroke's color, so the default role swatches come out as four colors. - `addon.packaging.setRole` (Make Cut Line, Make Crease Line, Make Partial Cut Line, Make Perforation Line) paints the top stroke of each path among the objects with the role's swatch at 100%, through groups and clip groups. Locked and hidden objects are left out, also when named by id. A path without a stroke gets a 1 pt stroke, a hidden stroke is shown, and the stroke overprints unless `overprint` is false. A missing role swatch is made as a global spot swatch in the document's color mode (Cut 100% magenta, Crease 100% cyan, Partial Cut 100% yellow, Perforation 50% magenta and 50% cyan). When a color group or a swatch that can't carry a role has that name, the swatch is made as "Cut 2" and so on. `none` takes the role away and keeps the color. One undo step, none when nothing changes. - `addon.packaging.roles` counts each role in the selection, or in the document while nothing is selected, locked and hidden lines included. The Fold Lines panel shows these counts, gives the selected paths a role when a row is clicked, and says when nothing is selected. - `addon.packaging.setRoleSwatch` (the panel menu's Role Swatches…) makes another global or spot color swatch carry a role. It refuses missing, gradient, pattern, process, tint, [None] and [Registration] swatches and a swatch another role has. When `swatch.edit` renames a role swatch, the role stays with it under the new name. When it turns Global off, the role moves to a new swatch name that the next Make … Line makes. When `swatch.merge` merges a role swatch into a global swatch that carries no role, the kept swatch takes the role. Docs: docs/mcp.md (Packaging Tools add-on) and ROADMAP. --- ROADMAP.md | 1 + crates/engine/src/cmd/addons.rs | 3 + crates/engine/src/cmd/addons/packaging.rs | 18 + .../engine/src/cmd/addons/packaging/roles.rs | 454 +++++++++++++++ .../engine/src/cmd/addons/packaging/tests.rs | 540 ++++++++++++++++++ crates/engine/src/cmd/plugin_call/reviewed.rs | 3 + crates/engine/src/cmd/swatch.rs | 8 +- crates/engine/tests/command_sweep.rs | 7 + crates/ui-egui/src/addons.rs | 2 + crates/ui-egui/src/addons/packaging.rs | 134 +++++ crates/ui-egui/src/addons/packaging/tests.rs | 133 +++++ crates/ui-egui/src/dialogs/command.rs | 5 + crates/ui-egui/src/i18n/bg.tsv | 17 + crates/ui-egui/src/i18n/bs.tsv | 17 + crates/ui-egui/src/i18n/ca.tsv | 17 + crates/ui-egui/src/i18n/cs.tsv | 17 + crates/ui-egui/src/i18n/da.tsv | 17 + crates/ui-egui/src/i18n/de.tsv | 17 + crates/ui-egui/src/i18n/el.tsv | 17 + crates/ui-egui/src/i18n/es.tsv | 17 + crates/ui-egui/src/i18n/fi.tsv | 17 + crates/ui-egui/src/i18n/fr.tsv | 17 + crates/ui-egui/src/i18n/gu.tsv | 17 + crates/ui-egui/src/i18n/hi.tsv | 17 + crates/ui-egui/src/i18n/hu.tsv | 17 + crates/ui-egui/src/i18n/id.tsv | 17 + crates/ui-egui/src/i18n/it.tsv | 17 + crates/ui-egui/src/i18n/ja.tsv | 17 + crates/ui-egui/src/i18n/ka.tsv | 17 + crates/ui-egui/src/i18n/ko.tsv | 17 + crates/ui-egui/src/i18n/nl.tsv | 17 + crates/ui-egui/src/i18n/pl.tsv | 17 + crates/ui-egui/src/i18n/pt-br.tsv | 17 + crates/ui-egui/src/i18n/ru.tsv | 17 + crates/ui-egui/src/i18n/sv.tsv | 17 + crates/ui-egui/src/i18n/tr.tsv | 17 + crates/ui-egui/src/i18n/uk.tsv | 17 + crates/ui-egui/src/i18n/vi.tsv | 17 + crates/ui-egui/src/i18n/zh-hans.tsv | 17 + crates/ui-egui/src/i18n/zh-hant.tsv | 17 + crates/ui-egui/src/panels.rs | 2 + crates/ui-egui/src/state.rs | 1 + docs/mcp.md | 52 ++ 43 files changed, 1837 insertions(+), 2 deletions(-) create mode 100644 crates/engine/src/cmd/addons/packaging.rs create mode 100644 crates/engine/src/cmd/addons/packaging/roles.rs create mode 100644 crates/engine/src/cmd/addons/packaging/tests.rs create mode 100644 crates/ui-egui/src/addons/packaging.rs create mode 100644 crates/ui-egui/src/addons/packaging/tests.rs diff --git a/ROADMAP.md b/ROADMAP.md index 283d7d7dff..af24ddda70 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -132,6 +132,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 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-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-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-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-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. diff --git a/crates/engine/src/cmd/addons.rs b/crates/engine/src/cmd/addons.rs index 66c67651a3..8c310878fd 100644 --- a/crates/engine/src/cmd/addons.rs +++ b/crates/engine/src/cmd/addons.rs @@ -8,6 +8,7 @@ mod contour; mod cutting; mod document; mod image; +mod packaging; mod pathtools; mod pen; mod select; @@ -15,6 +16,7 @@ mod shapes; mod typetools; pub(crate) use image::{DecodedImages, refresh_color_masks}; +pub(crate) use packaging::{role_swatch_edited, role_swatches_merged}; use super::CommandSpec; @@ -27,6 +29,7 @@ pub fn specs() -> Vec { v.extend(cutting::specs()); v.extend(document::specs()); v.extend(image::specs()); + v.extend(packaging::specs()); v.extend(pathtools::specs()); v.extend(pen::specs()); v.extend(select::specs()); diff --git a/crates/engine/src/cmd/addons/packaging.rs b/crates/engine/src/cmd/addons/packaging.rs new file mode 100644 index 0000000000..7e262c3869 --- /dev/null +++ b/crates/engine/src/cmd/addons/packaging.rs @@ -0,0 +1,18 @@ +//! Packaging Tools (`addon.packaging.*`), a built-in add-on for the dielines of boxes and other +//! folded packaging. A path is a fold line when its top stroke is painted with the swatch of a line +//! role: Cut, Crease, Partial Cut or Perforation ([`roles`]). The document's role table maps each +//! role to its swatch, so every format that keeps the stroke's swatch keeps the role. Its submenu +//! (Object › Plug-ins › Packaging Tools) and its Fold Lines panel are the UI's. + +mod roles; + +pub(crate) use roles::{role_swatch_edited, role_swatches_merged}; + +use super::super::CommandSpec; + +pub fn specs() -> Vec { + roles::specs() +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/addons/packaging/roles.rs b/crates/engine/src/cmd/addons/packaging/roles.rs new file mode 100644 index 0000000000..010384c6c2 --- /dev/null +++ b/crates/engine/src/cmd/addons/packaging/roles.rs @@ -0,0 +1,454 @@ +//! Fold line roles (`addon.packaging.setRole`, `addon.packaging.roles`, +//! `addon.packaging.setRoleSwatch`). A path, compound path or live shape has a role when its top +//! stroke is painted with the swatch the document's role table gives that role, at any tint. The +//! table lives in [`Document::unknown`] under [`ROLES_KEY`], `{cut, crease, partialCut, +//! perforation}` each naming a swatch; a role it leaves out, or names with something other than a +//! string, takes its default swatch, named after the role. + +use serde_json::{Map, Value, json}; +use vectorcraft_color::swatch::REGISTRATION; +use vectorcraft_color::{Color, Paint, Swatch}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; + +use super::super::super::overprint::edit_counted; +use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_selection, switch_or, text_param}; +use crate::{Result, Session}; + +/// Document unknown key: the role table, `{role id: swatch name}`. +pub(crate) const ROLES_KEY: &str = "packagingRoles"; + +const SET_ROLE: &str = "addon.packaging.setRole"; +const ROLES: &str = "addon.packaging.roles"; +const SET_ROLE_SWATCH: &str = "addon.packaging.setRoleSwatch"; + +/// What a fold line does when the blank is cut and folded. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Role { + /// Separates the material. + Cut, + /// A fold. + Crease, + /// A fold cut part way through the board. + PartialCut, + /// A fold along a line of cuts. + Perforation, +} + +impl Role { + pub(crate) const ALL: [Role; 4] = [Role::Cut, Role::Crease, Role::PartialCut, Role::Perforation]; + + /// The role's id in params and in the role table. + pub(crate) fn id(self) -> &'static str { + match self { + Role::Cut => "cut", + Role::Crease => "crease", + Role::PartialCut => "partialCut", + Role::Perforation => "perforation", + } + } + + /// The role's name, which is also its default swatch's name. + pub(crate) fn name(self) -> &'static str { + match self { + Role::Cut => "Cut", + Role::Crease => "Crease", + Role::PartialCut => "Partial Cut", + Role::Perforation => "Perforation", + } + } + + pub(crate) fn from_id(id: &str) -> Option { + Role::ALL.into_iter().find(|r| r.id() == id) + } + + /// The color a missing role swatch is made with (VectorCraft's own values): Cut 100% magenta, + /// Crease 100% cyan, Partial Cut 100% yellow, Perforation 50% magenta and 50% cyan. + fn color(self) -> Color { + match self { + Role::Cut => Color::cmyk(0.0, 1.0, 0.0, 0.0), + Role::Crease => Color::cmyk(1.0, 0.0, 0.0, 0.0), + Role::PartialCut => Color::cmyk(0.0, 0.0, 1.0, 0.0), + Role::Perforation => Color::cmyk(0.5, 0.5, 0.0, 0.0), + } + } + + fn index(self) -> usize { + Role::ALL.iter().position(|r| *r == self).unwrap_or(0) + } +} + +/// The swatch each role is carried by, in [`Role::ALL`] order. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct RoleTable([String; 4]); + +impl RoleTable { + /// The document's role table, with each missing or damaged entry at its default. When a damaged + /// table names one swatch for two roles, the later role takes its default name instead, or + /// "Crease 2" and so on when an earlier role has that. + pub(crate) fn of(d: &Document) -> RoleTable { + let stored = d.unknown.get(ROLES_KEY).and_then(Value::as_object); + let mut names: Vec = Vec::with_capacity(Role::ALL.len()); + for r in Role::ALL { + let name = match stored.and_then(|m| m.get(r.id())).and_then(Value::as_str) { + Some(name) if !name.is_empty() && !names.iter().any(|n| n == name) => name.to_string(), + _ => { + let base = r.name(); + std::iter::once(base.to_string()) + .chain((2..).map(|i| format!("{base} {i}"))) + .find(|n| !names.contains(n)) + .unwrap_or_else(|| base.to_string()) + } + }; + names.push(name); + } + RoleTable(Role::ALL.map(|r| names.get(r.index()).cloned().unwrap_or_else(|| r.name().to_string()))) + } + + /// The swatch of `role`. + pub(crate) fn swatch(&self, role: Role) -> &str { + self.0.get(role.index()).map_or("", String::as_str) + } + + /// The role swatch `name` carries. + pub(crate) fn role_of_swatch(&self, name: &str) -> Option { + Role::ALL.into_iter().find(|r| self.swatch(*r) == name) + } + + /// The role of object `n`: the role of the swatch its top stroke is painted with. + pub(crate) fn role_of(&self, n: &Node) -> Option { + if !can_carry(n) { + return None; + } + match &n.appearance.stroke()?.paint { + Paint::Solid { swatch: Some(name), .. } => self.role_of_swatch(name), + _ => None, + } + } + + fn to_value(&self) -> Value { + Value::Object(Role::ALL.into_iter().map(|r| (r.id().to_string(), json!(self.swatch(r)))).collect::>()) + } +} + +/// Swatch `from` of `d` is now named `to`, and `global` says whether it is still a global color. +/// A role it carried keeps it under the new name, as the strokes linked to it do; when it stopped +/// being global, which unlinks those strokes, the role moves to a new name that `setRole` makes a +/// swatch for. Another role that named `to` without such a swatch moves to a new name too, so no +/// two roles share a swatch. +pub(crate) fn role_swatch_edited(d: &mut Document, from: &str, to: &str, global: bool) { + let before = RoleTable::of(d); + let mut table = before.clone(); + for r in Role::ALL { + let name = table.swatch(r).to_string(); + let moved = if name == from && global { + Some(to.to_string()) + } else if name == from || (name == to && from != to) { + Some(free_role_name(d, &table, r)) + } else { + None + }; + if let (Some(new), Some(slot)) = (moved, table.0.get_mut(r.index())) { + *slot = new; + } + } + if table != before { + d.unknown.insert(ROLES_KEY.to_string(), table.to_value()); + } +} + +/// Swatches `merged` of `d` were merged into swatch `kept`, and `linked` says whether their strokes +/// now link to it (it is a global color). When `kept` carries no role, it takes the role of the +/// first merged swatch that carried one, so the lines of that role keep it; a merged swatch's other +/// role keeps its name, which the next `setRole` makes a swatch for. +pub(crate) fn role_swatches_merged(d: &mut Document, merged: &[String], kept: &str, linked: bool) { + let mut table = RoleTable::of(d); + if !linked || table.role_of_swatch(kept).is_some() { + return; + } + let Some(role) = merged.iter().find_map(|m| table.role_of_swatch(m)) else { return }; + if let Some(slot) = table.0.get_mut(role.index()) { + *slot = kept.to_string(); + } + d.unknown.insert(ROLES_KEY.to_string(), table.to_value()); +} + +/// A name for `role`'s swatch that no swatch, color group or other role of `table` uses: the +/// role's name, else "Cut 2", "Cut 3"… The document holds finitely many names, so the search +/// always ends at a free one. +fn free_role_name(d: &Document, table: &RoleTable, role: Role) -> String { + let free = |n: &str| !d.swatch_name_taken(n) && Role::ALL.into_iter().all(|r| r == role || table.swatch(r) != n); + let base = role.name(); + if free(base) { + return base.to_string(); + } + (2usize..).map(|i| format!("{base} {i}")).find(|n| free(n)).unwrap_or_else(|| base.to_string()) +} + +/// Whether `n` can carry a role: a path (a live shape too) that is neither a clipping path nor a +/// guide, or a compound path. +fn can_carry(n: &Node) -> bool { + match &n.kind { + NodeKind::Path { clipping, guide, .. } => !clipping && !guide, + NodeKind::Compound { .. } => true, + _ => false, + } +} + +/// The objects under the outermost objects `roots` that can carry a role, through groups and clip +/// groups, each once, and +/// how many of `roots` and their members can't (text, images, symbol instances and other objects). +/// With `editable`, objects that are locked or hidden, are in a locked or hidden group or layer, or +/// are on a locked artboard are left out and counted as skipped. +fn role_targets(d: &Document, roots: &[NodeId], editable: bool) -> (Vec, usize) { + fn walk(n: &Node, out: &mut Vec, skipped: &mut usize) { + match &n.kind { + NodeKind::Group { children, .. } => { + for c in children { + // A group's clipping path draws no stroke: it is skipped. + if matches!(c.kind, NodeKind::Path { clipping: true, .. }) { + *skipped += 1; + } else { + walk(c, out, skipped); + } + } + } + _ if can_carry(n) => out.push(n.id), + _ => *skipped += 1, + } + } + let (mut out, mut skipped) = (vec![], 0); + // A path of a compound path is painted with the compound's appearance: the compound takes the + // role. `roots` come from `checked_ids_or_selection`, which keeps only outermost objects, so a + // group and its member are never both roots. + let mut seen = std::collections::HashSet::new(); + let compound_of = |id: NodeId| d.parent_of(id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. }))); + for n in roots.iter().map(|id| compound_of(*id).unwrap_or(*id)).filter(|id| seen.insert(*id)).filter_map(|id| d.node(id)) { + walk(n, &mut out, &mut skipped); + } + if editable { + // Named directly or not, a locked or hidden object, or one in a locked or hidden group or + // layer or on a locked artboard, stays as it is. + let ok = d.editable(); + let before = out.len(); + out.retain(|id| ok(*id)); + skipped += before - out.len(); + } + (out, skipped) +} + +/// Every object of the document that can carry a role, through layers and groups. +fn document_targets(d: &Document) -> Vec { + fn walk(n: &Node, out: &mut Vec) { + match &n.kind { + NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().for_each(|c| walk(c, out)), + _ if can_carry(n) => out.push(n.id), + _ => {} + } + } + let mut out = vec![]; + d.layers.iter().for_each(|l| walk(l, &mut out)); + out +} + +pub fn specs() -> Vec { + vec![ + cmd!( + "addon.packaging.setRole", + "Make Fold Line", + ["Object", "Plug-ins", "Packaging Tools"], + None, + "{role: cut|crease|partialCut|perforation|none, ids?: [id…] (default: the selection), overprint?: bool (true)} give each path, compound path and live shape among the objects (through groups and clip groups; objects that are locked or hidden, in a locked or hidden group or layer, or on a locked artboard are left out and counted as skipped, even when named in ids) a fold line role: its top stroke is painted with the role's swatch (addon.packaging.roles) at 100% and shown, a path without a stroke gets a 1 pt stroke, and the stroke overprints, or with overprint: false does not. A missing role swatch is made as a global spot swatch (Cut 100% magenta, Crease 100% cyan, Partial Cut 100% yellow, Perforation 50% magenta and 50% cyan, in the document's color mode; named \"Cut 2\" and so on, in the role table too, when a color group or a swatch that can't carry a role, such as a process color that is not global, has the name). none takes the role away: a role stroke keeps the color it shows, no longer linked to the swatch, and stops overprinting. Text, images, symbol instances and other objects are skipped and counted. One undo step, none when nothing changes → {ids (the objects that can carry a role), changed, skipped}", + has_selection, + set_role + ), + cmd!( + query "addon.packaging.roles", + "Fold Lines", + [], + None, + "{ids?: [id…] (default: the selection)} the fold line roles → {roles: [{role: cut|crease|partialCut|perforation, name, swatch (the swatch that carries it), exists (the document has the swatch), count}], scope: ids|selection|document, selected (objects given or selected)}; count is how many of the paths, compound paths and live shapes among the objects (through groups, locked and hidden members included, each object once) have the role, or among every object of the document while nothing is selected and ids is left out", + has_doc, + roles + ), + cmd!( + "addon.packaging.setRoleSwatch", + "Role Swatches…", + ["Object", "Plug-ins", "Packaging Tools"], + None, + "{role: cut|crease|partialCut|perforation, swatch: a global or spot color swatch's name} make the swatch carry the role, in the document's role table, as one undo step (none when it already does). Objects stroked with the role's old swatch keep their color and no longer have the role. Refused: a missing swatch, a gradient or pattern swatch, a process color that is not global, a tint swatch, [None], [Registration], and a swatch another role has → {role, swatch, changed}", + has_doc, + set_role_swatch + ), + ] +} + +/// The role `p` gives: `Some(None)` for `none` when `none` is allowed. +fn role_param(p: &Value, cmd: &str, none: bool) -> Result> { + let id = text_param(p, "role", cmd)?.ok_or_else(|| bad(cmd, "missing `role`"))?; + match Role::from_id(id) { + Some(r) => Ok(Some(r)), + None if none && id == "none" => Ok(None), + None if none => Err(bad(cmd, format!("unknown role `{id}`: cut, crease, partialCut, perforation or none"))), + None => Err(bad(cmd, format!("unknown role `{id}`: cut, crease, partialCut or perforation"))), + } +} + +/// Why swatch `name` of `d` can't carry a role, if it can't. +fn unfit_swatch(d: &Document, name: &str) -> Option { + if name == REGISTRATION || name == "[None]" { + return Some(format!("`{name}` can't carry a role")); + } + let Some(sw) = d.swatch(name) else { return Some(format!("no swatch `{name}`")) }; + match &sw.paint { + Paint::Solid { swatch: Some(_), .. } => Some(format!("`{name}` is a tint swatch: pick its base or another global or spot color")), + Paint::Solid { .. } if sw.global => None, + Paint::Solid { .. } => Some(format!("`{name}` is a process color: pick a global or spot color")), + _ => Some(format!("`{name}` isn't a color swatch")), + } +} + +/// `role`'s swatch in `d`, made as a global spot swatch in the document's color mode when `d` +/// lacks it → its paint at 100%. When a color group or a swatch that can't carry a role (a process +/// color that is not global, a tint, a gradient) has the swatch's name, the swatch is made under a +/// free name, which the role table then gives the role. +fn role_paint(d: &mut Document, role: Role) -> Result { + let mut table = RoleTable::of(d); + let current = table.swatch(role); + let taken = match d.swatch(current) { + Some(_) => unfit_swatch(d, current).is_some(), + None => d.swatch_name_taken(current), + }; + if taken { + let free = free_role_name(d, &table, role); + if let Some(slot) = table.0.get_mut(role.index()) { + *slot = free; + } + d.unknown.insert(ROLES_KEY.to_string(), table.to_value()); + } + let name = table.swatch(role); + if d.swatch(name).is_none() { + let model = d.color_mode.model(); + let color = role.color(); + let color = if color.model() == model { + color + } else { + let cms = vectorcraft_color::cms::active(); + cms.convert(&color, model, cms.settings().intent) + }; + d.swatches.push(Swatch { name: name.to_string(), paint: Paint::solid(color), global: true, spot: true }); + } + if let Some(why) = unfit_swatch(d, name) { + return Err(bad(SET_ROLE, format!("{why} (the {} role's swatch; addon.packaging.setRoleSwatch picks another)", role.name()))); + } + d.tint_paint(name, 1.0).ok_or_else(|| bad(SET_ROLE, format!("`{name}` isn't a global or spot color"))) +} + +/// Gives object `id` of `d` `role`'s `paint` (`None`: takes its role away) → whether it changed. +fn give_role(d: &mut Document, table: &RoleTable, id: NodeId, paint: Option<&Paint>, overprint: bool) -> bool { + let Some(n) = d.node_mut(id) else { return false }; + let had = table.role_of(n); + let mut a = (*n.appearance).clone(); + match paint { + Some(paint) => { + a.set_stroke(paint.clone()); + if let Some(st) = a.stroke_mut() { + if st.width <= 0.0 { + st.width = 1.0; + } + // A hidden stroke would carry the role without drawing or printing the line. + st.visible = true; + st.overprint = overprint; + } + } + None => { + if had.is_none() { + return false; + } + if let Some(st) = a.stroke_mut() { + if let Paint::Solid { color, .. } = st.paint { + st.paint = Paint::solid(color); + } + st.overprint = false; + } + } + } + if a == *n.appearance { + return false; + } + n.appearance = vectorcraft_doc::Shared::new(a); + true +} + +fn set_role(s: &mut Session, p: &Value) -> Result { + let role = role_param(p, SET_ROLE, true)?; + let overprint = switch_or(p, "overprint", true, SET_ROLE)?; + let roots = checked_ids_or_selection(s, p, SET_ROLE)?; + let (ids, skipped) = role_targets(&s.doc()?.doc, &roots, true); + if ids.is_empty() { + return Err(bad(SET_ROLE, "select a path that is neither locked nor hidden: text, images and symbol instances can't have a fold line role")); + } + let label = role.map_or("Remove Fold Line Role", |_| "Make Fold Line"); + let mut changed = 0; + edit_counted(s, label, |d| { + let before = (d.swatches.len(), d.unknown.get(ROLES_KEY).cloned()); + let paint = role.map(|r| role_paint(d, r)).transpose()?; + // A role swatch made again (its strokes may still name it) is a change of its own. + let made = (d.swatches.len(), d.unknown.get(ROLES_KEY).cloned()) != before; + let table = RoleTable::of(d); + changed = ids.iter().filter(|id| give_role(d, &table, **id, paint.as_ref(), overprint)).count(); + Ok(changed + usize::from(made)) + })?; + Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>(), "changed": changed, "skipped": skipped })) +} + +fn roles(s: &mut Session, p: &Value) -> Result { + let given = p.get("ids").is_some_and(|v| !v.is_null()); + let roots = checked_ids_or_selection(s, p, ROLES)?; + let d = &s.doc()?.doc; + let (scope, ids) = match (given, roots.is_empty()) { + (true, _) => ("ids", role_targets(d, &roots, false).0), + (false, false) => ("selection", role_targets(d, &roots, false).0), + (false, true) => ("document", document_targets(d)), + }; + let table = RoleTable::of(d); + let mut counts = [0usize; 4]; + for r in ids.iter().filter_map(|id| d.node(*id)).filter_map(|n| table.role_of(n)) { + if let Some(c) = counts.get_mut(r.index()) { + *c += 1; + } + } + let rows: Vec = Role::ALL + .into_iter() + .zip(counts) + .map(|(r, count)| { + let swatch = table.swatch(r); + json!({ "role": r.id(), "name": r.name(), "swatch": swatch, "exists": d.swatch(swatch).is_some(), "count": count }) + }) + .collect(); + Ok(json!({ "roles": rows, "scope": scope, "selected": roots.len() })) +} + +fn set_role_swatch(s: &mut Session, p: &Value) -> Result { + let Some(role) = role_param(p, SET_ROLE_SWATCH, false)? else { return Err(bad(SET_ROLE_SWATCH, "missing `role`")) }; + let name = text_param(p, "swatch", SET_ROLE_SWATCH)?.ok_or_else(|| bad(SET_ROLE_SWATCH, "missing `swatch`"))?; + let d = &s.doc()?.doc; + if let Some(why) = unfit_swatch(d, name) { + return Err(bad(SET_ROLE_SWATCH, why)); + } + let mut table = RoleTable::of(d); + if let Some(other) = Role::ALL.into_iter().find(|r| *r != role && table.swatch(*r) == name) { + return Err(bad(SET_ROLE_SWATCH, format!("`{name}` already carries the {} role", other.name()))); + } + if let Some(slot) = table.0.get_mut(role.index()) { + *slot = name.to_string(); + } + let value = table.to_value(); + let changed = RoleTable::of(d) != table; + if changed { + s.edit("Role Swatches", |d, _| { + d.unknown.insert(ROLES_KEY.to_string(), value); + Ok(()) + })?; + } + Ok(json!({ "role": role.id(), "swatch": name, "changed": changed })) +} diff --git a/crates/engine/src/cmd/addons/packaging/tests.rs b/crates/engine/src/cmd/addons/packaging/tests.rs new file mode 100644 index 0000000000..07a8bd3a30 --- /dev/null +++ b/crates/engine/src/cmd/addons/packaging/tests.rs @@ -0,0 +1,540 @@ +//! Tests for Packaging Tools: fold line roles, their swatches and the role table. + +use std::collections::BTreeSet; + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{AppearanceItem, Node, NodeKind}; + +use crate::*; + +fn session(mode: &str) -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400, "colorMode": mode})).unwrap(); + s +} + +fn id_of(v: &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": 20, "width": 40, "height": 40})).unwrap()) +} + +fn node(s: &Session, id: NodeId) -> Node { + s.doc().unwrap().doc.node(id).cloned().unwrap() +} + +fn steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn set_role(s: &mut Session, p: Value) -> Value { + s.execute("addon.packaging.setRole", &p).unwrap() +} + +fn err(s: &mut Session, cmd: &str, p: Value) -> String { + s.execute(cmd, &p).unwrap_err().to_string() +} + +fn b64(v: &Value) -> Vec { + vectorcraft_format::base64_decode(v["dataBase64"].as_str().expect("dataBase64")).unwrap() +} + +/// The `roles` query's counts, in role order. +fn counts(s: &mut Session, p: Value) -> Vec { + let r = s.execute("addon.packaging.roles", &p).unwrap(); + r["roles"].as_array().unwrap().iter().map(|r| r["count"].as_u64().unwrap()).collect() +} + +#[test] +fn set_role_makes_the_spot_swatch_and_links_the_top_stroke() { + let mut s = session("cmyk"); + let a = rect(&mut s, 20.0); + assert!(s.doc().unwrap().doc.swatch("Cut").is_none()); + let before = steps(&s); + let r = set_role(&mut s, json!({"role": "cut", "ids": [a.0]})); + assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(1), Some(0))); + assert_eq!(steps(&s), before + 1, "one undo step"); + let d = &s.doc().unwrap().doc; + let sw = d.swatch("Cut").unwrap(); + assert!(sw.global && sw.spot, "{sw:?}"); + assert_eq!(sw.paint, Paint::solid(Color::cmyk(0.0, 1.0, 0.0, 0.0)), "100% magenta in a CMYK document"); + let st = node(&s, a).appearance.stroke().cloned().unwrap(); + assert!(matches!(&st.paint, Paint::Solid { swatch: Some(n), tint, .. } if n == "Cut" && *tint == 1.0), "{:?}", st.paint); + assert!(st.overprint, "role strokes overprint by default"); + // Again: nothing changes, and no undo step is recorded. + let r = set_role(&mut s, json!({"role": "cut", "ids": [a.0]})); + assert_eq!(r["changed"].as_u64(), Some(0)); + assert_eq!(steps(&s), before + 1); + // Undo takes the swatch away with the role. + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.swatch("Cut").is_none()); +} + +#[test] +fn each_role_gets_its_own_swatch_color_in_the_document_s_mode() { + let mut s = session("rgb"); + for (i, role) in ["cut", "crease", "partialCut", "perforation"].into_iter().enumerate() { + let id = rect(&mut s, 20.0 + 60.0 * i as f64); + set_role(&mut s, json!({"role": role, "ids": [id.0]})); + } + let d = &s.doc().unwrap().doc; + let colors: Vec = ["Cut", "Crease", "Partial Cut", "Perforation"].iter().map(|n| d.swatch(n).unwrap().paint.color().unwrap()).collect(); + assert!(colors.iter().all(|c| matches!(c, Color::Rgb { .. })), "an RGB document's swatches are RGB: {colors:?}"); + assert_eq!(colors.iter().map(|c| c.to_hex()).collect::>().len(), 4, "four colors: {colors:?}"); +} + +#[test] +fn a_path_without_a_stroke_gets_one_and_overprint_can_be_left_off() { + let mut s = session("cmyk"); + let a = rect(&mut s, 20.0); + s.edit("strip", |d, _| { + let n = d.node_mut(a).unwrap(); + n.appearance.items.retain(AppearanceItem::is_fill); + Ok(()) + }) + .unwrap(); + assert!(node(&s, a).appearance.stroke().is_none()); + set_role(&mut s, json!({"role": "crease", "ids": [a.0], "overprint": false})); + let st = node(&s, a).appearance.stroke().cloned().unwrap(); + assert_eq!(st.width, 1.0, "a 1 pt stroke"); + assert!(!st.overprint); + assert!(matches!(&st.paint, Paint::Solid { swatch: Some(n), .. } if n == "Crease")); + assert!(err(&mut s, "addon.packaging.setRole", json!({"role": "cut", "ids": [a.0], "overprint": "yes"})).contains("overprint")); +} + +#[test] +fn none_takes_the_role_away_and_keeps_the_color() { + let mut s = session("cmyk"); + let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 100.0)); + set_role(&mut s, json!({"role": "perforation", "ids": [a.0]})); + let shown = node(&s, a).appearance.stroke().unwrap().paint.color().unwrap(); + let before = steps(&s); + let r = set_role(&mut s, json!({"role": "none", "ids": [a.0, b.0]})); + assert_eq!(r["changed"].as_u64(), Some(1), "the plain rectangle has no role to take away"); + assert_eq!(steps(&s), before + 1); + let st = node(&s, a).appearance.stroke().cloned().unwrap(); + assert_eq!(st.paint, Paint::solid(shown)); + assert!(!st.overprint); + assert_eq!(counts(&mut s, json!({"ids": [a.0, b.0]})), [0, 0, 0, 0]); + // Nothing left with a role: no undo step. + set_role(&mut s, json!({"role": "none", "ids": [a.0, b.0]})); + assert_eq!(steps(&s), before + 1); +} + +#[test] +fn bad_roles_and_targets_are_refused() { + let mut s = session("cmyk"); + let a = rect(&mut s, 20.0); + assert!(err(&mut s, "addon.packaging.setRole", json!({"role": "fold", "ids": [a.0]})).contains("unknown role")); + assert!(err(&mut s, "addon.packaging.setRole", json!({"ids": [a.0]})).contains("role")); + assert!(err(&mut s, "addon.packaging.setRole", json!({"role": 3, "ids": [a.0]})).contains("role")); + s.execute("select.none", &json!({})).unwrap(); + assert!(s.execute("addon.packaging.setRole", &json!({"role": "cut"})).is_err(), "nothing selected"); + let t = id_of(&s.execute("text.create", &json!({"x": 20, "y": 200, "text": "Lid", "size": 20})).unwrap()); + let before = steps(&s); + assert!(err(&mut s, "addon.packaging.setRole", json!({"role": "cut", "ids": [t.0]})).contains("select a path")); + assert_eq!(steps(&s), before); + assert!(s.doc().unwrap().doc.swatch("Cut").is_none(), "a refused run makes no swatch"); + // Text beside a path is skipped and counted. + let r = set_role(&mut s, json!({"role": "cut", "ids": [a.0, t.0]})); + assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(1), Some(1))); +} + +#[test] +fn groups_are_walked_and_their_locked_and_hidden_members_left_out() { + let mut s = session("cmyk"); + let (a, b, c) = (rect(&mut s, 20.0), rect(&mut s, 100.0), rect(&mut s, 180.0)); + s.execute("select.set", &json!({"ids": [a.0, b.0, c.0]})).unwrap(); + let g = id_of(&s.execute("object.group", &json!({})).unwrap()); + s.edit("lock", |d, _| { + d.node_mut(b).unwrap().locked = true; + d.node_mut(c).unwrap().visible = false; + Ok(()) + }) + .unwrap(); + let r = set_role(&mut s, json!({"role": "crease", "ids": [g.0]})); + assert_eq!(r["ids"], json!([a.0])); + assert_eq!(r["skipped"].as_u64(), Some(2), "the locked and the hidden member"); + assert_eq!(counts(&mut s, json!({"ids": [g.0]})), [0, 1, 0, 0]); + // Named directly, a locked or hidden path is left out too. + let r = set_role(&mut s, json!({"role": "cut", "ids": [a.0, b.0, c.0]})); + assert_eq!((r["ids"].clone(), r["skipped"].as_u64()), (json!([a.0]), Some(2))); + let before = steps(&s); + assert!(err(&mut s, "addon.packaging.setRole", json!({"role": "cut", "ids": [b.0]})).contains("locked")); + assert_eq!(steps(&s), before); + assert_eq!(counts(&mut s, json!({"ids": [b.0, c.0]})), [0, 0, 0, 0]); +} + +#[test] +fn a_clip_group_s_clipping_path_is_skipped_and_counted() { + let mut s = session("cmyk"); + let (art, mask) = (rect(&mut s, 20.0), rect(&mut s, 30.0)); + s.execute("select.set", &json!({"ids": [art.0, mask.0]})).unwrap(); + let g = id_of(&s.execute("object.clippingMask.make", &json!({})).unwrap()); + let r = set_role(&mut s, json!({"role": "cut", "ids": [g.0]})); + assert_eq!((r["ids"].clone(), r["skipped"].as_u64()), (json!([art.0]), Some(1)), "the clipping path is left out and counted"); +} + +#[test] +fn a_group_and_its_member_count_once_and_locked_lines_count_in_every_scope() { + let mut s = session("cmyk"); + let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 100.0)); + set_role(&mut s, json!({"role": "cut", "ids": [b.0]})); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let g = id_of(&s.execute("object.group", &json!({})).unwrap()); + let r = set_role(&mut s, json!({"role": "crease", "ids": [g.0, a.0]})); + assert_eq!(r["ids"], json!([a.0, b.0]), "each path once"); + assert_eq!(counts(&mut s, json!({"ids": [g.0, a.0]})), [0, 2, 0, 0]); + set_role(&mut s, json!({"role": "cut", "ids": [b.0]})); + s.edit("lock", |d, _| { + d.node_mut(b).unwrap().locked = true; + Ok(()) + }) + .unwrap(); + // A locked line keeps its role and is counted, whether its group is selected or not. + assert_eq!(counts(&mut s, json!({"ids": [g.0]})), [1, 1, 0, 0]); + s.execute("select.none", &json!({})).unwrap(); + assert_eq!(counts(&mut s, json!({})), [1, 1, 0, 0]); +} + +#[test] +fn a_process_swatch_named_like_a_role_swatch_keeps_its_name() { + let mut s = session("cmyk"); + let a = rect(&mut s, 20.0); + s.execute("swatch.new", &json!({"name": "Cut", "color": "#ff0000"})).unwrap(); + set_role(&mut s, json!({"role": "cut", "ids": [a.0]})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.unknown.get("packagingRoles").unwrap()["cut"], json!("Cut 2")); + assert!(d.swatch("Cut 2").is_some_and(|w| w.spot), "the role swatch is made beside it"); + assert!(d.swatch("Cut").is_some_and(|w| !w.global), "the process swatch is left as it was"); + assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [1, 0, 0, 0]); +} + +#[test] +fn the_free_role_swatch_name_is_searched_past_ten_thousand() { + let mut s = session("cmyk"); + let a = rect(&mut s, 20.0); + let taken = std::iter::once("Cut".to_string()).chain((2..10_000).map(|i| format!("Cut {i}"))).chain(["Cut 10004".to_string()]); + let process = |name: String| vectorcraft_color::Swatch { name, paint: Paint::solid(Color::rgb(1.0, 0.0, 0.0)), global: false, spot: false }; + Arc::make_mut(&mut s.doc_mut().unwrap().doc).swatches.extend(taken.map(process)); + set_role(&mut s, json!({"role": "cut", "ids": [a.0]})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.unknown.get("packagingRoles").unwrap()["cut"], json!("Cut 10000")); + assert!(d.swatch("Cut 10000").is_some_and(|w| w.spot), "the role swatch is made under the first free name"); + assert!(d.swatch("Cut 10004").is_some_and(|w| !w.global), "a taken name is left as it was"); +} + +#[test] +fn a_merged_role_swatch_hands_its_role_to_the_kept_swatch() { + let mut s = session("cmyk"); + let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 100.0)); + set_role(&mut s, json!({"role": "cut", "ids": [a.0]})); + set_role(&mut s, json!({"role": "crease", "ids": [b.0]})); + s.execute("swatch.new", &json!({"name": "Die", "color": {"model": "cmyk", "c": 0, "m": 0.8, "y": 0.2, "k": 0}, "spot": true})).unwrap(); + s.execute("swatch.merge", &json!({"names": ["Die", "Cut"]})).unwrap(); + assert_eq!(s.doc().unwrap().doc.unknown.get("packagingRoles").unwrap()["cut"], json!("Die")); + assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [1, 0, 0, 0], "the cut line is still a cut line"); + // A kept swatch that already carries a role keeps it; the merged role's lines take it. + s.execute("swatch.merge", &json!({"names": ["Crease", "Die"]})).unwrap(); + let table = s.doc().unwrap().doc.unknown.get("packagingRoles").cloned().unwrap(); + assert_eq!((&table["cut"], &table["crease"]), (&json!("Die"), &json!("Crease")), "{table}"); + assert_eq!(counts(&mut s, json!({"ids": [a.0, b.0]})), [0, 2, 0, 0]); + // The next Make Cut Line makes the Cut role's swatch again. + set_role(&mut s, json!({"role": "cut", "ids": [a.0]})); + assert!(s.doc().unwrap().doc.swatch("Die").is_some_and(|w| w.spot)); + assert_eq!(counts(&mut s, json!({"ids": [a.0, b.0]})), [1, 1, 0, 0]); +} + +#[test] +fn a_global_process_swatch_can_carry_a_role() { + let mut s = session("cmyk"); + let a = rect(&mut s, 20.0); + s.execute("swatch.new", &json!({"name": "Die", "color": {"model": "cmyk", "c": 0, "m": 0.8, "y": 0.2, "k": 0}, "global": true})).unwrap(); + s.execute("addon.packaging.setRoleSwatch", &json!({"role": "partialCut", "swatch": "Die"})).unwrap(); + set_role(&mut s, json!({"role": "partialCut", "ids": [a.0]})); + assert!(matches!(&node(&s, a).appearance.stroke().unwrap().paint, Paint::Solid { swatch: Some(n), .. } if n == "Die")); + assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [0, 0, 1, 0]); +} + +#[test] +fn roles_counts_the_selection_or_the_whole_document() { + let mut s = session("cmyk"); + let (a, b, c) = (rect(&mut s, 20.0), rect(&mut s, 100.0), rect(&mut s, 180.0)); + set_role(&mut s, json!({"role": "cut", "ids": [a.0, b.0]})); + set_role(&mut s, json!({"role": "partialCut", "ids": [c.0]})); + s.execute("select.set", &json!({"ids": [a.0, c.0]})).unwrap(); + let r = s.execute("addon.packaging.roles", &json!({})).unwrap(); + assert_eq!((r["scope"].as_str(), r["selected"].as_u64()), (Some("selection"), Some(2))); + assert_eq!(counts(&mut s, json!({})), [1, 0, 1, 0]); + s.execute("select.none", &json!({})).unwrap(); + let r = s.execute("addon.packaging.roles", &json!({})).unwrap(); + assert_eq!((r["scope"].as_str(), r["selected"].as_u64()), (Some("document"), Some(0))); + assert_eq!(counts(&mut s, json!({})), [2, 0, 1, 0]); + let rows = r["roles"].as_array().unwrap(); + assert_eq!(rows[0], json!({"role": "cut", "name": "Cut", "swatch": "Cut", "exists": true, "count": 2})); + assert_eq!(rows[1]["exists"], json!(false), "no Crease swatch yet"); +} + +#[test] +fn role_swatches_maps_a_role_to_another_swatch() { + let mut s = session("cmyk"); + let a = rect(&mut s, 20.0); + set_role(&mut s, json!({"role": "cut", "ids": [a.0]})); + s.execute("swatch.new", &json!({"name": "Die", "color": {"model": "cmyk", "c": 0, "m": 0.8, "y": 0.2, "k": 0}, "spot": true})).unwrap(); + let before = steps(&s); + let r = s.execute("addon.packaging.setRoleSwatch", &json!({"role": "cut", "swatch": "Die"})).unwrap(); + assert_eq!(r["changed"], json!(true)); + assert_eq!(steps(&s), before + 1); + assert_eq!(s.doc().unwrap().doc.unknown.get("packagingRoles").unwrap()["cut"], json!("Die")); + // The old swatch's objects keep their color and lose the role. + assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [0, 0, 0, 0]); + set_role(&mut s, json!({"role": "cut", "ids": [a.0]})); + assert!(matches!(&node(&s, a).appearance.stroke().unwrap().paint, Paint::Solid { swatch: Some(n), .. } if n == "Die")); + // The same mapping again changes nothing. + let steps_now = steps(&s); + let r = s.execute("addon.packaging.setRoleSwatch", &json!({"role": "cut", "swatch": "Die"})).unwrap(); + assert_eq!((r["changed"].clone(), steps(&s)), (json!(false), steps_now)); +} + +#[test] +fn a_renamed_role_swatch_keeps_its_role() { + let mut s = session("cmyk"); + let a = rect(&mut s, 20.0); + set_role(&mut s, json!({"role": "crease", "ids": [a.0]})); + s.execute("swatch.edit", &json!({"name": "Crease", "newName": "Score"})).unwrap(); + assert_eq!(s.doc().unwrap().doc.unknown.get("packagingRoles").unwrap()["crease"], json!("Score")); + assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [0, 1, 0, 0]); + // A swatch that carries no role leaves the table alone. + s.execute("swatch.new", &json!({"name": "Ink", "color": {"model": "cmyk", "c": 0, "m": 1, "y": 1, "k": 0}, "spot": true})).unwrap(); + s.execute("swatch.edit", &json!({"name": "Ink", "newName": "Red Ink"})).unwrap(); + let table = s.doc().unwrap().doc.unknown.get("packagingRoles").cloned().unwrap(); + assert_eq!(table, json!({"cut": "Cut", "crease": "Score", "partialCut": "Partial Cut", "perforation": "Perforation"})); + // Undo puts the old name back in the table with the swatch. + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.unknown.get("packagingRoles").is_none()); + assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [0, 1, 0, 0]); +} + +#[test] +fn a_role_swatch_renamed_to_another_role_s_name_leaves_each_role_its_own_swatch() { + let mut s = session("cmyk"); + let a = rect(&mut s, 20.0); + set_role(&mut s, json!({"role": "cut", "ids": [a.0]})); + // No Crease swatch exists yet, so the name is free for the Cut swatch. + s.execute("swatch.edit", &json!({"name": "Cut", "newName": "Crease"})).unwrap(); + let table = s.doc().unwrap().doc.unknown.get("packagingRoles").cloned().unwrap(); + assert_eq!((&table["cut"], &table["crease"]), (&json!("Crease"), &json!("Crease 2")), "{table}"); + assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [1, 0, 0, 0], "the line is still a cut line"); +} + +#[test] +fn a_role_swatch_that_stops_being_global_hands_its_role_to_a_new_swatch() { + let mut s = session("cmyk"); + let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 100.0)); + set_role(&mut s, json!({"role": "perforation", "ids": [a.0]})); + s.execute("swatch.edit", &json!({"name": "Perforation", "spot": false, "global": false})).unwrap(); + assert_eq!(s.doc().unwrap().doc.unknown.get("packagingRoles").unwrap()["perforation"], json!("Perforation 2")); + assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [0, 0, 0, 0], "the unlinked stroke has no role"); + set_role(&mut s, json!({"role": "perforation", "ids": [b.0]})); + assert!(s.doc().unwrap().doc.swatch("Perforation 2").is_some_and(|w| w.spot)); + assert_eq!(counts(&mut s, json!({"ids": [b.0]})), [0, 0, 0, 1]); +} + +#[test] +fn a_color_group_named_like_a_role_swatch_keeps_its_name() { + let mut s = session("cmyk"); + let a = rect(&mut s, 20.0); + s.execute("swatch.newGroup", &json!({"name": "Cut", "colors": ["#ff0000"]})).unwrap(); + set_role(&mut s, json!({"role": "cut", "ids": [a.0]})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.unknown.get("packagingRoles").unwrap()["cut"], json!("Cut 2")); + assert!(d.swatch("Cut 2").is_some_and(|w| w.spot) && d.swatch("Cut").is_none()); + assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [1, 0, 0, 0]); +} + +#[test] +fn set_role_makes_a_deleted_role_swatch_again_for_strokes_that_still_name_it() { + let mut s = session("cmyk"); + let a = rect(&mut s, 20.0); + set_role(&mut s, json!({"role": "cut", "ids": [a.0]})); + s.execute("swatch.delete", &json!({"name": "Cut", "unlink": false})).unwrap(); + assert!(s.doc().unwrap().doc.swatch("Cut").is_none()); + let before = steps(&s); + let r = set_role(&mut s, json!({"role": "cut", "ids": [a.0]})); + assert_eq!(r["changed"].as_u64(), Some(0), "the stroke already names the swatch"); + assert!(s.doc().unwrap().doc.swatch("Cut").is_some_and(|w| w.spot), "the swatch is back"); + assert_eq!(steps(&s), before + 1, "as one undo step"); +} + +#[test] +fn a_hidden_stroke_is_shown_when_it_takes_a_role() { + let mut s = session("cmyk"); + let a = rect(&mut s, 20.0); + s.edit("hide", |d, _| { + if let Some(AppearanceItem::Stroke(st)) = d.node_mut(a).unwrap().appearance.items.iter_mut().find(|i| !i.is_fill()) { + st.visible = false; + } + Ok(()) + }) + .unwrap(); + set_role(&mut s, json!({"role": "cut", "ids": [a.0]})); + assert!(node(&s, a).appearance.stroke().unwrap().visible); +} + +#[test] +fn role_swatches_refuses_swatches_that_cannot_carry_a_role() { + let mut s = session("cmyk"); + let ramp = json!({"type": "linear", "stops": [{"offset": 0, "color": "#000000"}, {"offset": 1, "color": "#ffffff"}]}); + s.execute("swatch.new", &json!({"name": "Ramp", "gradient": ramp})).unwrap(); + s.execute("swatch.new", &json!({"name": "Plain", "color": "#336699"})).unwrap(); + s.execute("swatch.new", &json!({"name": "Ink", "color": {"model": "cmyk", "c": 0, "m": 1, "y": 1, "k": 0}, "spot": true})).unwrap(); + s.execute("swatch.new", &json!({"name": "Ink Tint", "swatch": "Ink", "tint": 0.5})).unwrap(); + s.execute("swatch.new", &json!({"name": "Crease", "color": {"model": "cmyk", "c": 1, "m": 0, "y": 0, "k": 0}, "spot": true})).unwrap(); + let before = steps(&s); + for (swatch, says) in [ + ("Nope", "no swatch"), + ("Ramp", "isn't a color swatch"), + ("Plain", "process color"), + ("Ink Tint", "tint swatch"), + ("[None]", "can't carry a role"), + ("[Registration]", "can't carry a role"), + ("Crease", "already carries the Crease role"), + ] { + let e = err(&mut s, "addon.packaging.setRoleSwatch", json!({"role": "cut", "swatch": swatch})); + assert!(e.contains(says), "{swatch}: {e}"); + } + assert!(err(&mut s, "addon.packaging.setRoleSwatch", json!({"role": "none", "swatch": "Ink"})).contains("unknown role")); + assert!(err(&mut s, "addon.packaging.setRoleSwatch", json!({"role": "cut"})).contains("swatch")); + assert_eq!(steps(&s), before, "no refusal records an undo step"); +} + +#[test] +fn a_damaged_role_table_reads_as_the_defaults() { + let mut s = session("cmyk"); + s.edit("damage", |d, _| { + d.unknown.insert("packagingRoles".into(), json!({"cut": 5, "crease": "", "partialCut": null, "extra": "x"})); + Ok(()) + }) + .unwrap(); + let r = s.execute("addon.packaging.roles", &json!({})).unwrap(); + let swatches: Vec<&str> = r["roles"].as_array().unwrap().iter().map(|r| r["swatch"].as_str().unwrap()).collect(); + assert_eq!(swatches, ["Cut", "Crease", "Partial Cut", "Perforation"]); + s.edit("not an object", |d, _| { + d.unknown.insert("packagingRoles".into(), json!("Cut")); + Ok(()) + }) + .unwrap(); + let a = rect(&mut s, 20.0); + set_role(&mut s, json!({"role": "cut", "ids": [a.0]})); + assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [1, 0, 0, 0]); + // One swatch named for two roles: the later role takes its own default. + s.edit("duplicate", |d, _| { + d.unknown.insert("packagingRoles".into(), json!({"cut": "Crease", "crease": "Crease", "partialCut": "Cut"})); + Ok(()) + }) + .unwrap(); + let r = s.execute("addon.packaging.roles", &json!({})).unwrap(); + let swatches: Vec<&str> = r["roles"].as_array().unwrap().iter().map(|r| r["swatch"].as_str().unwrap()).collect(); + assert_eq!(swatches, ["Crease", "Crease 2", "Cut", "Perforation"]); + let b = rect(&mut s, 100.0); + set_role(&mut s, json!({"role": "crease", "ids": [b.0]})); + assert_eq!(counts(&mut s, json!({"ids": [b.0]})), [0, 1, 0, 0], "the crease line is a crease line"); +} + +#[test] +fn native_save_and_open_keep_the_role_table_and_the_roles() { + let mut s = session("cmyk"); + let a = rect(&mut s, 20.0); + s.execute("swatch.new", &json!({"name": "Die", "color": {"model": "cmyk", "c": 0, "m": 0.8, "y": 0.2, "k": 0}, "spot": true})).unwrap(); + s.execute("addon.packaging.setRoleSwatch", &json!({"role": "cut", "swatch": "Die"})).unwrap(); + set_role(&mut s, json!({"role": "cut", "ids": [a.0]})); + let saved = s.execute("document.export", &json!({"format": "vectorcraft"})).unwrap(); + s.execute("document.open", &json!({"name": "box.vectorcraft", "dataBase64": saved["dataBase64"]})).unwrap(); + assert_eq!(s.doc().unwrap().doc.unknown.get("packagingRoles").unwrap()["cut"], json!("Die")); + s.execute("select.none", &json!({})).unwrap(); + assert_eq!(counts(&mut s, json!({})), [1, 0, 0, 0]); +} + +/// A document with one rectangle of each of Cut and Crease. +fn two_roles() -> Session { + let mut s = session("cmyk"); + let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 100.0)); + set_role(&mut s, json!({"role": "cut", "ids": [a.0]})); + set_role(&mut s, json!({"role": "crease", "ids": [b.0]})); + s +} + +fn export(s: &mut Session, format: &str) -> String { + String::from_utf8_lossy(&b64(&s.execute("document.export", &json!({"format": format})).unwrap())).into_owned() +} + +#[test] +fn pdf_prints_each_role_on_its_swatch_s_separation_and_overprints_it() { + let mut s = two_roles(); + let c = rect(&mut s, 180.0); + set_role(&mut s, json!({"role": "partialCut", "ids": [c.0]})); + let bytes = vectorcraft_pdf::export( + &s.doc().unwrap().doc, + &vectorcraft_pdf::PdfOptions { created: Some(0), ..vectorcraft_pdf::PdfOptions::uncompressed() }, + ) + .unwrap(); + let pdf = String::from_utf8_lossy(&bytes); + assert!(pdf.contains("/Separation/Cut"), "the Cut line prints on the Cut plate"); + assert!(pdf.contains("/Separation/Crease")); + assert!(pdf.contains("/Separation/Partial#20Cut"), "a name with a space"); + assert!(pdf.contains("/OP true"), "the role strokes overprint"); + // Without overprint, nothing in the file overprints. + let mut plain = session("cmyk"); + let (a, b) = (rect(&mut plain, 20.0), rect(&mut plain, 100.0)); + set_role(&mut plain, json!({"role": "cut", "ids": [a.0], "overprint": false})); + set_role(&mut plain, json!({"role": "crease", "ids": [b.0], "overprint": false})); + let bytes = vectorcraft_pdf::export( + &plain.doc().unwrap().doc, + &vectorcraft_pdf::PdfOptions { created: Some(0), ..vectorcraft_pdf::PdfOptions::uncompressed() }, + ) + .unwrap(); + assert!(!String::from_utf8_lossy(&bytes).contains("/OP true")); + assert!(!export(&mut s, "pdf").is_empty()); +} + +#[test] +fn svg_dxf_and_hpgl_keep_the_default_role_swatches_apart() { + let mut s = two_roles(); + let svg = export(&mut s, "svg"); + let strokes: BTreeSet<&str> = svg.split("stroke=\"").skip(1).filter_map(|t| t.split('"').next()).filter(|c| c.starts_with('#')).collect(); + let strokes = if strokes.is_empty() { + svg.split("stroke:").skip(1).filter_map(|t| t.split([';', '"', '}']).next()).filter(|c| c.starts_with('#')).collect() + } else { + strokes + }; + assert_eq!(strokes.len(), 2, "two stroke colors: {svg}"); + let dxf = export(&mut s, "dxf"); + let lines: Vec<&str> = dxf.lines().map(str::trim).collect(); + // The rectangles' white fills come out as true colors too. + let colors: BTreeSet<&str> = lines.windows(2).filter(|w| w[0] == "420" && w[1] != "16777215").map(|w| w[1]).collect(); + assert_eq!(colors.len(), 2, "two stroke true colors: {colors:?}"); + let plot = s.execute("document.export", &json!({"format": "hpgl", "hpglVersion": "hpgl2"})).unwrap(); + let plot = String::from_utf8_lossy(&b64(&plot)).into_owned(); + assert!(plot.contains("SP1") && plot.contains("SP2"), "a pen per role swatch color: {plot}"); +} + +#[test] +fn compound_paths_carry_a_role() { + let mut s = session("cmyk"); + let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 30.0)); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let c = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap()); + assert!(matches!(node(&s, c).kind, NodeKind::Compound { .. })); + let r = set_role(&mut s, json!({"role": "cut", "ids": [c.0]})); + assert_eq!(r["ids"], json!([c.0])); + assert_eq!(counts(&mut s, json!({"ids": [c.0]})), [1, 0, 0, 0]); + // A member named by id gives its compound the role. + let r = set_role(&mut s, json!({"role": "crease", "ids": [a.0, b.0]})); + assert_eq!((r["ids"].clone(), r["changed"].as_u64()), (json!([c.0]), Some(1))); + assert_eq!(counts(&mut s, json!({"ids": [c.0]})), [0, 1, 0, 0]); +} diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 03a931ba5d..97db1d94ce 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -40,6 +40,9 @@ pub(super) const ALLOWED: &[&str] = &[ "addon.image.colorMask", "addon.image.removeBackground", "addon.image.removeColorMask", + "addon.packaging.roles", + "addon.packaging.setRole", + "addon.packaging.setRoleSwatch", "addon.pathtools.addPoints", "addon.pathtools.close", "addon.pathtools.corner", diff --git a/crates/engine/src/cmd/swatch.rs b/crates/engine/src/cmd/swatch.rs index 3388b8344b..72c3821bde 100644 --- a/crates/engine/src/cmd/swatch.rs +++ b/crates/engine/src/cmd/swatch.rs @@ -48,7 +48,7 @@ pub fn specs() -> Vec { "Swatch Options", ["Window", "Swatches"], None, - "{name, newName?, color? (e.g. {l, a, b} for a Lab colour; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill; the swatch's own color and a color given with mode keep their model), mode?: \"gray\"|\"rgb\"|\"hsb\"|\"lab\"|\"cmyk\"|\"web\" (convert the colour), global?, spot? (spot colours are always global), paint?: paint.setFill params ({color}, {gradient} or {swatch}) or {pattern: name} replacing the swatch's colour; gradient or pattern with one of the same kind (stored as swatch.new stores it: a gradient keeps its aspect with or without start/end and holds no swatch link; a pattern is untransformed)} edit a swatch in any colour group, as one undo step. Fills, strokes, text, gradient stops and tint swatches linked to a global swatch take its new colour (at their own tint) and name; turning Global off unlinks them (they keep their colour). Colour, mode and spot apply to solid colours only; a tint swatch only takes a new name (edit its base) → {name, relinked: paints changed}", + "{name, newName?, color? (e.g. {l, a, b} for a Lab colour; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill; the swatch's own color and a color given with mode keep their model), mode?: \"gray\"|\"rgb\"|\"hsb\"|\"lab\"|\"cmyk\"|\"web\" (convert the colour), global?, spot? (spot colours are always global), paint?: paint.setFill params ({color}, {gradient} or {swatch}) or {pattern: name} replacing the swatch's colour; gradient or pattern with one of the same kind (stored as swatch.new stores it: a gradient keeps its aspect with or without start/end and holds no swatch link; a pattern is untransformed)} edit a swatch in any colour group, as one undo step. Fills, strokes, text, gradient stops and tint swatches linked to a global swatch take its new colour (at their own tint) and name; turning Global off unlinks them (they keep their colour). A fold line role the swatch carries (addon.packaging.roles) stays with it under its new name, and moves to a new swatch name when Global is turned off. Colour, mode and spot apply to solid colours only; a tint swatch only takes a new name (edit its base) → {name, relinked: paints changed}", has_doc, swatch_edit ), @@ -93,7 +93,7 @@ pub fn specs() -> Vec { "Merge Swatches", ["Window", "Swatches"], None, - "{names: [two or more solid-colour swatches], name?: the merged swatch's name (one swatch kept)} keep the first (its name and colour) and delete the others; paints linked to them take its colour and link to it (or unlink when it isn't global), as one undo step → {name, merged: [deleted names], relinked}", + "{names: [two or more solid-colour swatches], name?: the merged swatch's name (one swatch kept)} keep the first (its name and colour) and delete the others; paints linked to them take its colour and link to it (or unlink when it isn't global), as one undo step. When the kept swatch is global and carries no fold line role (addon.packaging.roles), it takes the role of the first merged swatch that carried one → {name, merged: [deleted names], relinked}", has_doc, swatch_merge ), @@ -932,6 +932,8 @@ fn swatch_edit(s: &mut Session, p: &Value) -> Result { } } let relinked = map_swatch_links(d, &mut |c, l, t| relink.apply(c, l, t)); + // A fold line role carried by the swatch follows its new name, as the strokes do. + super::addons::role_swatch_edited(d, &name, &to, global); super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(C, e))?; Ok(relinked) })?; @@ -1128,6 +1130,8 @@ fn swatch_merge(s: &mut Session, p: &Value) -> Result { let relinked = s.edit("Merge Swatches", |d, _| { take_swatches(d, merged, |_| true); let relinked = map_swatch_links(d, &mut relink); + // The lines of a merged role swatch link to the kept swatch, which takes that role. + super::addons::role_swatches_merged(d, merged, keep, link.is_some()); super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(C, e))?; Ok(relinked) })?; diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index fce3742d11..30d0dc96cf 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -993,6 +993,13 @@ fn structured_junk() { ("addon.document.symbolsFromLayers", json!({"layers": "x", "replace": 3})), ("addon.document.symbolsFromLayers", json!({"layers": [1e308, -1, null, u64::MAX], "replace": true})), ("addon.document.symbolsFromLayers", json!({"layers": [], "replace": true})), + // Packaging Tools add-on. + ("addon.packaging.setRole", json!({"role": "cut", "ids": [u64::MAX], "overprint": "no"})), + ("addon.packaging.setRole", json!({"role": ["crease"], "ids": "all"})), + ("addon.packaging.setRole", json!({"role": "none", "overprint": null})), + ("addon.packaging.roles", json!({"ids": [-1, 1e300]})), + ("addon.packaging.setRoleSwatch", json!({"role": "perforation", "swatch": "[Registration]"})), + ("addon.packaging.setRoleSwatch", json!({"role": "cut", "swatch": 5})), // Smart Pen add-on. ("addon.pen.append", json!({"id": 2, "x": 1e308, "y": 0, "in": [1e308, -1e308]})), ("addon.pen.append", json!({"id": 2, "subpath": u64::MAX, "x": 0, "y": 0, "segment": "curved"})), diff --git a/crates/ui-egui/src/addons.rs b/crates/ui-egui/src/addons.rs index 522f82bd2b..b63c32af59 100644 --- a/crates/ui-egui/src/addons.rs +++ b/crates/ui-egui/src/addons.rs @@ -9,6 +9,7 @@ pub mod cutting; pub mod document; pub mod enclosing_lasso; pub mod image; +pub mod packaging; pub mod pathtools; pub mod pen; pub mod select; @@ -30,6 +31,7 @@ pub fn plugin_menu() -> Vec { Item::Sub("Document Tools", document::menu()), Item::Sub("Enclosing Lasso", enclosing_lasso::menu()), Item::Sub("Image Tools", image::menu()), + Item::Sub("Packaging Tools", packaging::menu()), Item::Sub("Path Precision Tools", pathtools::menu()), Item::Sub("Selection Tools", select::menu()), Item::Sub("Smart Pen", pen::menu()), diff --git a/crates/ui-egui/src/addons/packaging.rs b/crates/ui-egui/src/addons/packaging.rs new file mode 100644 index 0000000000..1c70bef5d0 --- /dev/null +++ b/crates/ui-egui/src/addons/packaging.rs @@ -0,0 +1,134 @@ +//! Packaging Tools' submenu (Object › Plug-ins › Packaging Tools) and its Fold Lines panel. The +//! panel lists the fold line roles, each with its swatch's chip and how many of the selected objects +//! have it (of the whole document while nothing is selected); clicking a role gives the selected +//! paths that role (`addon.packaging.setRole`). Its menu's Role Swatches… picks the swatch that +//! carries a role (`addon.packaging.setRoleSwatch`). + +use egui::{Align, Layout, Sense, Ui, vec2}; +use serde_json::{Value, json}; + +use crate::VectorcraftApp; +use crate::menus::Item; +use crate::panels::{empty_state, pstate, set_pstate}; +use crate::widgets::{self, dim_label}; + +/// The panel's id (`window.panel {panel: "foldLines"}`). +pub const ID: &str = "foldLines"; +/// The command that gives objects a role. +pub const SET_ROLE: &str = "addon.packaging.setRole"; +/// The command that picks a role's swatch. +pub const SET_ROLE_SWATCH: &str = "addon.packaging.setRoleSwatch"; +/// 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")]; + +/// Where the panel keeps the last `addon.packaging.roles` answer (panel state). +const STATE: &str = "fold-lines"; + +/// Object › Plug-ins › Packaging Tools. +pub fn menu() -> Vec { + let make = |label, role: &str| Item::Cmd(label, SET_ROLE, json!({ "role": role })); + vec![ + Item::Cmd("Fold Lines", "window.panel", json!({ "panel": ID })), + Item::Sep, + make("Make Cut Line", "cut"), + make("Make Crease Line", "crease"), + make("Make Partial Cut Line", "partialCut"), + make("Make Perforation Line", "perforation"), + ] +} + +/// One role row: (role id, swatch name, the swatch's paint if the document has it, count). +type Row = (String, String, Option, u64); + +/// The panel's rows for one document state. +#[derive(Clone, Default)] +struct Rows { + /// What they were read for: the document, its revision and its selection. + key: Option<(u64, u64, Vec)>, + rows: Vec, +} + +/// The rows for the active document as it is now, read again only when it changed. +fn rows(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec { + let Some(st) = app.session.active() else { return vec![] }; + let key = (st.uid, st.revision, st.selection.objects.iter().map(|id| id.0).collect::>()); + let mut kept: Rows = pstate(ctx, STATE); + if kept.key.as_ref() == Some(&key) { + return kept.rows; + } + let answer = app.session.execute("addon.packaging.roles", &json!({})).unwrap_or(Value::Null); + let d = app.session.active().map(|st| st.doc.clone()); + let row = |r: &Value| { + let swatch = r["swatch"].as_str()?.to_string(); + let paint = d.as_ref().and_then(|d| d.swatch(&swatch)).map(|s| s.paint.clone()); + Some((r["role"].as_str()?.to_string(), swatch, paint, r["count"].as_u64()?)) + }; + kept = Rows { key: Some(key), rows: answer["roles"].as_array().into_iter().flatten().filter_map(row).collect() }; + set_pstate(ctx, STATE, kept.clone()); + kept.rows +} + +pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { + let Some(st) = app.session.active() else { + empty_state(ui, "scissors", tl!("No document"), tl!("Open a document to mark its fold lines.")); + return; + }; + let selected = !st.selection.is_empty(); + if !selected { + dim_label(ui, tl!("No objects are selected.")); + ui.add_space(4.0); + } + let mut picked = None; + for (role, swatch, paint, count) in rows(app, ui.ctx()) { + let label = ROLES.iter().find(|(_, id)| *id == role).map_or(role.as_str(), |(l, _)| *l); + let clicked = ui + .add_enabled_ui(selected, |ui| { + ui.horizontal(|ui| { + let (chip, _) = ui.allocate_exact_size(vec2(14.0, 14.0), Sense::hover()); + widgets::paint_chip(ui, chip, paint.as_ref().unwrap_or(&vectorcraft_color::Paint::None)); + let resp = ui.selectable_label(false, tl!(label)).on_hover_text(swatch.as_str()); + ui.with_layout(Layout::right_to_left(Align::Center), |ui| dim_label(ui, &count.to_string())); + resp.clicked() + }) + .inner + }) + .inner; + if clicked { + picked = Some(role); + } + } + if let Some(role) = picked + && let Err(e) = app.run(SET_ROLE, json!({ "role": role })) + { + app.status(e); + } +} + +/// Role Swatches… (the dialog of `addon.packaging.setRoleSwatch`): when another role is picked, its +/// Swatch field shows that role's current swatch. `__role` keeps the role the field was filled for. +pub(crate) fn follow_role(app: &mut VectorcraftApp, d: &mut crate::state::Dialog) { + let role = d.str("role"); + if d.str("__role") == role { + return; + } + let answer = app.session.execute("addon.packaging.roles", &json!({})).unwrap_or(Value::Null); + let current = answer["roles"].as_array().into_iter().flatten().find(|r| r["role"] == role.as_str()).and_then(|r| r["swatch"].as_str()); + if let Some(swatch) = current { + d.fields.insert("swatch".into(), json!(swatch)); + } + d.fields.insert("__role".into(), json!(role)); +} + +/// The panel's ≡ menu: Role Swatches… opens the options of `addon.packaging.setRoleSwatch` on the +/// Cut role and its current swatch. +pub fn panel_menu(app: &mut VectorcraftApp, ui: &mut Ui) { + if widgets::menu_item(ui, tl!("Role Swatches…"), app.session.active().is_some(), false) { + let swatch = rows(app, ui.ctx()).into_iter().find(|r| r.0 == "cut").map_or_else(|| "Cut".to_string(), |r| r.1); + let (id, p) = crate::menus::click_target("Role Swatches…", SET_ROLE_SWATCH, &json!({ "role": "cut", "swatch": swatch })); + crate::menus::invoke(app, &id, p); + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/addons/packaging/tests.rs b/crates/ui-egui/src/addons/packaging/tests.rs new file mode 100644 index 0000000000..cfe9909dc8 --- /dev/null +++ b/crates/ui-egui/src/addons/packaging/tests.rs @@ -0,0 +1,133 @@ +use serde_json::json; +use vectorcraft_engine::Session; + +use super::{ID, ROLES, SET_ROLE, SET_ROLE_SWATCH, show}; +use crate::tests_labels::painted_text; +use crate::{VectorcraftApp, menus}; + +/// An app with two rectangles, nothing selected → (app, their ids). +fn app() -> (VectorcraftApp, u64, u64) { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let rect = |app: &mut VectorcraftApp, x: f64| { + app.run("shape.rectangle", json!({"x": x, "y": 20, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap() + }; + let (a, b) = (rect(&mut app, 20.0), rect(&mut app, 100.0)); + app.run("select.none", json!({})).unwrap(); + (app, a, b) +} + +#[test] +fn the_plugins_submenu_opens_the_panel_and_makes_each_kind_of_line() { + let (mut app, a, _) = app(); + let entries = menus::menu_entries(&app); + let under = |label: &str| entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Packaging Tools"] && e.label == label); + let item = under("Fold Lines").expect("listed"); + assert_eq!((item.command.as_deref(), &item.params), (Some("window.panel"), &json!({ "panel": ID }))); + for (label, role) in + [("Make Cut Line", "cut"), ("Make Crease Line", "crease"), ("Make Partial Cut Line", "partialCut"), ("Make Perforation Line", "perforation")] + { + let e = under(label).unwrap_or_else(|| panic!("{label} listed")); + assert_eq!((e.command.as_deref(), &e.params), (Some(SET_ROLE), &json!({ "role": role })), "{label}"); + } + assert!(!crate::panel_docking::showing(&app.ui, ID)); + menus::invoke(&mut app, "window.panel", item.params.clone()); + assert!(crate::panel_docking::showing(&app.ui, ID), "the panel opens"); + app.run("select.set", json!({"ids": [a]})).unwrap(); + let make = under("Make Partial Cut Line").unwrap(); + let (target, p) = menus::click_target(&make.label, SET_ROLE, &make.params); + menus::invoke(&mut app, &target, p); + let r = app.session.execute("addon.packaging.roles", &json!({"ids": [a]})).unwrap(); + assert_eq!(r["roles"][2]["count"], json!(1), "{r}"); +} + +#[test] +fn the_panel_counts_the_roles_and_says_when_nothing_is_selected() { + let (mut app, a, b) = app(); + app.run(SET_ROLE, json!({"role": "cut", "ids": [a, b]})).unwrap(); + app.run("select.none", json!({})).unwrap(); + let text = painted_text(&mut app, show); + assert!(text.contains("No objects are selected."), "{text}"); + for (label, _) in ROLES { + assert!(text.contains(label), "{label}: {text}"); + } + assert!(text.contains('2'), "the document's two cut lines: {text}"); + app.run("select.set", json!({"ids": [a]})).unwrap(); + let text = painted_text(&mut app, show); + assert!(!text.contains("No objects are selected."), "{text}"); + assert!(text.contains('1') && !text.contains('2'), "the selection's one cut line: {text}"); +} + +/// A click on the panel row 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_row(app: &mut VectorcraftApp, label: &str) { + crate::i18n::set_current(crate::i18n::Lang::EN); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + let mut time = 0.0; + let mut frame = |app: &mut VectorcraftApp, events: Vec| { + time += 0.1; + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(300.0, 200.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 + }; + frame(app, vec![]); + let out = frame(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!("no row 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 }; + frame(app, vec![egui::Event::PointerMoved(at)]); + frame(app, vec![button(true)]); + frame(app, vec![button(false)]); +} + +#[test] +fn clicking_a_row_gives_the_selection_that_role_and_does_nothing_without_one() { + let (mut app, a, b) = app(); + click_row(&mut app, "Crease Line"); + let none = app.session.execute("addon.packaging.roles", &json!({"ids": [a, b]})).unwrap(); + assert_eq!(none["roles"][1]["count"], json!(0), "nothing selected: {none}"); + app.run("select.set", json!({"ids": [a]})).unwrap(); + click_row(&mut app, "Crease Line"); + let r = app.session.execute("addon.packaging.roles", &json!({"ids": [a, b]})).unwrap(); + assert_eq!(r["roles"][1]["count"], json!(1), "{r}"); +} + +#[test] +fn role_swatches_opens_the_options_of_its_command() { + let (target, p) = menus::click_target("Role Swatches…", SET_ROLE_SWATCH, &json!({"role": "cut", "swatch": "Cut"})); + assert_eq!((target.as_str(), &p["command"]), ("ui.paramDialog", &json!(SET_ROLE_SWATCH))); + let doc = vectorcraft_engine::find_command(SET_ROLE_SWATCH).unwrap().params; + let ids: Vec<&str> = ROLES.iter().map(|(_, id)| *id).collect(); + assert!(doc.contains(&format!("role: {}", ids.join("|"))), "{doc}"); +} + +#[test] +fn role_swatches_shows_the_swatch_of_the_role_picked() { + let (mut app, a, _) = app(); + app.run(SET_ROLE, json!({"role": "crease", "ids": [a]})).unwrap(); + app.run("swatch.edit", json!({"name": "Crease", "newName": "Score"})).unwrap(); + let mut d = crate::state::Dialog::new("command", json!({"role": "cut", "swatch": "Cut"})); + super::follow_role(&mut app, &mut d); + assert_eq!(d.str("swatch"), "Cut"); + d.fields.insert("role".into(), json!("crease")); + super::follow_role(&mut app, &mut d); + assert_eq!(d.str("swatch"), "Score", "the Crease role's swatch"); + // A swatch typed for the same role stays. + d.fields.insert("swatch".into(), json!("Ink")); + super::follow_role(&mut app, &mut d); + assert_eq!(d.str("swatch"), "Ink"); + assert_eq!(crate::dialogs::form::params(&d), json!({"role": "crease", "swatch": "Ink"}), "the dialog sends no __role"); +} + +#[test] +fn the_panel_without_a_document_asks_for_one() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let text = painted_text(&mut app, show); + assert!(text.contains("No document"), "{text}"); +} diff --git a/crates/ui-egui/src/dialogs/command.rs b/crates/ui-egui/src/dialogs/command.rs index 35890cd18e..a4098ac3fa 100644 --- a/crates/ui-egui/src/dialogs/command.rs +++ b/crates/ui-egui/src/dialogs/command.rs @@ -24,6 +24,9 @@ pub(super) const SPEC: DialogSpec = DialogSpec { let cmyk = app.session.active().is_some_and(|s| s.doc.color_mode == vectorcraft_doc::ColorMode::Cmyk); let choices = |k: &str| rasterize_color_models(&command, k, cmyk).or_else(|| choices(&command, k)); form::param_fields(ui, d, &|k| lengths.contains(&k), &choices, &rank, app.session.general_unit()); + if command == crate::addons::packaging::SET_ROLE_SWATCH { + crate::addons::packaging::follow_role(app, d); + } if linked && d.fields.get("rowGutter") == d.fields.get("__rowGutterLinked") && let Some(g) = d.fields.get("gutter").cloned() @@ -161,6 +164,7 @@ fn order(command: &str) -> &'static [&'static str] { &["background", "colors", "contiguous", "match", "tolerance", "softness"] } crate::addons::cutting::BRIDGES => &["width", "count", "direction", "keepOriginal"], + crate::addons::packaging::SET_ROLE_SWATCH => &["role", "swatch"], _ => &[], } } @@ -170,6 +174,7 @@ fn choices(command: &str, key: &str) -> Option { match (command, key) { ("type.pathOptions", "effect") => Some(crate::menus::PATH_EFFECTS), ("type.pathOptions", "alignToPath") => Some(PATH_ALIGN), + (crate::addons::packaging::SET_ROLE_SWATCH, "role") => Some(crate::addons::packaging::ROLES), (crate::addons::typetools::RELEASE, "mode") => Some(crate::addons::typetools::RELEASE_MODES), (crate::addons::cutting::BRIDGES, "direction") => Some(crate::addons::cutting::BRIDGE_DIRECTIONS), ("text.areaOptions", "fit") => Some(AREA_FIT), diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index fb3080c8c2..115eb9d69a 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -6917,3 +6917,20 @@ breakText Glyphs Глифи Nest Shapes… Подреждане на форми… Nest Shapes Подреждане на форми Roll Ролка + Packaging Tools Инструменти за опаковки + Fold Lines Линии на сгъване + Make Cut Line Направи линия за рязане + Make Crease Line Направи линия за биговане + Make Partial Cut Line Направи линия за частично рязане + Make Perforation Line Направи линия за перфорация + Make Fold Line Направи линия на сгъване + Role Swatches… Образци за видовете линии… + Role Swatches Образци за видовете линии + Role Вид линия + Cut Line Линия за рязане + Crease Line Линия за биговане + Partial Cut Line Линия за частично рязане + Perforation Line Линия за перфорация + No objects are selected. Няма избрани обекти. + Open a document to mark its fold lines. Отворете документ, за да отбележите линиите му на сгъване. + Remove Fold Line Role Премахни вида на линията diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 118609f801..ffb73c464e 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -6970,3 +6970,20 @@ shape Open Otvoren Nest Shapes… Slaganje oblika… Nest Shapes Slaganje oblika Roll Rolna + Packaging Tools Alati za ambalažu + Fold Lines Linije savijanja + Make Cut Line Napravi liniju rezanja + Make Crease Line Napravi liniju bigovanja + Make Partial Cut Line Napravi liniju djelimičnog rezanja + Make Perforation Line Napravi liniju perforacije + Make Fold Line Napravi liniju savijanja + Role Swatches… Uzorci boja za vrste linija… + Role Swatches Uzorci boja za vrste linija + Role Vrsta linije + Cut Line Linija rezanja + Crease Line Linija bigovanja + Partial Cut Line Linija djelimičnog rezanja + Perforation Line Linija perforacije + No objects are selected. Nijedan objekat nije odabran. + Open a document to mark its fold lines. Otvorite dokument da označite njegove linije savijanja. + Remove Fold Line Role Ukloni vrstu linije diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index ab50e14a58..8457d0d623 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -7629,3 +7629,20 @@ breakText Glyphs Glifs @msg {width} × {height} pixels is too large for JPEG (at most 65535 pixels a side): lower the resolution {width} × {height} píxels és massa gran per a JPEG (com a màxim 65535 píxels per costat): reduïu la resolució @msg {width} × {height} pixels is too large for Targa (at most 65535 pixels a side): lower the resolution {width} × {height} píxels és massa gran per a Targa (com a màxim 65535 píxels per costat): reduïu la resolució @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} píxels és massa gran per a PSD (com a màxim {MAX_SIDE} píxels per costat): reduïu la resolució + Packaging Tools Eines d’embalatge + Fold Lines Línies de plegat + Make Cut Line Converteix en línia de tall + Make Crease Line Converteix en línia d’hendit + Make Partial Cut Line Converteix en línia de tall parcial + Make Perforation Line Converteix en línia de perforació + Make Fold Line Converteix en línia de plegat + Role Swatches… Mostres dels tipus de línia… + Role Swatches Mostres dels tipus de línia + Role Tipus de línia + Cut Line Línia de tall + Crease Line Línia d’hendit + Partial Cut Line Línia de tall parcial + Perforation Line Línia de perforació + No objects are selected. No hi ha cap objecte seleccionat. + Open a document to mark its fold lines. Obre un document per marcar-ne les línies de plegat. + Remove Fold Line Role Elimina el tipus de línia diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 3b9c300980..e0c7035177 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -9461,3 +9461,20 @@ breakText Glyphs Glyfy @msg turn on at least one side zapněte alespoň jednu stranu @msg with no hem and no grommets there is nothing to mark bez lemu a bez průchodek není co označit @msg {saving} failed: {e} {saving} se nezdařilo: {e} + Packaging Tools Nástroje pro obaly + Fold Lines Linie skladu + Make Cut Line Vytvořit linii řezu + Make Crease Line Vytvořit linii bigu + Make Partial Cut Line Vytvořit linii částečného řezu + Make Perforation Line Vytvořit linii perforace + Make Fold Line Vytvořit linii skladu + Role Swatches… Vzorník typů linií… + Role Swatches Vzorník typů linií + Role Typ linie + Cut Line Linie řezu + Crease Line Linie bigu + Partial Cut Line Linie částečného řezu + Perforation Line Linie perforace + No objects are selected. Nejsou vybrány žádné objekty. + Open a document to mark its fold lines. Otevřete dokument, abyste označili jeho linie skladu. + Remove Fold Line Role Odstranit typ linie diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 59ce36d15f..e9061c9278 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -7542,3 +7542,20 @@ breakText Glyphs Glyffer Nest Shapes… Pak figurer tæt… Nest Shapes Pak figurer tæt Roll Rulle + Packaging Tools Emballageværktøjer + Fold Lines Foldelinjer + Make Cut Line Gør til skærelinje + Make Crease Line Gør til rillelinje + Make Partial Cut Line Gør til delvis skærelinje + Make Perforation Line Gør til perforeringslinje + Make Fold Line Gør til foldelinje + Role Swatches… Farveprøver for linjetyper… + Role Swatches Farveprøver for linjetyper + Role Linjetype + Cut Line Skærelinje + Crease Line Rillelinje + Partial Cut Line Delvis skærelinje + Perforation Line Perforeringslinje + No objects are selected. Ingen objekter er markeret. + Open a document to mark its fold lines. Åbn et dokument for at markere dets foldelinjer. + Remove Fold Line Role Fjern linjetype diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index ddc01a8016..0b06cc8a8d 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -9061,3 +9061,20 @@ breakText Glyphs Glyphen Nest Shapes… Formen verschachteln… Nest Shapes Formen verschachteln Roll Rolle + Packaging Tools Verpackungswerkzeuge + Fold Lines Faltlinien + Make Cut Line Als Schnittlinie festlegen + Make Crease Line Als Rilllinie festlegen + Make Partial Cut Line Als Teilschnittlinie festlegen + Make Perforation Line Als Perforationslinie festlegen + Make Fold Line Als Faltlinie festlegen + Role Swatches… Farbfelder der Linienarten… + Role Swatches Farbfelder der Linienarten + Role Linienart + Cut Line Schnittlinie + Crease Line Rilllinie + Partial Cut Line Teilschnittlinie + Perforation Line Perforationslinie + No objects are selected. Es sind keine Objekte ausgewählt. + Open a document to mark its fold lines. Öffnen Sie ein Dokument, um seine Faltlinien festzulegen. + Remove Fold Line Role Linienart entfernen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index a89d3c72e4..fa5fca58dd 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -7602,3 +7602,20 @@ breakText Glyphs Γλύφοι @msg {width} × {height} pixels is too large for JPEG (at most 65535 pixels a side): lower the resolution τα {width} × {height} εικονοστοιχεία είναι υπερβολικό μέγεθος για JPEG (το πολύ 65535 εικονοστοιχεία ανά πλευρά): μειώστε την ανάλυση @msg {width} × {height} pixels is too large for Targa (at most 65535 pixels a side): lower the resolution τα {width} × {height} εικονοστοιχεία είναι υπερβολικό μέγεθος για Targa (το πολύ 65535 εικονοστοιχεία ανά πλευρά): μειώστε την ανάλυση @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution τα {w} × {h} εικονοστοιχεία είναι υπερβολικό μέγεθος για PSD (το πολύ {MAX_SIDE} εικονοστοιχεία ανά πλευρά): μειώστε την ανάλυση + Packaging Tools Εργαλεία συσκευασίας + Fold Lines Γραμμές δίπλωσης + Make Cut Line Δημιουργία γραμμής κοπής + Make Crease Line Δημιουργία γραμμής πτύχωσης + Make Partial Cut Line Δημιουργία γραμμής μερικής κοπής + Make Perforation Line Δημιουργία γραμμής διάτρησης + Make Fold Line Δημιουργία γραμμής δίπλωσης + Role Swatches… Δείγματα χρωμάτων τύπων γραμμής… + Role Swatches Δείγματα χρωμάτων τύπων γραμμής + Role Τύπος γραμμής + Cut Line Γραμμή κοπής + Crease Line Γραμμή πτύχωσης + Partial Cut Line Γραμμή μερικής κοπής + Perforation Line Γραμμή διάτρησης + No objects are selected. Δεν έχουν επιλεγεί αντικείμενα. + Open a document to mark its fold lines. Ανοίξτε ένα έγγραφο για να σημειώσετε τις γραμμές δίπλωσής του. + Remove Fold Line Role Αφαίρεση τύπου γραμμής diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 4a912f8005..59da9db59c 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -7592,3 +7592,20 @@ breakText Glyphs Glifos Nest Shapes… Anidar formas… Nest Shapes Anidar formas Roll Rollo + Packaging Tools Herramientas de embalaje + Fold Lines Líneas de plegado + Make Cut Line Convertir en línea de corte + Make Crease Line Convertir en línea de hendido + Make Partial Cut Line Convertir en línea de corte parcial + Make Perforation Line Convertir en línea de perforación + Make Fold Line Convertir en línea de plegado + Role Swatches… Muestras de los tipos de línea… + Role Swatches Muestras de los tipos de línea + Role Tipo de línea + Cut Line Línea de corte + Crease Line Línea de hendido + Partial Cut Line Línea de corte parcial + Perforation Line Línea de perforación + No objects are selected. No hay objetos seleccionados. + Open a document to mark its fold lines. Abre un documento para marcar sus líneas de plegado. + Remove Fold Line Role Quitar tipo de línea diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 06499d13ea..e7f4221a83 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -7686,3 +7686,20 @@ breakText Glyphs Merkit @msg {width} × {height} pixels is too large for JPEG (at most 65535 pixels a side): lower the resolution {width} × {height} pikseliä on liian suuri JPEG-kuvalle (enintään 65535 pikseliä sivua kohti): pienennä tarkkuutta @msg {width} × {height} pixels is too large for Targa (at most 65535 pixels a side): lower the resolution {width} × {height} pikseliä on liian suuri Targa-kuvalle (enintään 65535 pikseliä sivua kohti): pienennä tarkkuutta @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} pikseliä on liian suuri PSD-kuvalle (enintään {MAX_SIDE} pikseliä sivua kohti): pienennä tarkkuutta + Packaging Tools Pakkaustyökalut + Fold Lines Taittoviivat + Make Cut Line Tee leikkausviiva + Make Crease Line Tee nuuttausviiva + Make Partial Cut Line Tee osittainen leikkausviiva + Make Perforation Line Tee rei’itysviiva + Make Fold Line Tee taittoviiva + Role Swatches… Viivatyyppien värimallit… + Role Swatches Viivatyyppien värimallit + Role Viivatyyppi + Cut Line Leikkausviiva + Crease Line Nuuttausviiva + Partial Cut Line Osittainen leikkausviiva + Perforation Line Rei’itysviiva + No objects are selected. Objekteja ei ole valittu. + Open a document to mark its fold lines. Avaa asiakirja, niin voit merkitä sen taittoviivat. + Remove Fold Line Role Poista viivatyyppi diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 90882cf105..a7def487ac 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -9446,4 +9446,21 @@ breakText Glyphs Glyphes @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} pixels, c’est trop grand pour le PSD ({MAX_SIDE} pixels par côté au plus) : réduisez la résolution @msg this is a DWG drawing, which can't be read: save it from the CAD app as a DXF and open that c’est un dessin DWG, qui ne peut pas être lu : enregistrez-le depuis l’application de CAO au format DXF et ouvrez ce fichier @msg this binary DXF file is damaged or cut short ce fichier DXF binaire est endommagé ou tronqué + Packaging Tools Outils d’emballage + Fold Lines Lignes de pliage + Make Cut Line Convertir en ligne de découpe + Make Crease Line Convertir en ligne de rainage + Make Partial Cut Line Convertir en ligne de découpe partielle + Make Perforation Line Convertir en ligne de perforation + Make Fold Line Convertir en ligne de pliage + Role Swatches… Nuances des types de ligne… + Role Swatches Nuances des types de ligne + Role Type de ligne + Cut Line Ligne de découpe + Crease Line Ligne de rainage + Partial Cut Line Ligne de découpe partielle + Perforation Line Ligne de perforation + No objects are selected. Aucun objet n’est sélectionné. + Open a document to mark its fold lines. Ouvrez un document pour marquer ses lignes de pliage. + Remove Fold Line Role Supprimer le type de ligne @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 0e9ed1997e..2fac5c0999 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -4700,3 +4700,20 @@ swatch [Registration] [રજિસ્ટ્રેશન] Repeat Objects પુનરાવર્તિત ઑબ્જેક્ટ્સ @msg `{path}` must be one of {_1}, not {got} `{path}` એ {_1}માંથી એક હોવું જોઈએ, {got} નહીં Path Length પાથની લંબાઈ + Packaging Tools પેકેજિંગ ટૂલ્સ + Fold Lines ફોલ્ડ લાઇન્સ + Make Cut Line કટ લાઇન બનાવો + Make Crease Line ક્રીઝ લાઇન બનાવો + Make Partial Cut Line આંશિક કટ લાઇન બનાવો + Make Perforation Line પર્ફોરેશન લાઇન બનાવો + Make Fold Line ફોલ્ડ લાઇન બનાવો + Role Swatches… લાઇન પ્રકારના સ્વેચ… + Role Swatches લાઇન પ્રકારના સ્વેચ + Role લાઇન પ્રકાર + Cut Line કટ લાઇન + Crease Line ક્રીઝ લાઇન + Partial Cut Line આંશિક કટ લાઇન + Perforation Line પર્ફોરેશન લાઇન + No objects are selected. કોઈ ઑબ્જેક્ટ પસંદ કરેલ નથી. + Open a document to mark its fold lines. તેની ફોલ્ડ લાઇન્સ ચિહ્નિત કરવા દસ્તાવેજ ખોલો. + Remove Fold Line Role લાઇન પ્રકાર દૂર કરો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 671052e82b..eb65028fdd 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -8923,3 +8923,20 @@ theme Appearance अपीयरेंस Nest Shapes… आकृतियाँ सटाकर रखें… Nest Shapes आकृतियाँ सटाकर रखें Roll रोल + Packaging Tools पैकेजिंग टूल्स + Fold Lines फ़ोल्ड लाइनें + Make Cut Line कट लाइन बनाएँ + Make Crease Line क्रीज़ लाइन बनाएँ + Make Partial Cut Line आंशिक कट लाइन बनाएँ + Make Perforation Line परफ़ोरेशन लाइन बनाएँ + Make Fold Line फ़ोल्ड लाइन बनाएँ + Role Swatches… लाइन प्रकार के स्वॉचेस… + Role Swatches लाइन प्रकार के स्वॉचेस + Role लाइन प्रकार + Cut Line कट लाइन + Crease Line क्रीज़ लाइन + Partial Cut Line आंशिक कट लाइन + Perforation Line परफ़ोरेशन लाइन + No objects are selected. कोई ऑब्जेक्ट सिलेक्ट नहीं है। + Open a document to mark its fold lines. फ़ोल्ड लाइनें मार्क करने के लिए कोई डॉक्यूमेंट ओपन करें। + Remove Fold Line Role लाइन प्रकार हटाएँ diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index a218a2ce15..2db2b2a04e 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -9448,3 +9448,20 @@ breakText Glyphs Glifák @msg {width} × {height} pixels is too large for JPEG (at most 65535 pixels a side): lower the resolution {width} × {height} pixel túl nagy a JPEG formátumhoz (oldalanként legfeljebb 65535 pixel): csökkentsd a felbontást @msg {width} × {height} pixels is too large for Targa (at most 65535 pixels a side): lower the resolution {width} × {height} pixel túl nagy a Targa formátumhoz (oldalanként legfeljebb 65535 pixel): csökkentsd a felbontást @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} pixel túl nagy a PSD formátumhoz (oldalanként legfeljebb {MAX_SIDE} pixel): csökkentsd a felbontást + Packaging Tools Csomagolóeszközök + Fold Lines Hajtásvonalak + Make Cut Line Vágóvonallá alakítás + Make Crease Line Bigvonallá alakítás + Make Partial Cut Line Részleges vágóvonallá alakítás + Make Perforation Line Perforációs vonallá alakítás + Make Fold Line Hajtásvonallá alakítás + Role Swatches… Vonaltípusok színmintái… + Role Swatches Vonaltípusok színmintái + Role Vonaltípus + Cut Line Vágóvonal + Crease Line Bigvonal + Partial Cut Line Részleges vágóvonal + Perforation Line Perforációs vonal + No objects are selected. Nincs kijelölt objektum. + Open a document to mark its fold lines. Nyiss meg egy dokumentumot a hajtásvonalai megjelöléséhez. + Remove Fold Line Role Vonaltípus eltávolítása diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index fdf06cc9ee..e3c066b125 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -6932,3 +6932,20 @@ breakText Glyphs Glif Nest Shapes… Susun Bentuk… Nest Shapes Susun Bentuk Roll Gulungan + Packaging Tools Alat kemasan + Fold Lines Garis lipat + Make Cut Line Jadikan garis potong + Make Crease Line Jadikan garis lekuk + Make Partial Cut Line Jadikan garis potong sebagian + Make Perforation Line Jadikan garis perforasi + Make Fold Line Jadikan garis lipat + Role Swatches… Swatch jenis garis… + Role Swatches Swatch jenis garis + Role Jenis garis + Cut Line Garis potong + Crease Line Garis lekuk + Partial Cut Line Garis potong sebagian + Perforation Line Garis perforasi + No objects are selected. Tidak ada objek yang dipilih. + Open a document to mark its fold lines. Buka dokumen untuk menandai garis lipatnya. + Remove Fold Line Role Hapus jenis garis diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 2b5a6bf3da..265460fb36 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -9094,3 +9094,20 @@ breakText Glyphs Glifi Nest Shapes… Annida forme… Nest Shapes Annida forme Roll Rotolo + Packaging Tools Strumenti di imballaggio + Fold Lines Linee di piega + Make Cut Line Trasforma in linea di taglio + Make Crease Line Trasforma in linea di cordonatura + Make Partial Cut Line Trasforma in linea di taglio parziale + Make Perforation Line Trasforma in linea di perforazione + Make Fold Line Trasforma in linea di piega + Role Swatches… Campioni dei tipi di linea… + Role Swatches Campioni dei tipi di linea + Role Tipo di linea + Cut Line Linea di taglio + Crease Line Linea di cordonatura + Partial Cut Line Linea di taglio parziale + Perforation Line Linea di perforazione + No objects are selected. Nessun oggetto selezionato. + Open a document to mark its fold lines. Apri un documento per segnarne le linee di piega. + Remove Fold Line Role Rimuovi tipo di linea diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 87ec6c8b05..f4f35c7bbe 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -9160,3 +9160,20 @@ breakText Glyphs 字形 @msg turn on at least one side 少なくとも 1 つの辺をオンにしてください @msg with no hem and no grommets there is nothing to mark 折り返しもハトメもないため、マークを付けるものがありません @msg {saving} failed: {e} {saving} に失敗しました: {e} + Packaging Tools パッケージツール + Fold Lines 折り線 + Make Cut Line カット線にする + Make Crease Line 筋入れ線にする + Make Partial Cut Line 半抜き線にする + Make Perforation Line ミシン目線にする + Make Fold Line 折り線にする + Role Swatches… 線種のスウォッチ… + Role Swatches 線種のスウォッチ + Role 線種 + Cut Line カット線 + Crease Line 筋入れ線 + Partial Cut Line 半抜き線 + Perforation Line ミシン目線 + No objects are selected. オブジェクトが選択されていません。 + Open a document to mark its fold lines. ドキュメントを開くと折り線を設定できます。 + Remove Fold Line Role 線種を解除 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8c42eafaf1..327e1da0e2 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -7646,3 +7646,20 @@ font-script Japanese იაპონური Nest Shapes… ფორმების განლაგება… Nest Shapes ფორმების განლაგება Roll რულონი + Packaging Tools შეფუთვის ხელსაწყოები + Fold Lines მოკეცვის ხაზები + Make Cut Line ჭრის ხაზად გადაქცევა + Make Crease Line ბიგის ხაზად გადაქცევა + Make Partial Cut Line ნაწილობრივი ჭრის ხაზად გადაქცევა + Make Perforation Line პერფორაციის ხაზად გადაქცევა + Make Fold Line მოკეცვის ხაზად გადაქცევა + Role Swatches… ხაზის ტიპების ფერის ნიმუშები… + Role Swatches ხაზის ტიპების ფერის ნიმუშები + Role ხაზის ტიპი + Cut Line ჭრის ხაზი + Crease Line ბიგის ხაზი + Partial Cut Line ნაწილობრივი ჭრის ხაზი + Perforation Line პერფორაციის ხაზი + No objects are selected. ობიექტები არ არის მონიშნული. + Open a document to mark its fold lines. გახსენით დოკუმენტი მისი მოკეცვის ხაზების მოსანიშნად. + Remove Fold Line Role ხაზის ტიპის მოხსნა diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 4fd8001ea7..767b352aff 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -9056,3 +9056,20 @@ breakText Glyphs 글리프 @msg {what} would print more than {MAX_COPIES_PER_SHEET} copies on a sheet: scale it up {what}은(는) 한 장에 {MAX_COPIES_PER_SHEET}개보다 많이 인쇄됩니다: 크기를 키우세요 @msg {what} would print on more than {MAX_TILES} tiles: scale it down {what}은(는) 타일 {MAX_TILES}개보다 많이 나뉘어 인쇄됩니다: 크기를 줄이세요 @msg {what} {i} out of range {what} {i}이(가) 범위를 벗어났습니다 + Packaging Tools 패키징 도구 + Fold Lines 접는 선 + Make Cut Line 재단선으로 만들기 + Make Crease Line 오시선으로 만들기 + Make Partial Cut Line 하프 컷 선으로 만들기 + Make Perforation Line 미싱선으로 만들기 + Make Fold Line 접는 선으로 만들기 + Role Swatches… 선 종류 견본… + Role Swatches 선 종류 견본 + Role 선 종류 + Cut Line 재단선 + Crease Line 오시선 + Partial Cut Line 하프 컷 선 + Perforation Line 미싱선 + No objects are selected. 선택한 개체가 없습니다. + Open a document to mark its fold lines. 접는 선을 지정하려면 문서를 여세요. + Remove Fold Line Role 선 종류 제거 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 31872f060e..581714423f 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -9495,3 +9495,20 @@ breakText Glyphs Glyphs @msg {width} × {height} pixels is too large for JPEG (at most 65535 pixels a side): lower the resolution {width} × {height} pixels is te groot voor JPEG (maximaal 65535 pixels per zijde): verlaag de resolutie @msg {width} × {height} pixels is too large for Targa (at most 65535 pixels a side): lower the resolution {width} × {height} pixels is te groot voor Targa (maximaal 65535 pixels per zijde): verlaag de resolutie @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} pixels is te groot voor PSD (maximaal {MAX_SIDE} pixels per zijde): verlaag de resolutie + Packaging Tools Verpakkingsgereedschap + Fold Lines Vouwlijnen + Make Cut Line Snijlijn maken + Make Crease Line Rillijn maken + Make Partial Cut Line Halve snijlijn maken + Make Perforation Line Perforatielijn maken + Make Fold Line Vouwlijn maken + Role Swatches… Stalen van lijnsoorten… + Role Swatches Stalen van lijnsoorten + Role Lijnsoort + Cut Line Snijlijn + Crease Line Rillijn + Partial Cut Line Halve snijlijn + Perforation Line Perforatielijn + No objects are selected. Er zijn geen objecten geselecteerd. + Open a document to mark its fold lines. Open een document om de vouwlijnen te markeren. + Remove Fold Line Role Lijnsoort verwijderen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 77b1425e5f..832539f18b 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -9315,3 +9315,20 @@ breakText Glyphs Glify @msg {width} × {height} pixels is too large for JPEG (at most 65535 pixels a side): lower the resolution {width} × {height} pikseli to za dużo dla formatu JPEG (najwyżej 65535 pikseli na bok): zmniejsz rozdzielczość @msg {width} × {height} pixels is too large for Targa (at most 65535 pixels a side): lower the resolution {width} × {height} pikseli to za dużo dla formatu Targa (najwyżej 65535 pikseli na bok): zmniejsz rozdzielczość @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} pikseli to za dużo dla formatu PSD (najwyżej {MAX_SIDE} pikseli na bok): zmniejsz rozdzielczość + Packaging Tools Narzędzia do opakowań + Fold Lines Linie zgięcia + Make Cut Line Utwórz linię cięcia + Make Crease Line Utwórz linię bigowania + Make Partial Cut Line Utwórz linię nacięcia + Make Perforation Line Utwórz linię perforacji + Make Fold Line Utwórz linię zgięcia + Role Swatches… Próbki rodzajów linii… + Role Swatches Próbki rodzajów linii + Role Rodzaj linii + Cut Line Linia cięcia + Crease Line Linia bigowania + Partial Cut Line Linia nacięcia + Perforation Line Linia perforacji + No objects are selected. Nie zaznaczono żadnych obiektów. + Open a document to mark its fold lines. Otwórz dokument, aby oznaczyć jego linie zgięcia. + Remove Fold Line Role Usuń rodzaj linii diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index caed79af2a..fd8b3ac11c 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -9533,3 +9533,20 @@ swatch Yellow Green Verde-amarelado Nest Shapes… Aninhar formas… Nest Shapes Aninhar formas Roll Rolo + Packaging Tools Ferramentas de Embalagem + Fold Lines Linhas de Dobra + Make Cut Line Transformar em Linha de Corte + Make Crease Line Transformar em Linha de Vinco + Make Partial Cut Line Transformar em Linha de Meio-Corte + Make Perforation Line Transformar em Linha de Perfuração + Make Fold Line Transformar em Linha de Dobra + Role Swatches… Amostras dos Tipos de Linha… + Role Swatches Amostras dos Tipos de Linha + Role Tipo de Linha + Cut Line Linha de Corte + Crease Line Linha de Vinco + Partial Cut Line Linha de Meio-Corte + Perforation Line Linha de Perfuração + No objects are selected. Nenhum objeto selecionado. + Open a document to mark its fold lines. Abra um documento para marcar suas linhas de dobra. + Remove Fold Line Role Remover Tipo de Linha diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 206b209ee2..43320b5b86 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -7736,4 +7736,21 @@ shape Open Открытый @msg {path}: could not be read {path}: не удалось прочитать @msg {width} × {height} pixels is too large for JPEG (at most 65535 pixels a side): lower the resolution {width} × {height} пикселей — слишком большой размер для JPEG (не более 65535 пикселей по стороне): уменьшите разрешение @msg {width} × {height} pixels is too large for Targa (at most 65535 pixels a side): lower the resolution {width} × {height} пикселей — слишком большой размер для Targa (не более 65535 пикселей по стороне): уменьшите разрешение + Packaging Tools Инструменты упаковки + Fold Lines Линии сгиба + Make Cut Line Сделать линией реза + Make Crease Line Сделать линией биговки + Make Partial Cut Line Сделать линией надреза + Make Perforation Line Сделать линией перфорации + Make Fold Line Сделать линией сгиба + Role Swatches… Образцы типов линий… + Role Swatches Образцы типов линий + Role Тип линии + Cut Line Линия реза + Crease Line Линия биговки + Partial Cut Line Линия надреза + Perforation Line Линия перфорации + No objects are selected. Объекты не выделены. + Open a document to mark its fold lines. Откройте документ, чтобы отметить его линии сгиба. + Remove Fold Line Role Убрать тип линии @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/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 82e63d1667..8b024a8212 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -9122,4 +9122,21 @@ digits Hindi Hindi @msg {path}: could not be read {path}: kunde inte läsas @msg {width} × {height} pixels is too large for JPEG (at most 65535 pixels a side): lower the resolution {width} × {height} pixlar är för stort för JPEG (högst 65535 pixlar per sida): sänk upplösningen @msg {width} × {height} pixels is too large for Targa (at most 65535 pixels a side): lower the resolution {width} × {height} pixlar är för stort för Targa (högst 65535 pixlar per sida): sänk upplösningen + Packaging Tools Förpackningsverktyg + Fold Lines Falslinjer + Make Cut Line Gör till skärlinje + Make Crease Line Gör till biglinje + Make Partial Cut Line Gör till halvskärlinje + Make Perforation Line Gör till perforeringslinje + Make Fold Line Gör till falslinje + Role Swatches… Färgrutor för linjetyper… + Role Swatches Färgrutor för linjetyper + Role Linjetyp + Cut Line Skärlinje + Crease Line Biglinje + Partial Cut Line Halvskärlinje + Perforation Line Perforeringslinje + No objects are selected. Inga objekt är markerade. + Open a document to mark its fold lines. Öppna ett dokument för att markera dess falslinjer. + Remove Fold Line Role Ta bort linjetyp @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/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 237694bff5..4fb138652c 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -9417,3 +9417,20 @@ breakText Glyphs Glifler Nest Shapes… Şekilleri yerleştir… Nest Shapes Şekilleri yerleştir Roll Rulo + Packaging Tools Ambalaj Araçları + Fold Lines Katlama Çizgileri + Make Cut Line Kesim Çizgisi Yap + Make Crease Line Pilyaj Çizgisi Yap + Make Partial Cut Line Yarım Kesim Çizgisi Yap + Make Perforation Line Perforaj Çizgisi Yap + Make Fold Line Katlama Çizgisi Yap + Role Swatches… Çizgi Türü Renk Örnekleri… + Role Swatches Çizgi Türü Renk Örnekleri + Role Çizgi türü + Cut Line Kesim çizgisi + Crease Line Pilyaj çizgisi + Partial Cut Line Yarım kesim çizgisi + Perforation Line Perforaj çizgisi + No objects are selected. Hiçbir nesne seçili değil. + Open a document to mark its fold lines. Katlama çizgilerini işaretlemek için bir belgeyi açın. + Remove Fold Line Role Çizgi Türünü Kaldır diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index a74a03529d..e3ed8eb72b 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -9069,3 +9069,20 @@ breakText Glyphs Гліфи Nest Shapes… Розкладка фігур… Nest Shapes Розкладка фігур Roll Рулон + Packaging Tools Інструменти пакування + Fold Lines Лінії згину + Make Cut Line Зробити лінією різу + Make Crease Line Зробити лінією біговки + Make Partial Cut Line Зробити лінією надрізу + Make Perforation Line Зробити лінією перфорації + Make Fold Line Зробити лінією згину + Role Swatches… Зразки типів ліній… + Role Swatches Зразки типів ліній + Role Тип лінії + Cut Line Лінія різу + Crease Line Лінія біговки + Partial Cut Line Лінія надрізу + Perforation Line Лінія перфорації + No objects are selected. Об’єкти не виділено. + Open a document to mark its fold lines. Відкрийте документ, щоб позначити його лінії згину. + Remove Fold Line Role Прибрати тип лінії diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 16c613874c..7ff754f74a 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -7143,6 +7143,23 @@ breakText Glyphs Glyph Nest Shapes… Xếp hình tiết kiệm vật liệu… Nest Shapes Xếp hình tiết kiệm vật liệu Roll Cuộn + Packaging Tools Công cụ bao bì + Fold Lines Đường gấp + Make Cut Line Đặt làm đường cắt + Make Crease Line Đặt làm đường cấn + Make Partial Cut Line Đặt làm đường cắt một phần + Make Perforation Line Đặt làm đường đục lỗ + Make Fold Line Đặt làm đường gấp + Role Swatches… Mẫu màu của các loại đường… + Role Swatches Mẫu màu của các loại đường + Role Loại đường + Cut Line Đường cắt + Crease Line Đường cấn + Partial Cut Line Đường cắt một phần + Perforation Line Đường đục lỗ + No objects are selected. Không có đối tượng nào được chọn. + Open a document to mark its fold lines. Mở tài liệu để đánh dấu các đường gấp của nó. + Remove Fold Line Role Bỏ loại đường # 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 diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index b83bee650f..c4a64884a1 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -9300,4 +9300,21 @@ breakText Glyphs 字形 @msg {path}: could not be read {path}:无法读取 @msg {width} × {height} pixels is too large for JPEG (at most 65535 pixels a side): lower the resolution {width} × {height} 像素对 JPEG 而言过大 (每边最多 65535 像素):请降低分辨率 @msg {width} × {height} pixels is too large for Targa (at most 65535 pixels a side): lower the resolution {width} × {height} 像素对 Targa 而言过大 (每边最多 65535 像素):请降低分辨率 + Packaging Tools 包装工具 + Fold Lines 折线 + Make Cut Line 设为切割线 + Make Crease Line 设为压痕线 + Make Partial Cut Line 设为半切线 + Make Perforation Line 设为打孔线 + Make Fold Line 设为折线 + Role Swatches… 线条类型色板… + Role Swatches 线条类型色板 + Role 线条类型 + Cut Line 切割线 + Crease Line 压痕线 + Partial Cut Line 半切线 + Perforation Line 打孔线 + No objects are selected. 未选择任何对象。 + Open a document to mark its fold lines. 打开文档以标记其折线。 + Remove Fold Line Role 移除线条类型 @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 4637ecb811..991e6597d1 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -9109,4 +9109,21 @@ breakText Glyphs 字符 @msg {v} is not an asset id {v} 不是資產 ID @msg {what} can't be intertwined {what} 無法交織 @msg {what} doesn't fit the paper with its bleed and marks {what} 連同出血和標記無法容納於紙張 + Packaging Tools 包裝工具 + Fold Lines 摺線 + Make Cut Line 設為切割線 + Make Crease Line 設為壓痕線 + Make Partial Cut Line 設為半切線 + Make Perforation Line 設為打孔線 + Make Fold Line 設為摺線 + Role Swatches… 線條類型色票… + Role Swatches 線條類型色票 + Role 線條類型 + Cut Line 切割線 + Crease Line 壓痕線 + Partial Cut Line 半切線 + Perforation Line 打孔線 + No objects are selected. 未選取任何物件。 + Open a document to mark its fold lines. 開啟文件以標記其摺線。 + Remove Fold Line Role 移除線條類型 @msg {what} would print on more than {MAX_TILES} tiles: scale it down {what} 會列印在超過 {MAX_TILES} 個拼貼上:請縮小 diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index bbe91da5a6..72c794a12a 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -190,6 +190,7 @@ pub fn show_icon_panel(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) { learn::ID => learn::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::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), @@ -245,6 +246,7 @@ pub fn panel_menu_items(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) -> bool variables::ID => variables::menu(app, ui), script_console::ID => script_console::menu(app, ui), "actions" => actions::menu(app, ui), + crate::addons::packaging::ID => crate::addons::packaging::panel_menu(app, ui), id if library_panel::parse(id).is_some() => library_panel::menu(app, ui, id), _ => return false, } diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index b28e4034a7..452da63188 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -227,6 +227,7 @@ pub const ICON_PANELS: &[(&str, &str, &str)] = &[ (crate::panels::learn::ID, "Learn", "graduation-cap"), (crate::addons::cleanup::ID, "Artwork Cleanup", "sparkles"), (crate::addons::color::ID, "Color Effects", "sun"), + (crate::addons::packaging::ID, "Fold Lines", "scissors"), (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"), diff --git a/docs/mcp.md b/docs/mcp.md index 99b0bfef38..8c43d66974 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -11922,6 +11922,58 @@ there is no step. → `{symbols: [name…], ids: [instance id…], skipped: [{la {"name":"run_command","arguments":{"command":"addon.document.symbolsFromLayers","params":{"replace":true}}} ``` +## 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` and `addon.packaging.setRoleSwatch`. In the desktop app, Object › +Plug-ins › Packaging Tools › Fold Lines opens the Fold Lines panel, and Make Cut Line, Make Crease Line, Make Partial Cut +Line and Make Perforation Line run `addon.packaging.setRole` on the selection. + +### Fold line roles + +A fold line has one of four roles: Cut (`cut`), Crease (`crease`), Partial Cut (`partialCut`) and Perforation +(`perforation`). A path, compound path or live shape has a role when its top stroke is painted with the role's swatch, at +any tint. Each document has a role table that names the swatch of each role, stored in the document under +`packagingRoles` as `{"cut": "Cut", "crease": "Crease", "partialCut": "Partial Cut", "perforation": "Perforation"}`. A +role the table leaves out, or names with something other than a string, uses the swatch named after the role. When +`swatch.edit` renames a role's swatch, the table names the swatch by its new name and the role stays with it; another +role whose swatch did not exist yet and had that name moves to a new name ("Crease 2"). When `swatch.edit` turns Global +off for a role's swatch, which unlinks its strokes, the role moves to a new name, and the next `addon.packaging.setRole` +makes that swatch. When `swatch.merge` merges a role's swatch into a global swatch that carries no role, the kept swatch +takes the role. Native files keep the table and the strokes. PDF prints a role line on the separation of its swatch when +the swatch is a spot color, as the default role swatches are; a role carried by a global process color is written as an +ordinary color with no separation of its own. SVG, DXF and HP-GL keep the stroke's color, so the default role swatches +come out as four colors, and as four pens in HP-GL without a pen table. + +`addon.packaging.setRole` (`{role: cut|crease|partialCut|perforation|none, ids?, overprint?: true}`) gives the role to +each path, compound path and live shape among the objects (the selection by default), through groups and clip groups. +Objects that are locked or hidden, in a locked or hidden group or layer, or on a locked artboard are left out and +counted as skipped, also when `ids` names them. The top stroke is painted with the role's swatch at 100% and shown if +it was hidden, a path without a stroke gets a 1 pt stroke, and the stroke overprints unless `overprint` is false. When +the document lacks the role's swatch, the command makes it as a global spot swatch in the document's color mode: Cut 100% +magenta, Crease 100% cyan, Partial Cut 100% yellow and Perforation 50% magenta and 50% cyan (VectorCraft's own defaults). +When a color group, or a swatch that can't carry a role such as a process color that is not global, has the swatch's +name, the swatch is named "Cut 2" (and so on) and the role table names it. `none` takes the role away: the stroke keeps +the color it shows, no longer linked to the swatch, and stops overprinting. Text, images, symbol instances and other +objects are skipped and counted. The command fails with an unknown role and when the objects hold no path it can change. One undo +step, none when nothing changes. Result: `{ids, changed, skipped}`. + +`addon.packaging.roles` (`{ids?}`) returns `{roles: [{role, name, swatch, exists, count}], scope, selected}`: each role's +swatch, whether the document has it, and how many of the objects have the role. It counts the selection, or every object +of the document while nothing is selected and `ids` is left out (`scope` says which). Locked and hidden objects are +counted in every scope, and an object is counted once when both it and its group are given. The Fold Lines panel shows +these counts; clicking a role gives the selected paths that role. With nothing selected the panel says so. + +`addon.packaging.setRoleSwatch` (`{role, swatch}`) makes another global or spot color swatch carry the role. Objects +stroked with the old swatch keep their color and no longer have the role. It fails with a missing swatch, a gradient or +pattern swatch, a process color that is not global, a tint swatch, `[None]`, `[Registration]` and a swatch another role +has. One undo step, none when the role already has that swatch. Result: `{role, swatch, changed}`. The Fold Lines +panel's menu opens it as Role Swatches…. + +```json +{"name":"run_command","arguments":{"command":"addon.packaging.setRole","params":{"role":"crease"}}} +``` + ## Image Tools add-on Image Tools is a built-in add-on for placed images: its commands are `addon.image.removeBackground`, From f35e9d091d8bc3c1e7adb17844d281f9dab79eac Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 18:27:30 -0800 Subject: [PATCH 02/31] Effects: pixel filter directions turn and reflect with a Transform effect after them A Transform effect listed after Underpainting, Rough Pastels, Conte Crayon, Bas Relief, Plaster or Texturizer now turns and reflects their light direction, and after Sprayed Strokes or Graphic Pen their stroke direction. Each is set to the nearest choice of its menu, the one clockwise of it at a tie. Color Halftone's four screen angles turn and reflect with the art. Stacked Transform effects, and an object's Transform effect over a fill's own, round the direction once. A zero scale leaves the direction as it is. The canvas, export and Expand Appearance use the same values. Filters with fixed stroke or pattern axes keep them. --- crates/effects/src/catalog.rs | 2 +- crates/effects/src/pixel.rs | 115 ++++++++++++- crates/effects/src/pixel/brushstrokes.rs | 4 +- crates/effects/src/pixel/texture.rs | 2 +- crates/effects/src/raster.rs | 27 ++- crates/effects/src/tests/rasterfollow.rs | 204 ++++++++++++++++++++++- crates/render/src/fx/tests.rs | 32 ++++ docs/target-app-parity.md | 2 +- 8 files changed, 371 insertions(+), 17 deletions(-) diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index 67677656e6..d83b149377 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -267,7 +267,7 @@ pub fn effect_catalog() -> Vec { "distort.transform", "Transform…", DT, - "{scaleH: % (100), scaleV: % (100), moveH: pt (0; right = +), moveV: pt (0; down = +), rotate: deg (0; counter-clockwise; when the effect turns, reflects or scales the object unevenly, a gradient fitted to the object is fixed to its fit and turns with the object and with each copy), copies: 0..1000 (0; each copy transforms the last again and is painted below it, the object on top; a group's copies each hold all its members, and a group with a member that carries a geometry, Pathfinder or 3D effect copies each member in its place; placed gradients transform with the object and with each copy), reflectX: bool (false; flips left to right), reflectY: bool (false; flips top to bottom), reference: 0..8 (4; the point of the bounds' 9-point grid it scales, rotates and reflects about: 0 top left, 4 centre, 8 bottom right), random: bool (false; each scale goes a random share of the way from 100 % to its value, each move and the angle a random share of theirs, differently for each object and the same on every redraw), objects: bool (true; Transform Objects: off, the geometry stays where it is and makes no copies, and only the two options below apply, once; on, without copies or random, the raster effects listed before this effect (Rasterize and SVG filters excepted) transform with the art whatever strokes says: their sizes scale by the mean scale and a Drop Shadow's offset turns, reflects and scales, while the angles and light directions of pixel filters stay as they are; so do the raster effects of the object's fills and strokes and, on a group, those of its members, of their fills and strokes and of their linked opacity masks' art, after their own Transform effects, including those that a member's own Transform effect with copies or random holds back), patterns: bool (false; Transform Patterns: pattern fills and strokes transform along; with copies the original keeps its pattern and copy k takes the transformation k times), strokes: bool (false; Scale Strokes & Effects: stroke weights and dashes, and the distances of the effects on the fills and strokes, scale by the mean scale √|scaleH·scaleV|, copy k by its k-th power; raster effects that transform with the art are not scaled again; on a fill or stroke, the effects listed after this effect in that fill's or stroke's own list keep their distances and apply to the transformed art, and with objects off so do the effects before it)}", + "{scaleH: % (100), scaleV: % (100), moveH: pt (0; right = +), moveV: pt (0; down = +), rotate: deg (0; counter-clockwise; when the effect turns, reflects or scales the object unevenly, a gradient fitted to the object is fixed to its fit and turns with the object and with each copy), copies: 0..1000 (0; each copy transforms the last again and is painted below it, the object on top; a group's copies each hold all its members, and a group with a member that carries a geometry, Pathfinder or 3D effect copies each member in its place; placed gradients transform with the object and with each copy), reflectX: bool (false; flips left to right), reflectY: bool (false; flips top to bottom), reference: 0..8 (4; the point of the bounds' 9-point grid it scales, rotates and reflects about: 0 top left, 4 centre, 8 bottom right), random: bool (false; each scale goes a random share of the way from 100 % to its value, each move and the angle a random share of theirs, differently for each object and the same on every redraw), objects: bool (true; Transform Objects: off, the geometry stays where it is and makes no copies, and only the two options below apply, once; on, without copies or random, the raster effects listed before this effect (Rasterize and SVG filters excepted) transform with the art whatever strokes says: their sizes scale by the mean scale, a Drop Shadow's offset turns, reflects and scales, a pixel filter's lightDirection or strokeDirection turns and reflects to the nearest choice (at a tie, the one clockwise of it; VectorCraft's own rule), and Color Halftone's channel angles turn and reflect with the art (0 to 360); so do the raster effects of the object's fills and strokes and, on a group, those of its members, of their fills and strokes and of their linked opacity masks' art, after their own Transform effects, including those that a member's own Transform effect with copies or random holds back), patterns: bool (false; Transform Patterns: pattern fills and strokes transform along; with copies the original keeps its pattern and copy k takes the transformation k times), strokes: bool (false; Scale Strokes & Effects: stroke weights and dashes, and the distances of the effects on the fills and strokes, scale by the mean scale √|scaleH·scaleV|, copy k by its k-th power; raster effects that transform with the art are not scaled again; on a fill or stroke, the effects listed after this effect in that fill's or stroke's own list keep their distances and apply to the transformed art, and with objects off so do the effects before it)}", json!({"scaleH": 100.0, "scaleV": 100.0, "moveH": 0.0, "moveV": 0.0, "rotate": 0.0, "copies": 0, "reflectX": false, "reflectY": false, "reference": 4, "random": false, "objects": true, "patterns": false, "strokes": false}), ), g( diff --git a/crates/effects/src/pixel.rs b/crates/effects/src/pixel.rs index 0c159f8485..264798bceb 100644 --- a/crates/effects/src/pixel.rs +++ b/crates/effects/src/pixel.rs @@ -29,6 +29,8 @@ mod sketch_ink; mod texture; mod video; +use std::f64::consts::{PI, TAU}; + use serde_json::Value; use vectorcraft_geom::{Affine, Point, Rect, Vec2}; @@ -331,6 +333,9 @@ pub struct PixelSpace { pub extent: f64, } +/// Color Halftone's screen angle parameters with their defaults (degrees). +const SCREEN_ANGLES: [(&str, f64); 4] = [("channel1", 108.0), ("channel2", 162.0), ("channel3", 90.0), ("channel4", 45.0)]; + /// Effect `id`'s parameters `p` (defaults merged in) as a [`PixelFx`]; `None` for other effects. pub(crate) fn parse(id: &str, p: &Value) -> Option { let quality = |levels: [(&str, u32); 3], default: u32| { @@ -564,8 +569,7 @@ pub(crate) fn parse(id: &str, p: &Value) -> Option { }, "pixelate.colorHalftone" => PixelFx::ColorHalftone { max_radius: num(p, "maxRadius", 8.0).clamp(4.0, 127.0), - angles: [("channel1", 108.0), ("channel2", 162.0), ("channel3", 90.0), ("channel4", 45.0)] - .map(|(k, d)| num(p, k, d).clamp(-360.0, 360.0)), + angles: SCREEN_ANGLES.map(|(k, d)| num(p, k, d).clamp(-360.0, 360.0)), }, "pixelate.crystallize" => PixelFx::Crystallize { cell: num(p, "cellSize", 10.0).clamp(3.0, 300.0) }, "pixelate.mezzotint" => PixelFx::Mezzotint { kind: Mezzotint::parse(text(p, "type", "fineDots")) }, @@ -854,6 +858,113 @@ fn pick(table: &[(&str, &str)], all: &[T], value: &str, default: T) -> table.iter().zip(all).find(|((_, v), _)| v.eq_ignore_ascii_case(value)).map_or(default, |(_, t)| t.clone()) } +/// The shortest that a direction's unit vector may become under a Transform effect and still give +/// a direction ([`turned_directions`]). +const MIN_TURNED: f64 = 1e-9; + +/// How close (radians) two directions' angles to a turned direction must be to count as equally +/// near ([`nearest`]). +const TIE: f64 = 1e-9; + +/// The parameters of pixel filter `id` (params `p`, defaults not merged in) that set a direction +/// on the page, as `a` turns them: `a` is the linear part of a Transform effect listed after the +/// filter, which turns, reflects and scales what the filter paints. A light direction or stroke +/// direction becomes the one nearest to where `a` takes it, the one clockwise of it when two are +/// equally near ([`snapped`]); `later` is the map the filter still goes through when it is drawn, +/// after `a`. Color Halftone's screen angles (degrees counterclockwise from the page's horizontal) +/// turn with `a`, from 0 up to 360. A direction that `a` takes to no direction (a zero scale) stays +/// as it is. Empty for filters with no such parameter. +pub(crate) fn turned_directions(id: &str, p: &Value, a: Affine, later: Affine) -> Vec<(&'static str, Value)> { + enum Kind { + Light(&'static str), + Stroke, + Screens, + } + let kind = match id { + "sketch.basRelief" => Kind::Light("bottom"), + "artistic.underpainting" | "artistic.roughPastels" | "sketch.conteCrayon" | "sketch.plaster" | "texture.texturizer" => Kind::Light("top"), + "brushStrokes.sprayedStrokes" | "sketch.graphicPen" => Kind::Stroke, + "pixelate.colorHalftone" => Kind::Screens, + _ => return Vec::new(), + }; + let p = crate::merged_params(id, p); + match kind { + Kind::Light(default) => { + let light = Light::parse(text(&p, "lightDirection", default)); + snapped(&Light::ALL, Light::toward, light, a, later, false) + .and_then(|t| name_of(&LIGHT_DIRECTIONS, &Light::ALL, t)) + .map(|name| vec![("lightDirection", Value::from(name))]) + .unwrap_or_default() + } + Kind::Stroke => { + let direction = StrokeDirection::parse(text(&p, "strokeDirection", "rightDiagonal")); + snapped(&StrokeDirection::ALL, StrokeDirection::along, direction, a, later, true) + .and_then(|t| name_of(&STROKE_DIRECTIONS, &StrokeDirection::ALL, t)) + .map(|name| vec![("strokeDirection", Value::from(name))]) + .unwrap_or_default() + } + // A screen at θ° runs along (cos θ, −sin θ) on the page (y down). + Kind::Screens => SCREEN_ANGLES + .iter() + .filter_map(|&(key, default)| { + let t = num(&p, key, default).clamp(-360.0, 360.0).to_radians(); + let v = mapped(a, Vec2::new(t.cos(), -t.sin()))?; + let degrees = ((-v.y).atan2(v.x).to_degrees() * 1e6).round() / 1e6; + Some((key, Value::from(degrees.rem_euclid(360.0) + 0.0))) + }) + .collect(), + } +} + +/// Where the linear part of `a` takes direction `v`; `None` when it takes it to no direction. +fn mapped(a: Affine, v: Vec2) -> Option { + let w = (a * v.to_point()) - (a * Point::ORIGIN); + (w.is_finite() && w.hypot() > MIN_TURNED).then_some(w) +} + +/// The entry of `all` to store for `from` (directions `dir`) once `a` turns it: the one nearest to +/// where `a` takes it ([`nearest`]). When the stored entry is still to be mapped by `later` and +/// rounded again as it is drawn, it is the entry nearest to that among those that `later` takes to +/// the entry nearest to where `later` after `a` takes `from`, so that the drawn direction is +/// rounded once. `None` when `a` takes `from` to no direction. +fn snapped(all: &[T], dir: fn(T) -> Vec2, from: T, a: Affine, later: Affine, axis: bool) -> Option { + let v = mapped(a, dir(from))?; + let turned = nearest(all, dir, v, axis)?; + if later == Affine::IDENTITY { + return Some(turned); + } + let Some(target) = mapped(later * a, dir(from)).and_then(|w| nearest(all, dir, w, axis)) else { return Some(turned) }; + let fits: Vec = all.iter().copied().filter(|&t| mapped(later, dir(t)).and_then(|w| nearest(all, dir, w, axis)) == Some(target)).collect(); + nearest(&fits, dir, v, axis).or(Some(turned)) +} + +/// The entry of `all` whose direction (`dir`, page axes with y down) is nearest to `v` by angle, +/// a direction and its opposite counting as the same with `axis`. Of two equally near, the one +/// clockwise of `v` on the page. +fn nearest(all: &[T], dir: impl Fn(T) -> Vec2, v: Vec2, axis: bool) -> Option { + let period = if axis { PI } else { TAU }; + let at = v.atan2(); + let mut best: Option<(T, f64)> = None; + for &t in all { + // How far clockwise of `v` the entry lies, within half a period either way. + let d = (dir(t).atan2() - at).rem_euclid(period); + let d = if d > period / 2.0 { d - period } else { d }; + let better = match best { + None => true, + Some((_, b)) => d.abs() < b.abs() - TIE || (d.abs() <= b.abs() + TIE && d > b), + }; + if better { + best = Some((t, d)); + } + } + best.map(|(t, _)| t) +} + +/// The value in `table` of entry `t` of `all` (the same order). +fn name_of(table: &[(&'static str, &'static str)], all: &[T], t: T) -> Option<&'static str> { + table.iter().zip(all).find(|(_, u)| **u == t).map(|((_, v), _)| *v) +} + /// `data` as `w` × `h` RGBA pixels, `None` when it isn't that size (or is empty). fn pixels(data: &mut [u8], w: usize, h: usize) -> Option<&mut [[u8; 4]]> { let (px, rest) = data.as_chunks_mut::<4>(); diff --git a/crates/effects/src/pixel/brushstrokes.rs b/crates/effects/src/pixel/brushstrokes.rs index 100d4e2497..ca5c0a9b48 100644 --- a/crates/effects/src/pixel/brushstrokes.rs +++ b/crates/effects/src/pixel/brushstrokes.rs @@ -43,7 +43,7 @@ pub enum StrokeDirection { } impl StrokeDirection { - const ALL: [StrokeDirection; 4] = + pub(super) const ALL: [StrokeDirection; 4] = [StrokeDirection::RightDiagonal, StrokeDirection::Horizontal, StrokeDirection::LeftDiagonal, StrokeDirection::Vertical]; /// The direction of `value` (a [`STROKE_DIRECTIONS`] value, any case); Right Diagonal @@ -53,7 +53,7 @@ impl StrokeDirection { } /// The unit vector along the strokes (document axes, y down). - fn along(self) -> Vec2 { + pub(super) fn along(self) -> Vec2 { match self { StrokeDirection::RightDiagonal => RIGHT, StrokeDirection::Horizontal => Vec2::new(1.0, 0.0), diff --git a/crates/effects/src/pixel/texture.rs b/crates/effects/src/pixel/texture.rs index a408454530..e041256dc0 100644 --- a/crates/effects/src/pixel/texture.rs +++ b/crates/effects/src/pixel/texture.rs @@ -137,7 +137,7 @@ pub enum Light { } impl Light { - const ALL: [Light; 8] = + pub(super) const ALL: [Light; 8] = [Light::Bottom, Light::BottomLeft, Light::Left, Light::TopLeft, Light::Top, Light::TopRight, Light::Right, Light::BottomRight]; /// The direction of `value` (a [`LIGHT_DIRECTIONS`] value, any case); Top otherwise. diff --git a/crates/effects/src/raster.rs b/crates/effects/src/raster.rs index b59d61beb2..9dcff61f0d 100644 --- a/crates/effects/src/raster.rs +++ b/crates/effects/src/raster.rs @@ -452,7 +452,7 @@ pub(crate) fn followed(effects: &[Effect]) -> Cow<'_, [Effect]> { let Some(a) = after.filter(|a| *a != Affine::IDENTITY && follows(&e.id)) else { continue }; let list = out.get_or_insert_with(|| effects.to_vec()); if let Some(e) = list.get_mut(i) { - follow_transform(e, a); + follow_transform(e, a, Affine::IDENTITY); } } out.map_or(Cow::Borrowed(effects), Cow::Owned) @@ -472,7 +472,7 @@ pub(crate) fn follow_one(effects: &mut [Effect], t: &Effect) -> bool { let Some(a) = transform_step(t).filter(|a| *a != Affine::IDENTITY) else { return false }; let mut changed = false; for e in effects.iter_mut().filter(|e| follows(&e.id)) { - follow_transform(e, a); + follow_transform(e, a, Affine::IDENTITY); changed = true; } changed @@ -519,7 +519,7 @@ pub(crate) fn follow_contents(effects: &mut [Effect], a: Affine, outer: Affine) let det = b.determinant(); let c = if b == Affine::IDENTITY || !(det.is_finite() && det.abs() > 1e-12) { a } else { b.inverse() * a * b }; if c.is_finite() { - follow_transform(e, c); + follow_transform(e, c, b); changed = true; } } @@ -615,9 +615,11 @@ pub(crate) fn follows(id: &str) -> bool { /// Make raster effect `e` follow `a`, the linear part of a Transform effect listed after it, as /// that effect transforms what `e` paints: its distances and raster sizes scale by `a`'s mean -/// scale ([`crate::scale_effect`]), and a Drop Shadow's offset turns, reflects and scales with -/// `a`. Effects that [`follows`] leaves out stay as they are. -fn follow_transform(e: &mut Effect, a: Affine) { +/// scale ([`crate::scale_effect`]), a Drop Shadow's offset turns, reflects and scales with `a`, +/// and a pixel filter's light direction, stroke direction or screen angles turn and reflect with +/// it ([`pixel::turned_directions`]; `later` is the map `e` still goes through when it is drawn). +/// Effects that [`follows`] leaves out stay as they are. +fn follow_transform(e: &mut Effect, a: Affine, later: Affine) { if !follows(&e.id) { return; } @@ -625,15 +627,22 @@ fn follow_transform(e: &mut Effect, a: Affine) { let p = merged_params(&e.id, &e.params); a * Point::new(num(&p, "x", 7.0), num(&p, "y", 7.0)) }); + let turned = pixel::turned_directions(&e.id, &e.params, a, later); if let Some(k) = vectorcraft_doc::Scaling::factor(a) { crate::scale_effect(e, k); } - if let Some(o) = offset.filter(|o| o.x.is_finite() && o.y.is_finite()) { + let mut set = |key: &str, value: Value| { if !e.params.is_object() { e.params = Value::Object(Map::new()); } - e.params["x"] = json!(o.x); - e.params["y"] = json!(o.y); + e.params[key] = value; + }; + if let Some(o) = offset.filter(|o| o.x.is_finite() && o.y.is_finite()) { + set("x", json!(o.x)); + set("y", json!(o.y)); + } + for (key, value) in turned { + set(key, value); } } diff --git a/crates/effects/src/tests/rasterfollow.rs b/crates/effects/src/tests/rasterfollow.rs index 1ebcab785a..ae407fd438 100644 --- a/crates/effects/src/tests/rasterfollow.rs +++ b/crates/effects/src/tests/rasterfollow.rs @@ -7,7 +7,8 @@ use vectorcraft_doc::{Appearance, Document, Effect, Node, NodeId}; use vectorcraft_geom::{Affine, Anchor, PathData, Point, Rect, SubPath, shapes}; use crate::geometry::{Budget, MAX_EFFECT_LINES, apply_geometry_carrying_within}; -use crate::{Carry, GeomContext, RasterFx, apply_geometry_carrying, bake_document, expand_outlined, raster_effects}; +use crate::pixel::{Light, StrokeDirection}; +use crate::{Carry, GeomContext, PixelFx, RasterFx, apply_geometry_carrying, bake_document, expand_outlined, raster_effects}; fn fx(id: &str, params: Value) -> Effect { Effect { id: id.into(), params, visible: true } @@ -378,6 +379,207 @@ fn pixel_filter_sizes_scale_with_the_transform_after_them() { assert!(matches!(drawn.get(1), Some(RasterFx::Pixel(crate::PixelFx::PaintDaubs { size, .. })) if (size - 20.0).abs() < 1e-9), "{drawn:?}"); } +/// The light direction of the first pixel filter `effects` draw, if it has one. +fn drawn_light(effects: &[Effect]) -> Option { + raster_effects(effects).into_iter().find_map(|r| match r { + RasterFx::Pixel( + PixelFx::Underpainting { light, .. } + | PixelFx::RoughPastels { light, .. } + | PixelFx::ConteCrayon { light, .. } + | PixelFx::BasRelief { light, .. } + | PixelFx::Plaster { light, .. } + | PixelFx::Texturizer { light, .. }, + ) => Some(light), + _ => None, + }) +} + +/// The stroke direction of the first pixel filter `effects` draw, if it has one. +fn drawn_strokes(effects: &[Effect]) -> Option { + raster_effects(effects).into_iter().find_map(|r| match r { + RasterFx::Pixel(PixelFx::SprayedStrokes { direction, .. } | PixelFx::GraphicPen { direction, .. }) => Some(direction), + _ => None, + }) +} + +/// The screen angles of the first Color Halftone `effects` draw. +fn drawn_screens(effects: &[Effect]) -> [f64; 4] { + match raster_effects(effects).into_iter().next() { + Some(RasterFx::Pixel(PixelFx::ColorHalftone { angles, .. })) => angles, + other => panic!("expected a Color Halftone, got {other:?}"), + } +} + +/// A Bas Relief lit from `light`, then a Transform effect with `params`: the light it draws with. +fn relief_then(light: &str, params: Value) -> Option { + drawn_light(&[fx("sketch.basRelief", json!({ "lightDirection": light })), transform(params)]) +} + +/// A light direction before a Transform effect turns and reflects with the art (y down on the +/// page), to the nearest of the eight directions, the clockwise one at a tie. +#[test] +fn bas_relief_light_follows_rotation_and_reflection() { + assert_eq!(relief_then("top", json!({"rotate": 90})), Some(Light::Left)); + assert_eq!(relief_then("top", json!({"reflectY": true})), Some(Light::Bottom)); + assert_eq!(relief_then("top", json!({"reflectX": true})), Some(Light::Top)); + assert_eq!(relief_then("left", json!({"reflectX": true})), Some(Light::Right)); + // 22.5° clockwise lies halfway between Top and Top Right; 22.5° counterclockwise halfway + // between Top and Top Left. + assert_eq!(relief_then("top", json!({"rotate": -22.5})), Some(Light::TopRight)); + assert_eq!(relief_then("top", json!({"rotate": 22.5})), Some(Light::Top)); + assert_eq!(relief_then("top", json!({"rotate": 30})), Some(Light::TopLeft)); + // A turn of 90° counterclockwise, from each direction. + for (from, to) in [ + ("bottom", Light::Right), + ("bottomLeft", Light::BottomRight), + ("left", Light::Bottom), + ("topLeft", Light::BottomLeft), + ("top", Light::Left), + ("topRight", Light::TopLeft), + ("right", Light::Top), + ("bottomRight", Light::TopRight), + ] { + assert_eq!(relief_then(from, json!({"rotate": 90})), Some(to), "{from}"); + } + // Every filter with a light direction, and Bas Relief's default light (Bottom). + for id in ["artistic.underpainting", "artistic.roughPastels", "sketch.conteCrayon", "sketch.basRelief", "sketch.plaster", "texture.texturizer"] { + let effects = [fx(id, json!({"lightDirection": "top"})), transform(json!({"rotate": 90}))]; + assert_eq!(drawn_light(&effects), Some(Light::Left), "{id}"); + } + assert_eq!(drawn_light(&[fx("sketch.basRelief", json!({})), transform(json!({"rotate": 90}))]), Some(Light::Right)); + // The Transform effects after the filter turn it together, with one rounding at the end. + let twice = [fx("sketch.basRelief", json!({"lightDirection": "top"})), transform(json!({"rotate": -22.5})), transform(json!({"rotate": -22.5}))]; + assert_eq!(drawn_light(&twice), Some(Light::TopRight)); +} + +/// A stroke direction before a Transform effect turns and reflects with the art, to the nearest +/// of the four, a stroke and its reverse being the same, the clockwise one at a tie. +#[test] +fn stroke_axis_follows_transform() { + let strokes = |id: &str, way: Option<&str>, params: Value| { + let p = way.map_or(json!({}), |w| json!({ "strokeDirection": w })); + drawn_strokes(&[fx(id, p), transform(params)]) + }; + let sprayed = "brushStrokes.sprayedStrokes"; + let pen = "sketch.graphicPen"; + assert_eq!(strokes(sprayed, Some("horizontal"), json!({"rotate": 90})), Some(StrokeDirection::Vertical)); + assert_eq!(strokes(sprayed, Some("vertical"), json!({"rotate": 90})), Some(StrokeDirection::Horizontal)); + assert_eq!(strokes(pen, Some("rightDiagonal"), json!({"rotate": 90})), Some(StrokeDirection::LeftDiagonal)); + assert_eq!(strokes(pen, Some("rightDiagonal"), json!({"reflectX": true})), Some(StrokeDirection::LeftDiagonal)); + assert_eq!(strokes(pen, Some("leftDiagonal"), json!({"reflectY": true})), Some(StrokeDirection::RightDiagonal)); + assert_eq!(strokes(pen, None, json!({"rotate": 90})), Some(StrokeDirection::LeftDiagonal)); + assert_eq!(strokes(sprayed, Some("horizontal"), json!({"rotate": -22.5})), Some(StrokeDirection::LeftDiagonal)); + assert_eq!(strokes(sprayed, Some("horizontal"), json!({"rotate": 22.5})), Some(StrokeDirection::Horizontal)); + assert_eq!(strokes(sprayed, Some("horizontal"), json!({"rotate": -44})), Some(StrokeDirection::LeftDiagonal)); + assert_eq!(strokes(sprayed, Some("horizontal"), json!({"rotate": 180})), Some(StrokeDirection::Horizontal)); +} + +fn near4(a: [f64; 4], b: [f64; 4]) -> bool { + a.iter().zip(b).all(|(p, q)| (p - q).abs() < 1e-6) +} + +/// Color Halftone's screen angles before a Transform effect turn and reflect with the art. +#[test] +fn halftone_channels_follow_rotation_and_reflection() { + let screens = |p: Value, transforms: &[Value]| { + let mut effects = vec![fx("pixelate.colorHalftone", p)]; + effects.extend(transforms.iter().cloned().map(transform)); + drawn_screens(&effects) + }; + let defaults = screens(json!({}), &[json!({"rotate": 90})]); + assert!(near4(defaults, [198.0, 252.0, 180.0, 135.0]), "{defaults:?}"); + let reflected = screens(json!({"channel1": 45, "channel2": 30, "channel3": 0, "channel4": 270}), &[json!({"reflectX": true})]); + assert!(near4(reflected, [135.0, 150.0, 180.0, 270.0]), "{reflected:?}"); + let flipped = screens(json!({"channel1": 45, "channel2": 30, "channel3": 0, "channel4": 270}), &[json!({"reflectY": true})]); + assert!(near4(flipped, [315.0, 330.0, 0.0, 90.0]), "{flipped:?}"); + // One Transform effect reflects, then turns; two apply in the order they are listed. + let p = json!({"channel1": 10.5, "channel2": -30, "channel3": 0, "channel4": 359.25}); + let one = screens(p.clone(), &[json!({"rotate": 30, "reflectX": true})]); + assert!(near4(one, [199.5, 240.0, 210.0, 210.75]), "{one:?}"); + let two = screens(p, &[json!({"rotate": 30}), json!({"reflectX": true})]); + assert!(near4(two, [139.5, 180.0, 150.0, 150.75]), "{two:?}"); +} + +/// Only the visible Transform effects listed after a filter that move the art once turn its +/// direction; a hidden filter turns too, and a zero scale leaves it as it is. +#[test] +fn only_earlier_visible_single_map_effects_follow() { + let relief = fx("sketch.basRelief", json!({"lightDirection": "top"})); + assert_eq!(drawn_light(&[transform(json!({"rotate": 90})), relief.clone()]), Some(Light::Top)); + for params in [ + json!({"rotate": 90, "objects": false}), + json!({"rotate": 90, "copies": 1}), + json!({"rotate": 90, "random": true}), + json!({"scaleH": 0, "scaleV": 0}), + ] { + assert_eq!(drawn_light(&[relief.clone(), transform(params.clone())]), Some(Light::Top), "{params}"); + } + let mut hidden = transform(json!({"rotate": 90})); + hidden.visible = false; + assert_eq!(drawn_light(&[relief.clone(), hidden]), Some(Light::Top)); + let zero = [fx("pixelate.colorHalftone", json!({"channel1": 20})), transform(json!({"scaleH": 0, "scaleV": 0}))]; + assert!(near4(drawn_screens(&zero), [20.0, 162.0, 90.0, 45.0]), "{:?}", drawn_screens(&zero)); + // A hidden filter kept when the Transform effect is applied draws turned once it is shown. + let mut off = relief; + off.visible = false; + let kept = crate::raster::without_geometry(&[off, transform(json!({"rotate": 90}))]); + assert_eq!(kept.len(), 1); + let mut shown = kept[0].clone(); + shown.visible = true; + assert_eq!(drawn_light(&[shown]), Some(Light::Left)); +} + +/// The light direction of every Bas Relief drawn on `n` and the nodes under it, from the object's +/// effects and from each fill's and stroke's. +fn lights_in(n: &Node) -> Vec { + let mut out = vec![]; + n.walk(&mut |m| { + let lists = std::iter::once(&m.appearance.effects).chain(m.appearance.items.iter().map(|i| i.effects())); + for list in lists { + out.extend(drawn_light(list)); + } + }); + out +} + +/// The canvas, a fill's own effects, a group's members and export turn the light the same way. +#[test] +fn nested_and_baked_directions_match_canvas() { + let relief = || fx("sketch.basRelief", json!({"lightDirection": "top"})); + let turn = || transform(json!({"rotate": 90})); + // A fill's own Transform effect, and the object's Transform effect over its fill. + let fill = fill_square(31, vec![relief(), turn()]); + let item = fill.appearance.items.first().unwrap(); + assert_eq!(drawn_light(item.effects()), Some(Light::Left)); + let mut over = fill_square(32, vec![relief()]); + over.appearance.effects = vec![turn()]; + let item = over.appearance.items.first().unwrap(); + assert_eq!(drawn_light(&crate::item_effects_in(&over.appearance.effects, item.effects())), Some(Light::Left)); + // A fill's own turn of 30° and the object's turn of 30° make 60°, rounded once: Top Left, not + // Left (Top Left after the first turn, then Left after the second). + let thirty = || transform(json!({"rotate": 30})); + let mut both = fill_square(37, vec![relief(), thirty()]); + both.appearance.effects = vec![thirty()]; + let item = both.appearance.items.first().unwrap(); + assert_eq!(drawn_light(&crate::item_effects_in(&both.appearance.effects, item.effects())), Some(Light::TopLeft)); + // A group's Transform effect over a member's own filter and its fill's. + let g = group(33, vec![square(34, vec![relief()]), fill_square(35, vec![relief()])], vec![turn()]); + let art = crate::evaluate_container(None, &g).unwrap(); + assert_eq!(lights_in(&art), vec![Light::Left; 2]); + // Baked for export: the Transform effect is applied and the filter keeps the turned light. + let mut d = Document::new(800.0, 800.0); + let layer = d.layers[0].id; + d.insert(Some(layer), 0, square(36, vec![relief(), turn()])).unwrap(); + d.insert(Some(layer), 1, g).unwrap(); + let baked = bake_document(&d).unwrap(); + let b = baked.node(NodeId(36)).unwrap(); + assert!(!b.appearance.effects.iter().any(|e| e.id == "distort.transform"), "{:?}", b.appearance.effects); + assert_eq!(drawn_light(&b.appearance.effects), Some(Light::Left)); + for id in [34, 35] { + assert_eq!(lights_in(baked.node(NodeId(id)).unwrap()), vec![Light::Left], "{id}"); + } +} + /// A Transform effect after a 3D effect that makes copies or moves at random holds back the shadow /// before the 3D effect, as it does without the 3D effect. #[test] diff --git a/crates/render/src/fx/tests.rs b/crates/render/src/fx/tests.rs index 50d0245c12..3bbd803cc2 100644 --- a/crates/render/src/fx/tests.rs +++ b/crates/render/src/fx/tests.rs @@ -337,6 +337,38 @@ fn a_transform_after_a_drop_shadow_scales_the_shadow_with_the_art() { } } +/// A Transform effect listed after a Bas Relief turns its light with the art: a group of a black +/// square centered on a white one, lit from the top and turned 90° counterclockwise about its +/// center, draws as the group lit from the left. +#[test] +fn a_transform_after_bas_relief_turns_its_light_with_the_art() { + let relieved = |effects: Vec<(&str, serde_json::Value)>| { + let mut d = Document::new(100.0, 100.0); + let mut square = + |r: Rect, c: Color| Arc::new(Node::path(d.alloc_id(), shapes::rectangle(r), Appearance::basic(Paint::solid(c), Paint::None, 0.0))); + let members = vec![square(Rect::new(20.0, 20.0, 80.0, 80.0), Color::WHITE), square(Rect::new(40.0, 40.0, 60.0, 60.0), Color::BLACK)]; + let mut g = Node::group(d.alloc_id(), members); + g.appearance.effects = effects.into_iter().map(|(id, p)| Effect { id: id.into(), params: p, visible: true }).collect(); + let l = d.layers[0].id; + d.insert(Some(l), 0, g).unwrap(); + render(&d) + }; + let relief = |light: &str| ("sketch.basRelief", json!({"lightDirection": light})); + let turned = relieved(vec![relief("top"), ("distort.transform", json!({"rotate": 90}))]); + let left = relieved(vec![relief("left")]); + let top = relieved(vec![relief("top")]); + // The largest difference of a channel between two images. + let diff = |a: &Rendered, b: &Rendered| { + (0..100u32) + .flat_map(|y| (0..100u32).map(move |x| (x, y))) + .map(|(x, y)| a.pixel(x, y).iter().zip(b.pixel(x, y)).map(|(p, q)| p.abs_diff(q)).max().unwrap_or(0)) + .max() + .unwrap_or(0) + }; + assert!(diff(&left, &top) > 50, "the light's direction shows: {}", diff(&left, &top)); + assert!(diff(&turned, &left) <= 2, "turned top light draws as a left light: {}", diff(&turned, &left)); +} + /// An object's or a group's Transform effect transforms the raster effects of what it holds with /// the art: halving a 40 pt square about its center halves the 10 pt offset of its fill's shadow, /// and of a group member's own shadow, with Scale Strokes & Effects off or on. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index cad5851e98..4615d556bb 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -619,7 +619,7 @@ since 2026-10-01. - **Selected Grid Repeat handles (#2691):** `tools/src/repeat_grid.rs` tests place the handles outside the grid at zoom 0.5, 1 and 4, preview rows, columns and spacing, leave no undo step for a drag that ends where it began, and give bounding-box handles priority; a headless canvas regression drags the row handle two tiles down in a zoomed view (3 → 5 rows, the source unchanged, one Undo back) and the column-spacing slider. Scores and hours unchanged. - **Selected Mirror Repeat handles:** a headless canvas regression creates the default mirror repeat and drags its Top bounding-box handle where the axis crosses it; the repeat grows vertically while its width stays fixed. Existing mirror-axis checks cover center movement and end-handle hit priority. The focused UI mirror tests pass. Scores and hours unchanged. - **Transform effect options (#885):** Effect › Distort & Transform › Transform… has visible Transform Objects, Transform Patterns and Scale Strokes & Effects checkboxes (`distort.transform` params `objects`, `patterns`, `strokes`; files without them draw as before). With Transform Objects off the geometry stays and makes no copies; Scale Strokes & Effects scales stroke weights, dashes and the fills' and strokes' effect distances by the mean scale, and Transform Patterns moves pattern tiles, each copy `k` by the transformation `k` times. Such objects draw, export and expand through the same per-copy art, so the canvas and Expand Appearance agree (engine `tests_transformfx`, effects `tests_transformfx`, the dialog test). A Transform effect in a fill's or stroke's own effects applies the same options to that fill or stroke: its weight and dashes and its pattern follow the transformation, and with copies each copy is an object of its own; the canvas, export, Expand Appearance and Use Preview Bounds use the same art (effects `tests_transformfx`). The effects listed after it in that fill's or stroke's list keep their own distances and apply to the transformed art and to each copy, as an object's later effects do after the object's Transform effect: a Drop Shadow after it keeps its offset, an Offset Path after it offsets by its own distance, and an SVG filter after it keeps its scale and the origin of its user space. With Transform Objects off, the effects before it keep their distances too. Before, Scale Strokes & Effects scaled a fill's or stroke's later effects by the mean scale, so existing documents with such effects draw differently. Effects apply in the order they are listed ([Appearance attributes](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/appearance-attributes-in-illustrator.html)); how the two options treat the effects after a fill's or stroke's own Transform effect is VectorCraft's own rule, following that order (effects `tests::rasterfollow::a_fills_own_transform_leaves_the_shadow_after_it`, `tests::rasterfollow::a_fills_own_transform_leaves_the_offset_after_it`, `tests::rasterfollow::a_fills_own_transform_leaves_the_svg_filter_after_it`, `tests::transformfx::a_fills_own_transform_with_scale_strokes_and_effects_leaves_its_later_effects`; engine `plugins::a_transform_after_a_painted_fill_effect_leaves_the_later_shadow_on_every_paint`). Public reference: [Scale objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-objects.html), [How to apply effects](https://helpx.adobe.com/illustrator/using/effects.html), [Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html). Scores and hours unchanged. -- **Raster effects before a Transform effect:** effects apply in the order they are listed ([Appearance attributes](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/appearance-attributes-in-illustrator.html)). A Drop Shadow, glow, blur, Feather or pixel filter listed before a Transform effect in the same list (an object's effects, or a fill's or stroke's own) now follows that Transform effect: its sizes scale by the mean scale, and a Drop Shadow's offset turns, reflects and scales with the art. VectorCraft applies this rule with Scale Strokes & Effects on or off. Before, such an effect was drawn at its own distances around the transformed art. The canvas, export, Expand Appearance, Object › Expand, Outline Stroke and the 3D effects use the same values (effects `tests::rasterfollow`; render `a_transform_after_a_drop_shadow_scales_the_shadow_with_the_art`; engine `objexpand::a_shadow_before_a_transform_expands_as_the_canvas_draws_it`, `outlinestroke::a_shadow_before_a_transform_outlines_as_the_canvas_draws_it`). Not yet: a Transform effect that makes copies or moves at random leaves the raster effects before it as they are; a Rasterize effect before a Transform effect keeps its pixel grid and room around the art; the angles and light directions of pixel filters do not turn or reflect with the art. Scores and hours unchanged. +- **Raster effects before a Transform effect:** effects apply in the order they are listed ([Appearance attributes](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/appearance-attributes-in-illustrator.html)). A Drop Shadow, glow, blur, Feather or pixel filter listed before a Transform effect in the same list (an object's effects, or a fill's or stroke's own) now follows that Transform effect: its sizes scale by the mean scale, and a Drop Shadow's offset turns, reflects and scales with the art. VectorCraft applies this rule with Scale Strokes & Effects on or off. Before, such an effect was drawn at its own distances around the transformed art. The canvas, export, Expand Appearance, Object › Expand, Outline Stroke and the 3D effects use the same values (effects `tests::rasterfollow`; render `a_transform_after_a_drop_shadow_scales_the_shadow_with_the_art`; engine `objexpand::a_shadow_before_a_transform_expands_as_the_canvas_draws_it`, `outlinestroke::a_shadow_before_a_transform_outlines_as_the_canvas_draws_it`). Not yet: a Transform effect that makes copies or moves at random leaves the raster effects before it as they are; a Rasterize effect before a Transform effect keeps its pixel grid and room around the art. The light direction of Underpainting, Rough Pastels, Conté Crayon, Bas Relief, Plaster and Texturizer and the stroke direction of Sprayed Strokes and Graphic Pen now turn and reflect with such a Transform effect, each set to the nearest of its menu's choices (at a tie, the one clockwise of it; VectorCraft's own rule), and Color Halftone's four screen angles turn and reflect with the art ([Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html); effects `tests::rasterfollow::bas_relief_light_follows_rotation_and_reflection` and the tests after it). Not yet: filters whose strokes or patterns run along fixed page axes without a direction setting (Angled Strokes, Crosshatch, Mezzotint's lines, Halftone Pattern's lines, Grain's horizontal and vertical types, De-Interlace) keep those axes, and an uneven scale or a shear sets a direction from the one vector it maps, not a skewed pattern. Scores and hours unchanged. - **Raster effects before a Transform effect that makes copies:** the Transform effect can make copies with its transformation applied ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html)). Giving each copy the raster effects listed before that effect is VectorCraft's own rule. On a path or compound path, each copy now carries the Drop Shadow, glow, blur, Feather or pixel filter listed before the last Transform effect that makes copies, with its sizes scaled by that copy's mean scale and a Drop Shadow's offset turned, reflected and scaled with the copy; a raster effect listed after it paints once around all the copies. Before, one shadow was drawn under all the copies at the object's own distances. The canvas, the object's bounds, export and Expand Appearance draw the same copies, and copies that stop at the effect budget each keep their effects (effects `tests::rasterfollow::each_copy_of_a_transform_effect_carries_the_shadow_listed_before_it`, `tests::rasterfollow::a_shadow_after_a_copying_transform_paints_once_around_the_copies`, `tests::rasterfollow::copies_past_the_budget_each_keep_their_shadow`; render `objectfx::each_copy_of_a_transform_effect_draws_its_own_shadow`; engine `objexpand::each_copys_shadow_expands_as_the_canvas_draws_it`). A Transform effect without copies draws as before. Not yet: the copies of type, images, symbol instances and groups, and a fill's or stroke's own copying Transform effect, still share one set of raster effects, and so does a path with Rasterize, an SVG filter or another effect that is neither a geometry effect nor one of those raster effects before the copying effect. Scores and hours unchanged. - **Raster effects before a Transform effect past the effect budget:** VectorCraft leaves out a Transform effect whose result would pass its geometry budget of 2 million anchors or 8 million lines drawn, and the art stays where it was. The raster effects listed before that Transform effect now stay with the art too: a Drop Shadow keeps its own offset and blur, and the Transform effects after it that fit still move both. Before, the art stayed while the shadow scaled with the Transform effect it did not take. This is VectorCraft's own rule. It applies to a path's own effects and to its fills' and strokes' own, also when the path is in a group whose geometry effects run after its members' own, on the canvas and in its bounds, in export, Expand Appearance, Object › Expand and Outline Stroke, and a hidden shadow keeps its values once shown (effects `tests::rasterfollow::a_transform_past_the_line_budget_moves_the_art_with_its_shadow`, `tests::rasterfollow::only_transforms_that_ran_move_a_preceding_shadow`, `tests::rasterfollow::a_skipped_item_transform_keeps_its_shadow`, `tests::rasterfollow::the_shape_art_of_a_skipped_transform_keeps_its_shadows`, `tests::rasterfollow::a_members_skipped_transform_keeps_its_shadow_under_its_groups_effects`; render `objectfx::a_shadow_before_a_skipped_transform_reaches_as_far_as_it_is_drawn`, `fx::renderer::tests::a_path_paints_from_the_transforms_that_moved_it`; engine `objexpand::a_shadow_before_a_skipped_transform_expands_with_its_own_offset`). Not yet: the shadow of type, an image, a symbol instance or a group whose art a Transform effect leaves in place past the budget still follows that effect. Scores and hours unchanged. - **Raster effects inside an object or group with a Transform effect:** effects applied to a group affect everything in it ([Appearance attributes](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/appearance-attributes-in-illustrator.html)). How a Transform effect changes the raster effects inside a group or object is VectorCraft's own rule. A group's Transform effect that moves it once now transforms the raster effects of its members, of their fills and strokes, of nested groups and of the art of the linked opacity masks in it, after the members' own Transform effects. A raster effect that a member's own Transform effect with copies or random holds back keeps its value through that effect and still transforms with the group's. VectorCraft applies the same rule to the raster effects of an object's fills and strokes under the object's Transform effect. Sizes scale by the mean scale and a Drop Shadow's offset turns, reflects and scales, with Scale Strokes & Effects on or off. Before, they kept their values, or with Scale Strokes & Effects on scaled by the mean scale with the offset unturned. A group's or object's Transform effect that makes copies or moves at random leaves them as before. The canvas, the redraw region, export, Expand Appearance, Object › Expand and Outline Stroke use the same values (effects `tests::rasterfollow`, `group::tests::a_compound_shapes_transform_turns_its_fills_shadow`; render `a_transform_scales_the_shadows_of_fills_and_members_with_the_art`; engine `objexpand::a_fills_shadow_under_the_objects_transform_expands_as_the_canvas_draws_it`, `objexpand::shadows_under_a_groups_or_an_objects_transform_expand_appearance_as_the_canvas_draws_them`, `outlinestroke::a_strokes_shadow_under_the_objects_transform_outlines_as_the_canvas_draws_it`). Scores and hours unchanged. From dfde48c181bf38473efc11755d91d30b9769f491 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 18:49:02 -0800 Subject: [PATCH 03/31] Type: outlined strokes on unevenly scaled type keep their thickness in each direction Create Outlines, Object > Expand and geometry effects scaled a character stroke on unevenly scaled, sheared or flattened type by the transform's mean scale, so a stroke scaled 300% across came out about 1.7 times as thick everywhere, while the canvas strokes the glyphs in text space and then transforms them. Under such a transform each run's stroke now becomes a path filled with the stroke's paint: the area the stroke paints around the glyphs in text space (dashes, caps, joins and inside or outside alignment), transformed with them. Moved, rotated, reflected and uniformly scaled type keeps a live stroke with its weight and dashes scaled. object.expand.info reports a gradient on such a filled stroke. --- crates/effects/src/reshape.rs | 53 ++++++++++- crates/effects/src/tests.rs | 1 + crates/effects/src/tests/typestroke.rs | 123 +++++++++++++++++++++++++ crates/engine/src/cmd/expand.rs | 13 ++- crates/engine/src/cmd/typecmd.rs | 32 ++++--- crates/engine/src/tests/charstroke.rs | 71 ++++++++++++++ crates/engine/src/tests/objexpand.rs | 23 +++++ docs/mcp.md | 6 +- docs/target-app-parity.md | 1 + 9 files changed, 299 insertions(+), 24 deletions(-) create mode 100644 crates/effects/src/tests/typestroke.rs diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index 70e5994cb5..217c1c2460 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -515,18 +515,62 @@ fn laid_out(t: &vectorcraft_doc::TextObject) -> (Vec, kurbo::Bez /// gradient fitted across the whole layout, and the transform also scales its stroke weights and /// dashes and transforms its pattern tiles. Placed gradients keep their place in text space and /// move with the type. -pub fn paint_type_piece(piece: &mut Node, style: &vectorcraft_doc::CharStyle, bounds: Rect, xf: Affine) { +/// +/// When `xf` is not a similarity (it scales unevenly, shears or flattens), one weight can't give +/// the stroke the thickness the canvas paints in each direction: `piece` keeps only the run's fill, +/// and the returned path is the area the run's stroke paints around `piece` in text space +/// ([`crate::stroke::outline_region`]: dashes, caps, joins and alignment), placed by `xf` and +/// filled with the stroke's paint, to paint over `piece`. `None` under a similarity and for a run +/// without a stroke. +pub fn paint_type_piece(piece: &mut Node, style: &vectorcraft_doc::CharStyle, bounds: Rect, xf: Affine) -> Option { + let scaling = vectorcraft_doc::Scaling { strokes: true, patterns: true, ..Default::default() }; let mut ap = style.appearance(); ap.pin_gradients(bounds); + let stroke = if is_similarity(xf) { None } else { filled_stroke(piece, &mut ap) }; piece.appearance = ap.into(); - piece.transform(xf, vectorcraft_doc::Scaling { strokes: true, patterns: true, ..Default::default() }); + piece.transform(xf, scaling); + stroke.map(|mut s| { + s.transform(xf, scaling); + s + }) +} + +/// Does `xf` keep angles and scale every direction alike (a move, a rotation, a uniform scale or a +/// reflection), without flattening? +fn is_similarity(xf: Affine) -> bool { + let [a, b, c, d, ..] = xf.as_coeffs(); + let (x, y) = (a.hypot(b), c.hypot(d)); + let tol = 1e-9 * x.max(y); + x.is_finite() && y.is_finite() && x > 0.0 && y > 0.0 && (x - y).abs() <= tol && (a * c + b * d).abs() <= tol * x.max(y) +} + +/// Takes the stroke out of `ap`, the appearance of `piece` (a path or compound path in text space), +/// and returns the area it paints there as a path filled with its paint, opacity, blend mode, +/// effects and overprint, with `piece`'s id. `None` when `ap` has no stroke or it paints nothing. +fn filled_stroke(piece: &Node, ap: &mut Appearance) -> Option { + let i = ap.items.iter().position(|i| matches!(i, AppearanceItem::Stroke(_)))?; + let AppearanceItem::Stroke(st) = ap.items.remove(i) else { return None }; + let path = PathData::from_bezpath(&piece.stroke_path()?); + let region = crate::stroke::outline_region(&path, FillRule::NonZero, &st); + if region.is_empty() { + return None; + } + let fill = vectorcraft_doc::FillLayer { + opacity: st.opacity, + blend: st.blend, + effects: st.effects.clone(), + overprint: st.overprint, + ..vectorcraft_doc::FillLayer::new(st.paint.stroke_as_fill()) + }; + Some(Node::path(piece.id, region, Appearance { items: vec![AppearanceItem::Fill(fill)], ..Default::default() })) } /// Type as glyph outlines in document space: one path per run with the run's fill and stroke, /// over its colour glyphs (images, art), and (when the object has its own fills/strokes) the whole /// outline with the object's items below the characters under them and the others over them, as /// the renderer paints them. Each run's path is placed by the type's transform, which also scales its stroke -/// weights and dashes and transforms its pattern tiles; its unplaced gradients are first fixed to +/// weights and dashes and transforms its pattern tiles (a transform that is not a similarity puts +/// the run's stroke on a filled path over it, [`paint_type_piece`]); its unplaced gradients are first fixed to /// the layout's bounds in text space. The object's own unplaced gradients are fixed to the /// bounding box of those bounds in the document. The group is marked as type's outlines /// ([`vectorcraft_doc::NodeExtras::type_outlines`]). @@ -542,8 +586,9 @@ pub fn outline_text(n: &Node) -> Option { continue; } let mut piece = Node::path(n.id, PathData::from_bezpath(bp), Appearance::default()); - paint_type_piece(&mut piece, &run.style, bounds, t.xf); + let stroke = paint_type_piece(&mut piece, &run.style, bounds, t.xf); children.push(Arc::new(piece)); + children.extend(stroke.map(Arc::new)); } if !n.appearance.items.is_empty() && !all.elements().is_empty() { let (below, above) = n.appearance.split_contents(); diff --git a/crates/effects/src/tests.rs b/crates/effects/src/tests.rs index c605b6461f..ac340224c6 100644 --- a/crates/effects/src/tests.rs +++ b/crates/effects/src/tests.rs @@ -11,6 +11,7 @@ mod rasterfollow; mod scale; mod solidcontext; mod transformfx; +mod typestroke; fn fx(id: &str, params: Value) -> Effect { Effect { id: id.into(), params, visible: true } diff --git a/crates/effects/src/tests/typestroke.rs b/crates/effects/src/tests/typestroke.rs new file mode 100644 index 0000000000..d6c8e82cec --- /dev/null +++ b/crates/effects/src/tests/typestroke.rs @@ -0,0 +1,123 @@ +//! Character strokes of outlined type under the type's transform ([`paint_type_piece`]): a live +//! stroke with a scaled weight under a similarity, otherwise the area the stroke paints in text +//! space, placed by the transform and filled. + +use vectorcraft_color::{Color, Gradient, GradientKind, GradientPaint, GradientStop, Paint}; +use vectorcraft_doc::{Appearance, CharStyle, Dash, LineJoin, Node, NodeId, StrokeAlign}; +use vectorcraft_geom::{Affine, FillRule, Rect, shapes}; + +use crate::*; + +const BOX: Rect = Rect::new(0.0, 0.0, 10.0, 10.0); + +fn red() -> Color { + Color::rgb(1.0, 0.0, 0.0) +} + +/// A black run with a red stroke of `width` and round joins. +fn style(width: f64) -> CharStyle { + CharStyle { + fill: Paint::solid(Color::BLACK), + stroke: Paint::solid(red()), + stroke_width: width, + stroke_join: LineJoin::Round, + ..CharStyle::default() + } +} + +/// A 10 x 10 square in text space standing in for a glyph. +fn square() -> Node { + Node::path(NodeId(7), shapes::rectangle(BOX), Appearance::default()) +} + +fn area(n: &Node) -> f64 { + vectorcraft_pathops::area(n.path_data().unwrap(), FillRule::NonZero).abs() +} + +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(|d| d.abs() < 0.05) +} + +#[test] +fn an_uneven_scale_fills_the_stroke_the_canvas_paints() { + let mut piece = square(); + let stroke = paint_type_piece(&mut piece, &style(4.0), BOX, Affine::scale_non_uniform(3.0, 1.0)).expect("a filled stroke"); + assert!(piece.appearance.stroke().is_none(), "the piece keeps only its fill"); + assert_eq!(piece.appearance.fill_paint(), Paint::solid(Color::BLACK)); + assert_eq!(piece.geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 30.0, 10.0)); + assert!(stroke.appearance.stroke().is_none()); + assert_eq!(stroke.appearance.fill_paint(), Paint::solid(red())); + assert_eq!(stroke.id, NodeId(7)); + // 4 pt across in text space: 12 pt across the upright sides and 4 pt across the level ones. + let b = stroke.geometric_bounds().unwrap(); + assert!(near(b, Rect::new(-6.0, -2.0, 36.0, 12.0)), "{b:?}"); + // The ring of a 10 pt square stroked 4 pt with round joins (180 + 4π outside, 36 inside), 3 times as wide. + let ring = 180.0 + 4.0 * std::f64::consts::PI - 36.0; + assert!((area(&stroke) - 3.0 * ring).abs() < 0.5, "{}", area(&stroke)); +} + +#[test] +fn a_similarity_keeps_the_live_stroke_with_a_scaled_weight() { + for (xf, weight) in [ + (Affine::translate((5.0, 5.0)), 4.0), + (Affine::scale(2.0), 8.0), + (Affine::rotate(0.5) * Affine::scale(2.0), 8.0), + (Affine::scale_non_uniform(-2.0, 2.0), 8.0), + ] { + let mut piece = square(); + assert!(paint_type_piece(&mut piece, &style(4.0), BOX, xf).is_none(), "{xf:?}"); + let st = piece.appearance.stroke().expect("a live stroke"); + assert!((st.width - weight).abs() < 1e-9, "{xf:?}: {}", st.width); + assert_eq!(st.join, LineJoin::Round); + } +} + +#[test] +fn shears_and_flattening_transforms_fill_the_stroke() { + // A shear keeps the area. + let mut piece = square(); + let stroke = paint_type_piece(&mut piece, &style(4.0), BOX, Affine::skew(0.5, 0.0)).expect("a filled stroke"); + let ring = 180.0 + 4.0 * std::f64::consts::PI - 36.0; + assert!((area(&stroke) - ring).abs() < 0.5, "{}", area(&stroke)); + // Flattened to a line or a point: no division by the determinant, nothing non-finite. + for xf in [Affine::scale_non_uniform(2.0, 0.0), Affine::scale(0.0)] { + let mut piece = square(); + let stroke = paint_type_piece(&mut piece, &style(4.0), BOX, xf).expect("a filled stroke"); + assert!(piece.appearance.stroke().is_none()); + if let Some(b) = stroke.geometric_bounds() { + assert!([b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite()) && b.height().abs() < 1e-9, "{xf:?}: {b:?}"); + } + } +} + +#[test] +fn the_stroke_options_shape_the_filled_stroke_in_text_space() { + let xf = Affine::scale_non_uniform(3.0, 1.0); + let filled = |st: CharStyle| paint_type_piece(&mut square(), &st, BOX, xf); + // No stroke, or no weight: nothing is filled. + assert!(filled(style(0.0)).is_none()); + assert!(filled(CharStyle { stroke: Paint::None, ..style(4.0) }).is_none()); + // Inside and outside alignment are kept to their side of the square before it is scaled. + let inside = filled(CharStyle { stroke_align: StrokeAlign::Inside, ..style(4.0) }).unwrap(); + assert!(near(inside.geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 30.0, 10.0))); + assert!((area(&inside) - 3.0 * (100.0 - 4.0)).abs() < 0.5, "{}", area(&inside)); + let outside = filled(CharStyle { stroke_align: StrokeAlign::Outside, ..style(4.0) }).unwrap(); + assert!(near(outside.geometric_bounds().unwrap(), Rect::new(-12.0, -4.0, 42.0, 14.0)), "{:?}", outside.geometric_bounds()); + // Dashes are laid out along the square in text space: half of each 10 pt is painted. + let solid = area(&filled(style(1.0)).unwrap()); + let dash = Dash { pattern: vec![5.0, 5.0], ..Default::default() }; + let dashed = area(&filled(CharStyle { stroke_dash: Some(dash), ..style(1.0) }).unwrap()); + assert!(dashed < 0.7 * solid && dashed > 0.3 * solid, "{dashed} of {solid}"); +} + +#[test] +fn a_gradient_on_the_stroke_stays_where_the_stroke_had_it() { + let stops = vec![GradientStop::new(0.0, red()), GradientStop::new(1.0, Color::BLACK)]; + let ramp = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops)))); + let mut piece = square(); + let stroke = paint_type_piece(&mut piece, &CharStyle { stroke: ramp, ..style(4.0) }, BOX, Affine::scale_non_uniform(3.0, 1.0)).unwrap(); + let Paint::Gradient(g) = stroke.appearance.fill_paint() else { panic!("a gradient fill") }; + // Fitted across the stroke's box in text space (the square grown by half the weight), then scaled. + let geom = g.geom.expect("placed"); + assert!((geom.start.x + 6.0).abs() < 1e-6 && (geom.end.x - 36.0).abs() < 1e-6, "{geom:?}"); +} diff --git a/crates/engine/src/cmd/expand.rs b/crates/engine/src/cmd/expand.rs index 43975fe4e4..a17a02ed15 100644 --- a/crates/engine/src/cmd/expand.rs +++ b/crates/engine/src/cmd/expand.rs @@ -265,18 +265,21 @@ fn gradient_expands(d: &Document, l: &Node) -> bool { /// Whether type `t` has a gradient fill that Fill expands once Object has outlined it: one of the /// paths `type.createOutlines` makes of its glyphs, ruby glyphs and underline and strikethrough -/// bars, each painted as its run with its unplaced gradients fitted to the layout's bounds, has one +/// bars, each painted as its run with its unplaced gradients fitted to the layout's bounds, or the +/// path filled with its run's stroke under a transform that is not a similarity, has one /// ([`gradient_expands`] on that path). Inline graphics and color glyphs become other art. Leaves /// the document as it is and stops at the first such path. fn text_gradient_expands(d: &Document, t: &TextObject) -> bool { - if !t.runs.iter().any(|r| matches!(r.style.fill, Paint::Gradient(_))) { + let gradient = + |st: &vectorcraft_doc::CharStyle| matches!(st.fill, Paint::Gradient(_)) || (st.has_stroke() && matches!(st.stroke, Paint::Gradient(_))); + if !t.runs.iter().any(|r| gradient(&r.style)) { return false; } let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); let first = t.first_style(); let expands = |run: usize, outline: &BezPath| { let style = t.runs.get(run).map_or(&first, |r| &r.style); - if !matches!(style.fill, Paint::Gradient(_)) { + if !gradient(style) { return false; } let path = PathData::from_bezpath(outline); @@ -284,8 +287,8 @@ fn text_gradient_expands(d: &Document, t: &TextObject) -> bool { return false; } let mut piece = Node::path(NodeId(u64::MAX), path, Appearance::default()); - vectorcraft_render::effects::paint_type_piece(&mut piece, style, lay.bounds, t.xf); - gradient_expands(d, &piece) + let stroke = vectorcraft_render::effects::paint_type_piece(&mut piece, style, lay.bounds, t.xf); + gradient_expands(d, &piece) || stroke.is_some_and(|s| gradient_expands(d, &s)) }; let inline = |gi: usize| lay.inlines.iter().find(|i| i.glyph == gi).is_some_and(|i| t.runs.get(i.run).is_some_and(|r| r.inline.is_some())); lay.glyphs.iter().enumerate().any(|(gi, g)| !inline(gi) && g.image.is_none() && g.colour.is_none() && expands(g.run, &g.outline)) diff --git a/crates/engine/src/cmd/typecmd.rs b/crates/engine/src/cmd/typecmd.rs index 31bcad4671..9c4999bced 100644 --- a/crates/engine/src/cmd/typecmd.rs +++ b/crates/engine/src/cmd/typecmd.rs @@ -41,7 +41,7 @@ pub fn specs() -> Vec { "Create Outlines", ["Type"], Some("Cmd+Shift+O"), - "{} convert the selected text to groups of compound paths (one per glyph); the type object's own fills and strokes (not its characters') go on paths of its whole outline, below or above the glyphs as its Characters row places them; a frame of threaded text leaves its thread with the text it shows; a dimension whose label is outlined becomes a plain group of its art → {ids}", + "{} convert the selected text to groups of compound paths (one per glyph); on type scaled unevenly, sheared or flattened, each glyph's stroke becomes a filled path over it, shaped as the canvas strokes it; the type object's own fills and strokes (not its characters') go on paths of its whole outline, below or above the glyphs as its Characters row places them; a frame of threaded text leaves its thread with the text it shows; a dimension whose label is outlined becomes a plain group of its art → {ids}", has_selection, create_outlines ), @@ -619,16 +619,25 @@ fn scale_text_attributes(s: &mut Session, p: &Value) -> Result { /// A path (or compound path) of `outline`, a piece of type `t`'s outline in text space, painted as /// run `run` and placed in the document as the canvas paints it ([`paint_type_piece`]: unplaced /// gradients fitted to `bounds`, the layout's bounds, stroke weights scaled by the type's -/// transform); `None` when the piece has no path. -fn type_piece(d: &mut Document, t: &TextObject, bounds: kurbo::Rect, run: usize, outline: &kurbo::BezPath) -> Option { +/// transform), followed by a path (or compound path) filled with the run's stroke when the type's +/// transform is not a similarity; empty when the piece has no path. +fn type_piece(d: &mut Document, t: &TextObject, bounds: kurbo::Rect, run: usize, outline: &kurbo::BezPath) -> Vec { let path = PathData::from_bezpath(outline); if path.is_empty() { - return None; + return vec![]; } let st = t.runs.get(run).map(|r| r.style.clone()).unwrap_or_else(|| t.first_style()); let mut node = shape_node(d, path, None); - vectorcraft_render::effects::paint_type_piece(&mut node, &st, bounds, t.xf); - Some(node) + let stroke = vectorcraft_render::effects::paint_type_piece(&mut node, &st, bounds, t.xf); + let mut out = vec![node]; + if let Some(s) = stroke + && let Some(path) = s.path_data() + { + let mut filled = shape_node(d, path.clone(), None); + filled.appearance = s.appearance.clone(); + out.push(filled); + } + out } fn create_outlines(s: &mut Session, _: &Value) -> Result { @@ -675,9 +684,7 @@ fn create_outlines(s: &mut Session, _: &Value) -> Result { children.push(Arc::new(d.reid(&art))); break 'glyph; } - if let Some(node) = type_piece(d, t, lay.bounds, g.run, &g.outline) { - children.push(Arc::new(node)); - } + children.extend(type_piece(d, t, lay.bounds, g.run, &g.outline).into_iter().map(Arc::new)); } run_end.insert(g.run, children.len()); } @@ -686,10 +693,9 @@ fn create_outlines(s: &mut Session, _: &Value) -> Result { // nothing there either). let mut ruby: Vec<(usize, Arc)> = vec![]; for g in &lay.ruby { - let Some(node) = type_piece(d, t, lay.bounds, g.run, &g.outline) else { continue }; // After the glyphs of its run and of the runs before it. let at = run_end.range(..=g.run).map(|(_, end)| *end).max().unwrap_or(0); - ruby.push((at, Arc::new(node))); + ruby.extend(type_piece(d, t, lay.bounds, g.run, &g.outline).into_iter().map(|node| (at, Arc::new(node)))); } ruby.sort_by_key(|(at, _)| *at); let mut ruby = ruby.into_iter().peekable(); @@ -711,9 +717,7 @@ fn create_outlines(s: &mut Session, _: &Value) -> Result { // Underline and strikethrough bars become paths of their run's paint too (#847). for (run, bar) in vectorcraft_text::decorations(&lay, vectorcraft_text::FontDb::global(), t) { all.extend(bar.iter()); - if let Some(node) = type_piece(d, t, lay.bounds, run, &bar) { - children.push(Arc::new(node)); - } + children.extend(type_piece(d, t, lay.bounds, run, &bar).into_iter().map(Arc::new)); } // The object's own fills and strokes (not its characters') paint the whole outline: // those below the Characters row under the characters, the others over them, with diff --git a/crates/engine/src/tests/charstroke.rs b/crates/engine/src/tests/charstroke.rs index 2c34e697ea..d692becbce 100644 --- a/crates/engine/src/tests/charstroke.rs +++ b/crates/engine/src/tests/charstroke.rs @@ -188,6 +188,77 @@ fn align_stroke_reaches_the_characters_stroke() { assert!(aligns.contains(&StrokeAlign::Inside) && aligns.contains(&StrokeAlign::Outside), "{aligns:?}"); } +/// The bounds of type `t`'s glyph outlines in text space. +fn glyph_bounds(t: &TextObject) -> kurbo::Rect { + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); + let mut all = kurbo::BezPath::new(); + for g in &lay.glyphs { + all.extend(g.outline.iter()); + } + kurbo::Shape::bounding_box(&all) +} + +/// Create Outlines on type scaled 300% across and 100% down: the canvas strokes the characters in +/// text space and then scales them, so the outlined stroke is filled art three times as thick +/// across upright stems as across level bars, not a live stroke of one mean weight. +#[test] +fn create_outlines_keeps_the_character_strokes_thickness_under_an_uneven_scale() { + let mut s = session(); + let id = stroked_text(&mut s); + run(&mut s, "stroke.set", json!({"weight": 4, "join": "round", "cap": "round"})); + run(&mut s, "object.scale", json!({"ids": [id.0], "sx": 300, "sy": 100})); + let t = text(&s, id); + let [a, b, c, d, ..] = t.xf.as_coeffs(); + assert!((a - 3.0).abs() < 1e-9 && b.abs() < 1e-9 && c.abs() < 1e-9 && (d - 1.0).abs() < 1e-9, "{:?}", t.xf); + let w = t.runs[0].style.stroke_width; + let gb = glyph_bounds(&t); + run(&mut s, "select.set", json!({ "ids": [id.0] })); + let g = run(&mut s, "type.createOutlines", json!({}))["ids"][0].as_u64().unwrap(); + let doc = &s.doc().unwrap().doc; + let group = doc.node(NodeId(g)).unwrap(); + let mut strokes: Option = None; + for c in group.children().unwrap() { + assert!(c.appearance.stroke().is_none(), "no live stroke of one weight is left"); + if c.appearance.fill_paint() == Paint::solid(Color::rgb8(255, 0, 0)) { + let cb = c.geometric_bounds().unwrap(); + strokes = Some(strokes.map_or(cb, |s| s.union(cb))); + } + } + // Round joins and caps reach half the weight past the glyphs in text space, then scale. + let want = t.xf.transform_rect_bbox(gb.inflate(w / 2.0, w / 2.0)); + let got = strokes.expect("filled character strokes"); + assert!((got.width() - want.width()).abs() < 0.1 && (got.height() - want.height()).abs() < 0.1, "{got:?} for {want:?}"); + assert!((got.height() - (gb.height() + w)).abs() < 0.1, "level bars keep the weight: {got:?}"); +} + +/// Under a uniform scale and a rotation the outlined characters keep a live stroke, its weight +/// and dashes scaled with them. +#[test] +fn create_outlines_keeps_a_live_character_stroke_under_a_uniform_scale_and_rotation() { + let mut s = session(); + let id = stroked_text(&mut s); + run(&mut s, "stroke.set", json!({"weight": 4, "dash": [6, 2]})); + run(&mut s, "object.scale", json!({"ids": [id.0], "sx": 200, "sy": 200})); + run(&mut s, "object.rotate", json!({"angle": 30})); + let t = text(&s, id); + let k = t.xf.determinant().abs().sqrt(); + assert!((k - 2.0).abs() < 1e-9, "{:?}", t.xf); + let st = t.runs[0].style.clone(); + let dash = st.stroke_dash.as_ref().unwrap().pattern.clone(); + let glyphs = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).glyphs.len(); + run(&mut s, "select.set", json!({ "ids": [id.0] })); + let g = run(&mut s, "type.createOutlines", json!({}))["ids"][0].as_u64().unwrap(); + let doc = &s.doc().unwrap().doc; + let pieces = doc.node(NodeId(g)).unwrap().children().unwrap().to_vec(); + assert_eq!(pieces.len(), glyphs, "one path for each glyph, no filled strokes"); + for p in &pieces { + let ps = p.appearance.stroke().expect("a live stroke"); + assert!((ps.width - st.stroke_width * k).abs() < 1e-6, "{} for {}", ps.width, st.stroke_width * k); + let got = &ps.dash.as_ref().unwrap().pattern; + assert!(got.iter().zip(&dash).all(|(g, d)| (g - d * k).abs() < 1e-6), "{got:?} for {dash:?}"); + } +} + /// Copying type's appearance onto a path keeps its characters' stroke alignment (the Eyedropper's /// own stroke attributes have none, on paths as on type). #[test] diff --git a/crates/engine/src/tests/objexpand.rs b/crates/engine/src/tests/objexpand.rs index 3788185ae6..7d1c38b5e5 100644 --- a/crates/engine/src/tests/objexpand.rs +++ b/crates/engine/src/tests/objexpand.rs @@ -717,6 +717,29 @@ fn type_reports_a_gradient_when_any_glyph_expands() { assert_eq!(gradients_and_type(&s), (1, 0), "the large glyph keeps its gradient"); } +/// Type scaled unevenly outlines its characters' stroke as a filled path, so a gradient on that +/// stroke becomes a gradient fill: the query reports it, and Expand turns it into art. +#[test] +fn type_reports_a_stroke_gradient_its_uneven_scale_turns_into_a_fill() { + let mut s = session(); + let t = run(&mut s, "text.create", json!({"x": 50, "y": 100, "text": "Hi", "size": 48}))["id"].as_u64().unwrap(); + run(&mut s, "select.set", json!({"ids": [t]})); + run( + &mut s, + "paint.setStroke", + json!({"gradient": {"kind": "linear", "spread": "repeat", "repeats": 100, "start": [50, 100], "end": [70, 100], + "stops": [{"offset": 0, "color": "#ffff00"}, {"offset": 1, "color": "#004080"}]}}), + ); + run(&mut s, "stroke.set", json!({"weight": 4})); + let info = run(&mut s, "object.expand.info", json!({})); + assert_eq!(info["gradient"], json!(false), "a live stroke's gradient is not a fill"); + run(&mut s, "object.scale", json!({"ids": [t], "sx": 300, "sy": 100})); + let info = run(&mut s, "object.expand.info", json!({})); + assert_eq!((info["gradient"].clone(), info["fill"].clone()), (json!(true), json!(true))); + run(&mut s, "object.expand", json!({})); + assert_eq!(gradients_and_type(&s), (0, 0), "the filled strokes' gradients became art"); +} + /// The same rule for type in the art of a symbol instance that Object expands. The symbol's art /// is the type scaled down (its "i" about 2.5 pt wide), so its glyphs need more runs than are /// written with 0.002 pt runs (over a 0.2 pt vector). diff --git a/docs/mcp.md b/docs/mcp.md index d4e03892e9..7d9542a508 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -8755,7 +8755,11 @@ indent and bullet or number again. ``` `type.createOutlines` (Type › Create Outlines) makes a group with a path per glyph, ruby glyph and underline or -strikethrough bar, each painted as its characters are. The type object's own fills and strokes (the items around the +strikethrough bar, each painted as its characters are. When the type is scaled unevenly, sheared or flattened, each of +these paths takes only its characters' fill, and a path filled with the stroke's paint follows it: the area the +characters' stroke paints around the glyphs before the type's transform (dashes, caps, joins and alignment), transformed +with them as the canvas draws it. Under a move, rotation, reflection or uniform scale the paths keep a live stroke, its +weight and dashes scaled with the type. The type object's own fills and strokes (the items around the Appearance panel's Characters row, not the characters' formatting) go on paths of the type's whole outline: the items below the Characters row on one path under the glyph paths, the others on one path over them, in their order and with their opacity, blend mode, effects and stroke settings. Their gradients that are not placed are fixed to the type's diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index cad5851e98..8620a8d858 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -687,6 +687,7 @@ since 2026-10-01. - **OpenType SVG colour fonts:** each glyph's SVG document is read by the SVG importer (registered by the engine) into vector art in the run's colours, then drawn, exported and outlined as COLR glyphs are; PDF real text writes them as text that draws nothing and draws their art where they sit. Measured by `tests_svg_glyphs`, `svg/tests/it/svg_glyphs.rs`, `tests_colourfonts::create_outlines_turns_svg_glyphs_into_groups`, `tests_colourfonts::pdf_real_text_draws_svg_glyphs_as_art_and_keeps_their_characters`. Scores unchanged (estimated). - **Create Outlines keeps the type object's own appearance:** Type › Create Outlines and Object › Expand put the type object's own fills and strokes (the Appearance panel's items around its Characters row) on paths of the whole outline, below or above the glyph paths as that row places them, with one gradient across every glyph, so the outlines draw what the type drew; `object.expand.info` reports those strokes, pattern fills and gradient fills. Outlined characters keep their stroke and fill (the help page, ); a type object's appearance is separate from its characters' (the help page, ); where the object's items go is VectorCraft's own rule. Measured by `tests::pathops::create_outlines_keeps_the_objects_own_fills_and_strokes`, `tests::objexpand::create_outlines_draws_the_type_objects_own_paint`, `tests::objexpand::type_objects_own_stroke_pattern_and_gradient_are_reported`, `tests::objexpand::type_without_an_outline_reports_no_own_stroke_or_fill`, `tests::objexpand::a_stroke_under_an_unpainted_stroke_is_reported_and_outlined` and `tests::objexpand::expand_keeps_the_type_objects_own_paint`. Scores unchanged (estimated). - **Create Outlines keeps the characters' gradients across the type:** Type › Create Outlines and Object › Expand give every glyph, ruby glyph and underline or strikethrough bar the gradient its characters drew with: a gradient with no vector of its own stays fitted to the whole layout rather than to each glyph, and one with a vector keeps its place, both moved, scaled and rotated with the type; the characters' stroke keeps the weight it was drawn at on scaled type. `object.expand.info` measures gradient fills on the same paths. Outlined characters keep their stroke and fill (the help page, ); the gradient fitted across the whole layout is VectorCraft's own rule. Measured by `tests::objexpand::create_outlines_keeps_a_character_gradient_across_the_type` and `tests::objexpand::expand_keeps_a_character_gradient_across_the_type`. Scores unchanged (estimated). +- **Create Outlines keeps the characters' stroke on unevenly scaled type:** on type scaled unevenly, sheared or flattened, Type › Create Outlines, Object › Expand and geometry effects on the type turn each character stroke into a filled path of the area the canvas strokes: laid out around the glyphs before the type's transform (dashes, caps, joins and inside or outside alignment), then transformed with them, so a stroke scaled 300% across is three times as thick across upright stems as across level bars. Moved, rotated, reflected and uniformly scaled type keeps a live stroke with its weight and dashes scaled. `object.expand.info` reports a gradient on such a filled stroke. Outlined characters keep their stroke and fill (the help page, ); turning the stroke into a filled path only under such transforms is VectorCraft's own rule. Measured by `tests::charstroke::create_outlines_keeps_the_character_strokes_thickness_under_an_uneven_scale`, `tests::charstroke::create_outlines_keeps_a_live_character_stroke_under_a_uniform_scale_and_rotation`, `tests::objexpand::type_reports_a_stroke_gradient_its_uneven_scale_turns_into_a_fill` and `tests::typestroke` (`crates/effects`). Scores unchanged (estimated). - **Composite fonts that two documents define differently:** when two open documents each define a composite font (Type › Composite Fonts…) by the same name with different parts, each document draws and exports its type in its own definition: in a tiled or floating window drawn while the front document draws, when it is placed in a document that defines the name differently, and in an export made while another document is in front. Evidence: `tests::composite::nested_loans_of_one_name_use_each_documents_definition` and `threads_lending_one_name_at_once_use_their_own_definitions` (`crates/text`), `tests::fontchange::a_placed_document_draws_its_own_definition_of_a_name_the_page_defines` (`crates/render`). Scores unchanged (estimated). - **Composite fonts only another document defines:** a document draws, measures and exports its type only in the composite fonts it defines itself. Type naming a composite font that only another open document, or the document a placed document sits in, defines is set as in a missing font, also when the document defines no composite font: in a window, a thumbnail or an export of a document in the back, in a file being opened and in a placed document. A temporary document drawn while a document draws keeps that document's composite fonts. Evidence: `tests::composite::a_lent_document_does_not_use_another_documents_composite_font` and `a_document_without_composite_fonts_uses_none_and_a_preview_is_unchanged` (`crates/text`), `tests::fontchange::a_placed_document_draws_its_own_definition_of_a_name_the_page_defines` and `a_document_draws_type_in_another_documents_composite_font_as_missing` (`crates/render`), `a_document_replaced_in_the_back_measures_a_font_it_lacks_as_missing` (`crates/engine`). Scores unchanged (estimated). - **Character-style Auto leading:** capture and explicit style attributes retain Auto as a reset, distinct from omitted leading. Redefine and later numeric updates preserve local leading overrides; the Character Styles marker recognizes Auto correctly. Regression assertions cover partial definitions, Undo/Redo and native save/load serialization. Public references: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html) and [Leading](https://helpx.adobe.com/illustrator/using/line-character-spacing.html). From a327587d645f87b73cc82c4d2d21fef0989b230a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 20:12:25 -0800 Subject: [PATCH 04/31] Effects: nested groups' Transform effects round a member's direction once A member's light or stroke direction under groups that each have a Transform effect is now rounded once for the turn of all of them. The inner group's members are evaluated first, so each group rounded the direction again: two 30-degree turns of a top light gave Left instead of Top Left. While a group's members are evaluated, the group's own Transform effects are counted among those the members still go through. --- crates/effects/src/group.rs | 6 +++- crates/effects/src/raster.rs | 37 ++++++++++++++++++++++-- crates/effects/src/tests/rasterfollow.rs | 23 +++++++++++++++ 3 files changed, 62 insertions(+), 4 deletions(-) diff --git a/crates/effects/src/group.rs b/crates/effects/src/group.rs index 1b64971a3a..8d71b7f1a1 100644 --- a/crates/effects/src/group.rs +++ b/crates/effects/src/group.rs @@ -868,7 +868,11 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option { } if !fx.is_empty() { m = crate::reshape::outlined_members(doc, &m); - members_as_drawn(doc, &mut m); + { + // The members' raster effects then follow the group's own Transform effects as well. + let _later = crate::raster::LaterGroups::enter(&n.appearance.effects); + members_as_drawn(doc, &mut m); + } let carry = crate::reshape::reshape_leaves_carrying(&mut m, &fx, &n.appearance.effects, doc); // The group's own fills and strokes paint the members as a whole: their gradients follow // the effects as the members' do. diff --git a/crates/effects/src/raster.rs b/crates/effects/src/raster.rs index 9dcff61f0d..7f57abe4bf 100644 --- a/crates/effects/src/raster.rs +++ b/crates/effects/src/raster.rs @@ -613,12 +613,43 @@ pub(crate) fn follows(id: &str) -> bool { crate::is_raster(id) && id != crate::SVG_FILTER && id != RASTERIZE } +thread_local! { + /// The linear part of the Transform effects of the groups and layers whose members are being + /// evaluated ([`LaterGroups`]), which those groups apply to the members' raster effects once + /// the members are evaluated: the members' light and stroke directions are rounded for them as + /// well ([`follow_transform`]). + static LATER_GROUPS: std::cell::Cell = const { std::cell::Cell::new(Affine::IDENTITY) }; +} + +/// The Transform effects of a group or layer whose members are being evaluated before the group's +/// own effects are applied to them, added to [`LATER_GROUPS`] until it is dropped. +pub(crate) struct LaterGroups(Affine); + +impl LaterGroups { + /// Add the Transform effects of `owner`, a group's or layer's own effects ([`contents_step`]), + /// to those the members will still go through. + pub(crate) fn enter(owner: &[Effect]) -> Self { + let was = LATER_GROUPS.with(|l| l.get()); + if let Some(step) = contents_step(owner) { + LATER_GROUPS.with(|l| l.set(was * step)); + } + LaterGroups(was) + } +} + +impl Drop for LaterGroups { + fn drop(&mut self) { + LATER_GROUPS.with(|l| l.set(self.0)); + } +} + /// Make raster effect `e` follow `a`, the linear part of a Transform effect listed after it, as /// that effect transforms what `e` paints: its distances and raster sizes scale by `a`'s mean /// scale ([`crate::scale_effect`]), a Drop Shadow's offset turns, reflects and scales with `a`, /// and a pixel filter's light direction, stroke direction or screen angles turn and reflect with -/// it ([`pixel::turned_directions`]; `later` is the map `e` still goes through when it is drawn). -/// Effects that [`follows`] leaves out stay as they are. +/// it ([`pixel::turned_directions`]; `later` is the map `e` still goes through when it is drawn, +/// before the Transform effects of the groups around it in [`LATER_GROUPS`]). Effects that +/// [`follows`] leaves out stay as they are. fn follow_transform(e: &mut Effect, a: Affine, later: Affine) { if !follows(&e.id) { return; @@ -627,7 +658,7 @@ fn follow_transform(e: &mut Effect, a: Affine, later: Affine) { let p = merged_params(&e.id, &e.params); a * Point::new(num(&p, "x", 7.0), num(&p, "y", 7.0)) }); - let turned = pixel::turned_directions(&e.id, &e.params, a, later); + let turned = pixel::turned_directions(&e.id, &e.params, a, LATER_GROUPS.with(|l| l.get()) * later); if let Some(k) = vectorcraft_doc::Scaling::factor(a) { crate::scale_effect(e, k); } diff --git a/crates/effects/src/tests/rasterfollow.rs b/crates/effects/src/tests/rasterfollow.rs index ae407fd438..3d3d81c172 100644 --- a/crates/effects/src/tests/rasterfollow.rs +++ b/crates/effects/src/tests/rasterfollow.rs @@ -580,6 +580,29 @@ fn nested_and_baked_directions_match_canvas() { } } +/// A member's light under two nested groups that each turn 30° turns 60° in all, rounded once: +/// Top Left, not Left (Top Left after the inner group's turn, then Left after the outer one's). +#[test] +fn nested_group_turns_round_the_light_once() { + let relief = || fx("sketch.basRelief", json!({"lightDirection": "top"})); + let thirty = || transform(json!({"rotate": 30})); + let inner = group(41, vec![square(42, vec![relief()]), fill_square(43, vec![relief()])], vec![thirty()]); + let outer = group(40, vec![inner], vec![thirty()]); + let art = crate::evaluate_container(None, &outer).unwrap(); + assert_eq!(lights_in(&art), vec![Light::TopLeft; 2]); + let mut d = Document::new(800.0, 800.0); + let layer = d.layers[0].id; + d.insert(Some(layer), 0, outer).unwrap(); + let baked = bake_document(&d).unwrap(); + for id in [42, 43] { + assert_eq!(lights_in(baked.node(NodeId(id)).unwrap()), vec![Light::TopLeft], "{id}"); + } + // Three groups make 90°: Left, not Bottom Left. + let three = group(44, vec![group(45, vec![group(46, vec![square(47, vec![relief()])], vec![thirty()])], vec![thirty()])], vec![thirty()]); + let art = crate::evaluate_container(None, &three).unwrap(); + assert_eq!(lights_in(&art), vec![Light::Left]); +} + /// A Transform effect after a 3D effect that makes copies or moves at random holds back the shadow /// before the 3D effect, as it does without the 3D effect. #[test] From 918105d945b4eb8232c881ee3ee10b491da7fd80 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 21:44:43 -0800 Subject: [PATCH 05/31] Recolor Artwork: Find shows the selected rows' art and dims the rest The Assign tab's Find button finds the colors of the selected rows in the art. While it is on, their art shows as the preview shows it (its current colors with Preview off) and the rest of the selected art, preserved colors included, shows a 25% tint of its current colors. A second click shows the art as before. Find records no undo step, and OK applies every row as it does with Find off. `findColors` is the dialog field. --- crates/ui-egui/src/dialogs/recolor.rs | 216 +++++++++++++++++++++++++- crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/gu.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + docs/mcp.md | 12 ++ docs/target-app-parity.md | 1 + 31 files changed, 253 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index d2bbeb3013..41049e6fbe 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -9,7 +9,9 @@ //! CMYK or Lab, and Tint when the new color is a spot color of the library), which edit the //! first selected row's new color (once they have, OK gives the art each new color in its own //! model), Merge and Separate, Randomize order or -//! saturation and brightness, Reset, the Method and Limit to Library (its folder button imports a +//! saturation and brightness, Find (with it on, the art of the selected rows shows as the preview +//! shows it, their current colors with Preview off, and the rest of the selected art shows its +//! current colors dimmed; a second click shows the art as before), Reset, the Method and Limit to Library (its folder button imports a //! library file and limits to it; a library's colours apply as its swatches: a spot colour stays a //! spot colour, and joins the document's swatches). Edit tab: a hue and //! saturation wheel with a marker per new colour (drag one; with linked handles they all turn and @@ -48,7 +50,8 @@ //! `globalAdjust` in every slider mode), `display` (the Edit tab's `smooth`, `segmented` or `bars`; //! unset: `smooth`), `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). Changing `colors`, a +//! `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`). use egui::{Rect, Sense, Ui, pos2, vec2}; @@ -161,7 +164,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { "preserveWhite": kept("preserveWhite", true), "preserveBlack": kept("preserveBlack", true), "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, "__art": art, "__assign": assign, "__newGroup": new_group, + "preview": true, THEME_PICKER: false, THEME_PICKS: [], WEIGHTS: null, FIND: false, "__art": art, "__assign": assign, "__newGroup": new_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,6 +218,8 @@ fn sync(app: &mut VectorcraftApp, d: &mut Dialog) { } snap(app, d, &mut rows); d.fields.insert("rows".into(), Value::Array(rows)); + // Find dims the preserved colors with the rows that aren't selected. + d.fields.insert(PRESERVED.into(), r["preserved"].clone()); d.fields.insert("__sel".into(), json!([])); // The new rows hold no slider edit. d.fields.remove(COMPS); @@ -586,6 +591,76 @@ fn apply_params(d: &Dialog) -> Value { p } +/// The Find button's field, and the tint of its current color that the art of the rows that +/// aren't selected shows while it is on (VectorCraft's own amount: [`Color::tinted`]). +const FIND: &str = "findColors"; +const FIND_DIM: f32 = 0.25; +/// The lighter tints, a percent apart, tried when a dimmed color is one a selected row lists. +const FIND_TRIES: usize = 20; +/// The colors of the art that the rows leave out (Preserve White, Black and Grays), as +/// `recolor.reduce` returned them. +const PRESERVED: &str = "__preserved"; + +/// 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 +/// color a selected row lists (a color a selected row also lists stays); +/// with Preview on, a second recolors the selected rows as [`apply_params`] would (the other rows +/// excluded, no color group rewritten). None otherwise, and when there is nothing to dim with +/// Preview off. OK still applies [`apply_params`]. +fn find_params(d: &Dialog) -> Option { + if !d.bool(FIND) || !d.bool("__art") || d.str("tab") == "edit" { + return None; + } + let rs = rows(d); + let sel: Vec = selection(d).into_iter().filter(|i| *i < rs.len()).collect(); + if sel.is_empty() { + return None; + } + let keys = |r: &Value| r["from"].as_array().cloned().unwrap_or_default(); + let found: Vec = sel.iter().flat_map(|&i| keys(&rs[i])).collect(); + // A dimmed color must not be one the second step recolors (by its key, or by its hex as a + // "#rrggbb" entry matches): the nearest lighter tint that is none of them is taken instead. + let found_hex: Vec = found.iter().filter_map(color_value).map(|c| c.to_hex()).collect(); + let dimmed = |c: Color| { + (0..FIND_TRIES) + .map(|n| c.tinted(FIND_DIM - n as f32 * 0.01)) + .find(|t| !found.contains(&key(t)) && !found_hex.contains(&t.to_hex())) + .map(|t| key(&t)) + }; + // The current colors of the rows that aren't selected, and the preserved colors. + let preserved = d.fields.get(PRESERVED).and_then(Value::as_array).cloned().unwrap_or_default(); + let others = rs.iter().enumerate().filter(|(i, _)| !sel.contains(i)).flat_map(|(_, r)| keys(r)).chain(preserved); + let mut dim = serde_json::Map::new(); + // A color shown as the same hex as one a selected row lists stays: a "#rrggbb" entry on either + // side matches both. + let listed = |k: &Value| found.contains(k) || color_value(k).is_some_and(|c| found_hex.contains(&c.to_hex())); + for k in others.filter(|k| !listed(k)) { + if let (Some(to), Some(name)) = (color_value(&k).and_then(dimmed), k.as_str()) { + dim.insert(name.to_string(), to); + } + } + let mut commands = vec![]; + if !dim.is_empty() { + commands.push(json!({"command": CMD, "params": {"map": dim}})); + } + if d.bool("preview") { + let mut p = apply_params(d); + let mut only = rs; + for (_, r) in only.iter_mut().enumerate().filter(|(i, _)| !sel.contains(i)) { + r["exclude"] = json!(true); + } + p["map"] = Value::Array(only); + if let Some(p) = p.as_object_mut() { + for k in ["group", "groupColors", "rename"] { + p.remove(k); + } + } + commands.push(json!({"command": CMD, "params": p})); + } + (!commands.is_empty()).then(|| json!({"commands": commands})) +} + fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { sync(app, d); sync_theme(app, d); @@ -646,7 +721,15 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { } sync(app, d); if d.bool("__art") { - form::preview(app, ui, d, "Recolor Artwork", CMD, apply_params(d)); + match find_params(d) { + // Find shows the art so with Preview off too. + Some(p) => { + ui.add_space(8.0); + form::preview_check(ui, d); + form::preview_now(app, d, "Recolor Artwork", "command.batch", p); + } + None => form::preview(app, ui, d, "Recolor Artwork", CMD, apply_params(d)), + } } if let Some(c) = pick.and_then(|i| Some((i, to_color(rows(d).get(i)?)?))) { *d = super::color_picker::over_recolor(d, c.1, c.0); @@ -858,6 +941,10 @@ fn assign_tab(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut } } } + let finding = d.bool(FIND); + if widgets::icon_button_enabled(ui, "search", tl!("Find the selected colors in the artwork"), finding, d.bool("__art"), 24.0).clicked() { + d.fields.insert(FIND.into(), json!(!finding)); + } if widgets::icon_button(ui, "rotate-ccw", tl!("Reset the rows to the artwork's colors"), false, 24.0).clicked() { d.fields.remove("__reduced"); d.fields.remove(COMPS); @@ -2020,6 +2107,127 @@ mod tests { assert_eq!(new_colors(&app), [json!("rgb 0 255 0"), json!("rgb 255 255 0")]); } + /// Find previews nothing of its own while it is off, on the Edit tab, without art or without a + /// selected row. On, a first `recolor.apply` dims each current color of the other rows (a color + /// a selected row also lists stays), and with Preview on a second recolors the selected rows + /// alone, without rewriting the color group. + #[test] + fn find_dims_the_colors_of_the_rows_not_selected() { + let mut d = Dialog::new( + KIND, + json!({"rows": rows(), "__art": true, "preview": true, "method": "exact", "limitTo": "", "group": "G", "groupName": "H", "__sel": [0]}), + ); + assert_eq!(find_params(&d), None, "off"); + d.fields.insert(FIND.into(), json!(true)); + let dim = |k: &str| key(&color_value(&json!(k)).unwrap().tinted(FIND_DIM)); + let p = find_params(&d).expect("on"); + let cmds = p["commands"].as_array().unwrap(); + assert_eq!(cmds.len(), 2); + assert_eq!(cmds[0]["command"], CMD); + assert_eq!( + cmds[0]["params"]["map"], + json!({"rgb 0 0 255": dim("rgb 0 0 255"), "rgb 0 0 128": dim("rgb 0 0 128"), "rgb 0 255 0": dim("rgb 0 255 0")}) + ); + assert_eq!(dim("rgb 0 0 255"), json!("rgb 191.25 191.25 255"), "a quarter of the color, the rest white"); + let second = &cmds[1]["params"]; + assert_eq!(second["map"][0], rows()[0], "the selected row recolors as it would"); + assert_eq!((second["map"][1]["exclude"].clone(), second["map"][2]["exclude"].clone()), (json!(true), json!(true))); + assert!(second.get("group").is_none() && second.get("rename").is_none(), "{second}"); + // A color that a selected row lists as a hex (or with another key of the same hex) stays. + let mut e = d.clone(); + let mut rs = rows(); + rs[0]["from"] = json!(["#0000ff"]); + e.fields.insert("rows".into(), json!(rs)); + let map = find_params(&e).unwrap()["commands"][0]["params"]["map"].clone(); + assert!(map.get("rgb 0 0 255").is_none() && map.get("rgb 0 0 128").is_some(), "{map}"); + // The preserved colors dim too. + let mut e = d.clone(); + e.fields.insert(PRESERVED.into(), json!(["rgb 0 0 0"])); + assert_eq!(find_params(&e).unwrap()["commands"][0]["params"]["map"]["rgb 0 0 0"], dim("rgb 0 0 0")); + // A color a selected row lists is not dimmed; with Preview off only the dimming runs. + let mut rs = rows(); + rs[2]["from"] = json!(["rgb 0 255 0", "rgb 255 0 0"]); + d.fields.insert("rows".into(), json!(rs)); + d.fields.insert("preview".into(), json!(false)); + let p = find_params(&d).unwrap(); + assert_eq!(p["commands"].as_array().map(Vec::len), Some(1)); + assert!(p["commands"][0]["params"]["map"].get("rgb 255 0 0").is_none(), "{p}"); + // A dimmed color that a selected row lists would be recolored with it: a lighter tint is taken. + let mut rs = rows(); + rs[0]["from"] = json!(["rgb 255 0 0", "rgb 191 191 255"]); + d.fields.insert("rows".into(), json!(rs)); + let p = find_params(&d).unwrap(); + let to = color_value(&p["commands"][0]["params"]["map"]["rgb 0 0 255"]).unwrap(); + assert_eq!(to.to_hex(), "#c2c2ff", "{p}"); + // Every row selected with Preview off: nothing to show. + d.fields.insert("__sel".into(), json!([0, 1, 2])); + assert_eq!(find_params(&d), None); + for (k, v) in [("__sel", json!([])), ("__sel", json!([7])), ("tab", json!("edit")), ("__art", json!(false))] { + let mut e = d.clone(); + e.fields.insert("preview".into(), json!(true)); + e.fields.insert("__sel".into(), json!([0])); + e.fields.insert(k.into(), v.clone()); + assert_eq!(find_params(&e), None, "{k}: {v}"); + } + } + + /// In the dialog, Find with the red art's row selected shows the red art's new color and the + /// blue art dimmed, with Preview off the red art's own color; off again, the art shows as the + /// preview has it. Cancel leaves the art as it was with no undo step, and OK with Find on + /// applies the rows to all the art, as one undo step. + #[test] + fn find_shows_the_selected_rows_art_and_dims_the_rest() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + let [red, blue] = theme_setup(&mut app, &ctx); + let undo = app.session.doc().unwrap().history.undo.len(); + let set = |app: &mut VectorcraftApp, k: &str, v: Value| { + app.ui.dialog.as_mut().unwrap().fields.insert(k.into(), v); + }; + let rs = json!([{"from": ["rgb 255 0 0"], "to": "rgb 0 255 0"}, {"from": ["rgb 0 0 255"], "to": "rgb 255 255 0"}]); + set(&mut app, "rows", rs.clone()); + set(&mut app, "__sel", json!([0])); + frame(&mut app, &ctx, 0.1, vec![], 0); + let fills = |app: &VectorcraftApp| (fill_hex(app, red), fill_hex(app, blue)); + assert_eq!(fills(&app), ("#00ff00".into(), "#ffff00".into()), "off: the preview"); + set(&mut app, FIND, json!(true)); + frame(&mut app, &ctx, 0.2, vec![], 0); + assert_eq!(fills(&app), ("#00ff00".into(), "#bfbfff".into()), "on: the other art dimmed"); + set(&mut app, "preview", json!(false)); + frame(&mut app, &ctx, 0.3, vec![], 0); + assert_eq!(fills(&app), ("#ff0000".into(), "#bfbfff".into()), "Preview off: the current colors"); + set(&mut app, "__sel", json!([1])); + frame(&mut app, &ctx, 0.4, vec![], 0); + assert_eq!(fills(&app), ("#ffbfbf".into(), "#0000ff".into()), "the other row selected"); + set(&mut app, FIND, json!(false)); + frame(&mut app, &ctx, 0.5, vec![], 0); + assert_eq!(fills(&app), ("#ff0000".into(), "#0000ff".into()), "off with Preview off: the art as it is"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo, "Find records no undo step"); + set(&mut app, FIND, json!(true)); + frame(&mut app, &ctx, 0.6, vec![], 0); + crate::dialogs::cancel(&mut app); + assert!(app.ui.dialog.is_none()); + assert_eq!(fills(&app), ("#ff0000".into(), "#0000ff".into()), "Cancel: the art as it was"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); + // A black square joins the selection: Preserve Black leaves it out of the rows. + let black = square(&mut app, 70.0, "#000000"); + let undo = app.session.doc().unwrap().history.undo.len(); + app.run("select.set", json!({"ids": [red, blue, black]})).unwrap(); + app.run("ui.recolorDialog", json!({})).unwrap(); + set(&mut app, "method", json!(Method::Exact.id())); + frame(&mut app, &ctx, 1.0, vec![], 0); + set(&mut app, "rows", rs); + set(&mut app, "__sel", json!([0])); + set(&mut app, FIND, json!(true)); + frame(&mut app, &ctx, 1.1, vec![], 0); + assert_eq!(fills(&app), ("#00ff00".into(), "#bfbfff".into())); + assert_eq!(fill_hex(&app, black), "#bfbfbf", "the preserved black dims too"); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(fills(&app), ("#00ff00".into(), "#ffff00".into()), "OK applies the rows to all the art"); + assert_eq!(fill_hex(&app, black), "#000000", "and keeps the preserved black"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); + } + /// In a CMYK document colors opened alone are saved as a new color group in their own model. #[test] fn a_new_group_from_colors_keeps_their_model_in_a_cmyk_document() { diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 948b295e17..1ff12356a6 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1446,6 +1446,7 @@ font-technology Variable Променливи Show smooth color wheel Показване на плавно цветово колело Show segmented color wheel Показване на сегментирано цветово колело Show color bars Показване на цветни ленти + Find the selected colors in the artwork Намиране на избраните цветове в илюстрацията Harmony Sets Набори от хармонии Height Височина Height: Височина: diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index f8d6fa263b..d0c4c61ba7 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -2881,6 +2881,7 @@ digits Malayalam Malajalam Show smooth color wheel Prikaži glatki kotač boja Show segmented color wheel Prikaži segmentirani kotač boja Show color bars Prikaži trake boja + Find the selected colors in the artwork Pronađi odabrane boje u crtežu Harmony Rules Pravila harmonije Keep this row's colors (exclude) Zadrži boje ovog reda (isključi) Limit to Library: Ograniči na biblioteku: diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 3ed3ca8331..3918a384e9 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1977,6 +1977,7 @@ digits Malayalam Malaiàlam Show smooth color wheel Mostra la roda de color contínua Show segmented color wheel Mostra la roda de color segmentada Show color bars Mostra les barres de color + Find the selected colors in the artwork Troba els colors seleccionats a l’obra Harmony Sets Conjunts d’harmonia HDTV 1080p HDTV 1080p HDTV 720p HDTV 720p diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 161e235c56..117dec883c 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -2917,6 +2917,7 @@ digits Malayalam Malajálamské Show smooth color wheel Zobrazit plynulé barevné kolo Show segmented color wheel Zobrazit segmentované barevné kolo Show color bars Zobrazit barevné pruhy + Find the selected colors in the artwork Najít vybrané barvy v kresbě Harmony Rules Pravidla harmonie Keep this row's colors (exclude) Ponechat barvy tohoto řádku (vyloučit) Limit to Library: Omezit na knihovnu: diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index fd0b7c042e..71bbea2027 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -3308,6 +3308,7 @@ digits Malayalam Malayalam Show smooth color wheel Vis glat farvehjul Show segmented color wheel Vis segmenteret farvehjul Show color bars Vis farvebjælker + Find the selected colors in the artwork Find de valgte farver i grafikken Harmony Rules Harmoniregler Keep this row's colors (exclude) Behold farverne i denne række (ekskludér) Limit to Library: Begræns til bibliotek: diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 2a5f32a5d9..58dbb1d623 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1491,6 +1491,7 @@ file-filter Templates Vorlagen Show smooth color wheel Stufenlosen Farbkreis anzeigen Show segmented color wheel Segmentierten Farbkreis anzeigen Show color bars Farbbalken anzeigen + Find the selected colors in the artwork Ausgewählte Farben in der Grafik finden Harmony Sets Harmoniesätze Height Höhe Height: Höhe: diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index b1b7b4d039..63bd2dfc4d 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1421,6 +1421,7 @@ font-technology Variable Μεταβλητές Show smooth color wheel Εμφάνιση ομαλού χρωματικού τροχού Show segmented color wheel Εμφάνιση τμηματοποιημένου χρωματικού τροχού Show color bars Εμφάνιση χρωματικών ράβδων + Find the selected colors in the artwork Εύρεση των επιλεγμένων χρωμάτων στο σχέδιο Harmony Sets Σύνολα χρωματικής αρμονίας Height Ύψος Height: Ύψος: diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 5b3c675f7b..d7994eb6fc 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1500,6 +1500,7 @@ font-technology Variable Variables Show smooth color wheel Mostrar rueda de color continua Show segmented color wheel Mostrar rueda de color segmentada Show color bars Mostrar barras de color + Find the selected colors in the artwork Buscar los colores seleccionados en la ilustración Harmony Sets Conjuntos de armonía Height Altura Height: Altura: diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index e77a617c52..824ad48ee0 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -2861,6 +2861,7 @@ digits Malayalam Malajalam Show smooth color wheel Näytä liukuva väriympyrä Show segmented color wheel Näytä segmentoitu väriympyrä Show color bars Näytä väripalkit + Find the selected colors in the artwork Etsi valitut värit kuvituksesta Harmony Rules Harmoniasäännöt Keep this row's colors (exclude) Säilytä tämän rivin värit (jätä pois) Limit to Library: Rajoita kirjastoon: diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 2762d2a954..598185ed18 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1493,6 +1493,7 @@ font-technology Variable Variables Show smooth color wheel Afficher la roue chromatique continue Show segmented color wheel Afficher la roue chromatique segmentée Show color bars Afficher les barres de couleur + Find the selected colors in the artwork Rechercher les couleurs sélectionnées dans l’illustration Harmony Rules: Règles d’harmonie : Harmony Sets Ensembles d’harmonies Height Hauteur diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 1c96900b2b..2296f70318 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -3504,6 +3504,7 @@ Show all plates બધી પ્લેટ બતાવો Show axis અક્ષ બતાવો Show color bars રંગ બાર બતાવો + Find the selected colors in the artwork પસંદ કરેલા રંગો આર્ટવર્કમાં શોધો Show handles when multiple anchors are selected બહુવિધ એન્કર પસંદ હોય ત્યારે હૅન્ડલ બતાવો Show in Folder ફોલ્ડરમાં બતાવો Show its progress, see Cancel and write log lines તેની પ્રગતિ બતાવવી, રદ કરવાની વિનંતી જોવી અને લૉગ લાઇનો લખવી diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 548f961f51..401f1fe1f8 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -4590,6 +4590,7 @@ antiAlias Sharp शार्प Show Center Mark शो सेंटर मार्क Show Code कोड दिखाएं Show color bars रंग सलाखों दिखाएँ + Find the selected colors in the artwork चयनित रंगों को आर्टवर्क में खोजें Show Color Groups रंग समूह दिखाएँ Show Color Swatches रंग स्वॉचेस दिखाएँ Show Corner Widget शो कॉर्नर विजेट diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 200b45d1b1..f20f65f424 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1899,6 +1899,7 @@ file-filter Templates Sablonok Show smooth color wheel Folytonos színkör megjelenítése Show segmented color wheel Szegmentált színkör megjelenítése Show color bars Színsávok megjelenítése + Find the selected colors in the artwork A kijelölt színek keresése a grafikában Harmony Sets Harmóniakészletek HDTV 1080p HDTV 1080p HDTV 720p HDTV 720p diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index f3dcca3874..235a98c4e5 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -2699,6 +2699,7 @@ digits Malayalam Malayalam Show smooth color wheel Tampilkan roda warna halus Show segmented color wheel Tampilkan roda warna bersegmen Show color bars Tampilkan bilah warna + Find the selected colors in the artwork Temukan warna yang dipilih di karya seni Harmony Rules Aturan harmoni Keep this row's colors (exclude) Pertahankan warna baris ini (kecualikan) Limit to Library: Batasi ke pustaka: diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 90ec79404c..ea2007eb43 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1521,6 +1521,7 @@ file-filter Templates Modelli Show smooth color wheel Mostra ruota dei colori continua Show segmented color wheel Mostra ruota dei colori segmentata Show color bars Mostra barre di colore + Find the selected colors in the artwork Trova i colori selezionati nella grafica Harmony Sets Gruppi di armonia Height Altezza Height: Altezza: diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index d98acfa22d..1b41557a24 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1925,6 +1925,7 @@ antiAlias Sharp シャープ Show smooth color wheel 滑らかなカラーホイールを表示 Show segmented color wheel 分割カラーホイールを表示 Show color bars カラーバーを表示 + Find the selected colors in the artwork 選択したカラーをアートワーク内で検索 Height 高さ Height: 高さ: Help › Search Commands… ヘルプ › コマンドを検索… diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 794e5454a9..32cf861c37 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -2616,6 +2616,7 @@ digits Malayalam მალაიალამური Show smooth color wheel გლუვი ფერთა წრის ჩვენება Show segmented color wheel სეგმენტირებული ფერთა წრის ჩვენება Show color bars ფერთა ზოლების ჩვენება + Find the selected colors in the artwork არჩეული ფერების პოვნა ნახატში Keep this row's colors (exclude) ამ სტრიქონის ფერების შენარჩუნება (გამორიცხვა) Limit to Library: ბიბლიოთეკით შეზღუდვა: Link harmony colors ჰარმონიის ფერების დაკავშირება diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index bb8676df71..98a996179d 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1915,6 +1915,7 @@ antiAlias Sharp 날카롭게 Show smooth color wheel 부드러운 색상환 표시 Show segmented color wheel 분할 색상환 표시 Show color bars 색상 막대 표시 + Find the selected colors in the artwork 선택한 색상을 아트웍에서 찾기 Height 높이 Height: 높이: Help › Search Commands… 도움말 › 명령 검색… diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index a597a03fd0..0d8d9be9b5 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -3217,6 +3217,7 @@ digits Malayalam Malayalam Show smooth color wheel Vloeiend kleurenwiel tonen Show segmented color wheel Gesegmenteerd kleurenwiel tonen Show color bars Kleurbalken tonen + Find the selected colors in the artwork De geselecteerde kleuren zoeken in de artwork Harmony Rules Harmonieregels Keep this row's colors (exclude) De kleuren van deze rij behouden (uitsluiten) Limit to Library: Beperken tot bibliotheek: diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 99ee2080b8..0d964a5026 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -2827,6 +2827,7 @@ digits Malayalam Malajalam Show smooth color wheel Pokaż płynne koło kolorów Show segmented color wheel Pokaż segmentowe koło kolorów Show color bars Pokaż paski kolorów + Find the selected colors in the artwork Znajdź zaznaczone kolory w kompozycji Keep this row's colors (exclude) Zachowaj kolory tego wiersza (wyklucz) Limit to Library: Ogranicz do biblioteki: Link harmony colors Połącz kolory harmonii diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 677c8e460f..5181b0eb13 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -1323,6 +1323,7 @@ antiAlias Sharp Nítido Show smooth color wheel Mostrar roda de cores contínua Show segmented color wheel Mostrar roda de cores segmentada Show color bars Mostrar barras de cores + Find the selected colors in the artwork Localizar as cores selecionadas na arte Harmony Sets Conjuntos de Harmonia Height Altura Height: Altura: diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 106343cddd..f2da3f7c42 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1510,6 +1510,7 @@ file-filter Templates Шаблоны Show smooth color wheel Показать плавный цветовой круг Show segmented color wheel Показать сегментированный цветовой круг Show color bars Показать цветовые полосы + Find the selected colors in the artwork Найти выбранные цвета в рисунке Harmony Sets Наборы гармонии Height Высота Height: Высота: diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index cc854aa362..a739583ab1 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1459,6 +1459,7 @@ font-technology Variable Variabla Show smooth color wheel Visa steglöst färghjul Show segmented color wheel Visa segmenterat färghjul Show color bars Visa färgstaplar + Find the selected colors in the artwork Hitta de markerade färgerna i teckningen Harmony Sets Harmoniuppsättningar Height Höjd Height: Höjd: diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index f2888a30f0..9db264343f 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1422,6 +1422,7 @@ font-technology Variable Değişken Show smooth color wheel Kesintisiz renk tekerleğini göster Show segmented color wheel Bölümlü renk tekerleğini göster Show color bars Renk çubuklarını göster + Find the selected colors in the artwork Seçili renkleri resimde bul Harmony Sets Armoni Setleri Height Yükseklik Height: Yükseklik: diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 411b2c3baf..2e09a8f0c8 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1515,6 +1515,7 @@ file-filter Templates Шаблони Show smooth color wheel Показати плавне колірне коло Show segmented color wheel Показати сегментоване колірне коло Show color bars Показати колірні смуги + Find the selected colors in the artwork Знайти вибрані кольори в малюнку Harmony Sets Набори гармонії Height Висота Height: Висота: diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 1460910197..5be6d9174c 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1746,6 +1746,7 @@ file-filter Templates Mẫu Show smooth color wheel Hiện bánh xe màu liền mạch Show segmented color wheel Hiện bánh xe màu phân đoạn Show color bars Hiện các thanh màu + Find the selected colors in the artwork Tìm các màu đã chọn trong tác phẩm Harmony Sets Bộ hài hòa màu Height Chiều cao Height: Chiều cao: diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 3fe2f9e009..e7408947c8 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1449,6 +1449,7 @@ file-filter Templates 模板 Show smooth color wheel 显示平滑色轮 Show segmented color wheel 显示分段色轮 Show color bars 显示颜色条 + Find the selected colors in the artwork 在图稿中查找所选颜色 Harmony Sets 色彩调和组 Height 高度 Height: 高度: diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index ab7f9d9dd2..167777d864 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1486,6 +1486,7 @@ file-filter Templates 範本 Show smooth color wheel 顯示平滑色輪 Show segmented color wheel 顯示分段色輪 Show color bars 顯示顏色條 + Find the selected colors in the artwork 在圖稿中尋找所選顏色 Harmony Sets 色彩調和組 Height 高度 Height: 高度: diff --git a/docs/mcp.md b/docs/mcp.md index 8ca4121032..0d3bd96e65 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4408,6 +4408,18 @@ of the rows that are not excluded, in row order, and Save Prominent Colors saves {"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]}}} ``` +The Assign tab's Find button (the dialog field `findColors`) 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 and rows are selected, the art of those rows shows as the preview shows it (its current colors with +Preview off), and the rest of the selected art shows dimmed; a second click shows the art as before +([archived help, Recolor Artwork](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=149)). +As VectorCraft's own rules, a dimmed color is a 25% tint of its current color, or the nearest lighter tint (in steps +of 1%) when that tint is a color a selected row lists (`recolor.apply` gives each current color of the other rows +and the preserved colors that tint, then recolors the selected rows), a color that a selected row also lists is not +dimmed, so art that mixes colors dims only its other colors, and nothing is dimmed on the Edit tab or with no row +selected. Find changes only what the canvas shows: it records no undo step, Cancel leaves the art as it was, and OK +applies every row to the art as it does with Find off. + The `recolor.*` commands refuse parameters of the wrong form. A `limitTo` or `method` that is not a string gets the error for an unknown library or method. Other wrong-form parameters get an error that names them. `includeImages`, `includePatterns`, a row's `exclude`, `order`, `saturationBrightness` and the `white`, `black` and diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f4424700be..ccb1198959 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1591,6 +1591,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Document Color Mode for effects and graphs:** File › Document Color Mode and `document.open {colorMode}` convert the colors of effects (Drop Shadow, Inner Glow, Outer Glow and the other effects with a color, on objects, their fills and strokes and in graphic styles) and the series paints and label styles that a graph keeps, so a graph drawn again from new data keeps the converted colors; File › Document Color Mode also converts the fill and stroke that new art takes. Undo restores the original new-art fill and stroke and Redo applies the conversion again. - **Recolor Artwork layout (#3416):** the Edit chip list uses the modal scroll helper and its actual remaining height; the tab's minimum-height space scrolls with the chips. `tests_recolor` covers 5/20/200/400 colors, window resizing, 100/125/150/200% UI scaling, scrolling to and editing the final chip, Preview, Cancel, Confirm and Undo, alongside the existing #1733 drag regressions. Scores and estimates unchanged. - **Recolor Artwork Edit displays:** buttons beside the Edit tab's wheel show the colors on a smooth color wheel, a segmented color wheel or as color bars ([Edit colors using Recolor Artwork](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/edit-colors-using-edit-colors-dialog.html)). The segmented wheel draws 24 hues by 5 saturations as solid patches, and its markers move freely as on the smooth wheel. The bars show one solid bar per recolored color in row order: a click selects a bar for the color sliders, and a drag moves its row without changing a color ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html)). The dialog opens on the smooth wheel; `display` (`smooth`, `segmented`, `bars`) is the dialog field. `tests_recolor` covers switching, the dialog height, segmented dragging and Brightness, and bar selection, editing, reordering, scrolling, Preview, Cancel and OK. 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. - **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. - **Working RGB numeric controls:** the Color panel and Color Picker read RGB, HSB, hex and Web Safe RGB values in the active working RGB space. Editing one RGB channel preserves the other native channels, including colors outside display sRGB. Regressions cover sRGB, Display P3, Wide Gamut RGB and ProPhoto RGB, picker initialization, native numeric round trips, and a slider click with one Undo step. Scores and estimates unchanged. From 0c1ddbd90b8ea72c02fc9bf8aeaf2aae57f296b1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 22:46:16 -0800 Subject: [PATCH 06/31] Recolor Artwork: Find dims a color that only shares a selected key's hex Find kept every color shown as the same hex as a color a selected row lists, so art in another row whose key differs only past the hex (for example rgb 191.25 191.25 255 next to a selected rgb 191 191 255) stayed undimmed, although recolor.apply recolors only the exact key. A color now stays only when its key matches, or when either entry is a "#rrggbb" one. Keys are compared as recolor.apply parses them, whatever their case or spacing. --- crates/ui-egui/src/dialogs/recolor.rs | 49 +++++++++++++++++++++++---- 1 file changed, 43 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index 41049e6fbe..4438d59454 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -601,6 +601,18 @@ const FIND_TRIES: usize = 20; /// `recolor.reduce` returned them. const PRESERVED: &str = "__preserved"; +/// A row's current color as `recolor.apply` matches it: an exact color (its key, parsed whatever +/// its case or spacing), or `Err` with the hex of a "#rrggbb" entry, which matches every color +/// shown as that hex. +type FindEntry = Result; + +fn find_entry(k: &Value) -> Option { + match k.as_str() { + Some(s) => ColorKey::parse(s).map(Ok).or_else(|| color_value(k).map(|c| Err(c.to_hex()))), + None => color_value(k).map(|c| Ok(ColorKey::of(&c))), + } +} + /// 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 @@ -619,22 +631,30 @@ fn find_params(d: &Dialog) -> Option { } let keys = |r: &Value| r["from"].as_array().cloned().unwrap_or_default(); let found: Vec = sel.iter().flat_map(|&i| keys(&rs[i])).collect(); + // The selected rows' entries as `recolor.apply` reads them: exact colors and "#rrggbb" ones. + let found: Vec = found.iter().filter_map(find_entry).collect(); + let found_keys: Vec = found.iter().filter_map(|e| e.as_ref().ok().copied()).collect(); + let found_hex_entries: Vec = found.iter().filter_map(|e| e.as_ref().err().cloned()).collect(); + let found_hex: Vec = found.iter().map(|e| e.as_ref().map_or_else(Clone::clone, |k| k.color().to_hex())).collect(); // A dimmed color must not be one the second step recolors (by its key, or by its hex as a // "#rrggbb" entry matches): the nearest lighter tint that is none of them is taken instead. - let found_hex: Vec = found.iter().filter_map(color_value).map(|c| c.to_hex()).collect(); let dimmed = |c: Color| { (0..FIND_TRIES) .map(|n| c.tinted(FIND_DIM - n as f32 * 0.01)) - .find(|t| !found.contains(&key(t)) && !found_hex.contains(&t.to_hex())) + .find(|t| !found_keys.contains(&ColorKey::of(t)) && !found_hex.contains(&t.to_hex())) .map(|t| key(&t)) }; // The current colors of the rows that aren't selected, and the preserved colors. let preserved = d.fields.get(PRESERVED).and_then(Value::as_array).cloned().unwrap_or_default(); let others = rs.iter().enumerate().filter(|(i, _)| !sel.contains(i)).flat_map(|(_, r)| keys(r)).chain(preserved); let mut dim = serde_json::Map::new(); - // A color shown as the same hex as one a selected row lists stays: a "#rrggbb" entry on either - // side matches both. - let listed = |k: &Value| found.contains(k) || color_value(k).is_some_and(|c| found_hex.contains(&c.to_hex())); + // A color a selected row lists stays, and so does one shown as the same hex when either entry is + // "#rrggbb" (it matches both). Two keys of the same hex are separate colors. + let listed = |k: &Value| match find_entry(k) { + Some(Ok(key)) => found_keys.contains(&key) || found_hex_entries.contains(&key.color().to_hex()), + Some(Err(hex)) => found_hex.contains(&hex), + None => false, + }; for k in others.filter(|k| !listed(k)) { if let (Some(to), Some(name)) = (color_value(&k).and_then(dimmed), k.as_str()) { dim.insert(name.to_string(), to); @@ -2133,13 +2153,30 @@ mod tests { assert_eq!(second["map"][0], rows()[0], "the selected row recolors as it would"); assert_eq!((second["map"][1]["exclude"].clone(), second["map"][2]["exclude"].clone()), (json!(true), json!(true))); assert!(second.get("group").is_none() && second.get("rename").is_none(), "{second}"); - // A color that a selected row lists as a hex (or with another key of the same hex) stays. + // A color that a selected row lists as a hex stays. let mut e = d.clone(); let mut rs = rows(); rs[0]["from"] = json!(["#0000ff"]); e.fields.insert("rows".into(), json!(rs)); let map = find_params(&e).unwrap()["commands"][0]["params"]["map"].clone(); assert!(map.get("rgb 0 0 255").is_none() && map.get("rgb 0 0 128").is_some(), "{map}"); + // A color a selected row lists by its key keeps only that color: another key of the same hex + // dims, and a hex entry of it stays (it would dim the selected color too). + let mut e = d.clone(); + let mut rs = rows(); + rs[0]["from"] = json!(["rgb 191 191 255"]); + rs[1]["from"] = json!(["rgb 191.25 191.25 255", "#bfbfff"]); + e.fields.insert("rows".into(), json!(rs)); + let map = find_params(&e).unwrap()["commands"][0]["params"]["map"].clone(); + assert!(map.get("rgb 191.25 191.25 255").is_some() && map.get("#bfbfff").is_none(), "{map}"); + // A key is read whatever its case or spacing, as `recolor.apply` reads it. + let mut e = d.clone(); + let mut rs = rows(); + rs[0]["from"] = json!(["RGB 191 191 255"]); + rs[1]["from"] = json!(["rgb 191 191 255", "rgb 0 0 128"]); + e.fields.insert("rows".into(), json!(rs)); + let map = find_params(&e).unwrap()["commands"][0]["params"]["map"].clone(); + assert!(map.get("rgb 191 191 255").is_none() && map.get("rgb 0 0 128").is_some(), "{map}"); // The preserved colors dim too. let mut e = d.clone(); e.fields.insert(PRESERVED.into(), json!(["rgb 0 0 0"])); From 0384726c7aa8170ab2120d3cfc23058080693900 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 22:54:10 -0800 Subject: [PATCH 07/31] Type: Adjust Horizontal and Vertical Diacritic Position move marks off their letters The Character panel shows Adjust Horizontal and Adjust Vertical Diacritic Position with the Middle Eastern options. text.setFormat and text.setRangeStyle take diacriticHorizontal and diacriticVertical, in thousandths of an em from -1000 to 1000. Positive values move the characters' mark glyphs (GDEF class 3) right and up, and the letters keep their places. An Arabic harakat or a Hebrew point styled apart from its letter takes its own values without splitting the shaping cluster. Character styles and Character Style Options carry both values. They are saved only when set, and SVG export writes such type as outlines. Docs: docs/mcp.md, docs/type-parity.md, docs/target-app-parity.md. --- crates/doc/src/text.rs | 4 +- crates/doc/src/text/char_style.rs | 24 +++- crates/doc/src/text/object.rs | 4 + crates/doc/src/text/tests.rs | 36 ++++++ crates/engine/src/cmd/panelcmds.rs | 8 +- crates/engine/src/cmd/textedit.rs | 28 ++++- crates/engine/src/cmd/textstyles.rs | 15 ++- crates/engine/src/cmd/textstyles/tests.rs | 5 +- crates/engine/src/cmd/typecmd/area_tests.rs | 60 ++++++++++ crates/svg/src/export/text.rs | 6 +- crates/svg/tests/it/text_layout.rs | 13 +++ crates/text/src/harakat.rs | 41 ++++++- crates/text/src/shape.rs | 47 ++++++-- crates/text/src/tests/harakat.rs | 72 ++++++++++++ .../ui-egui/src/dialogs/char_style_options.rs | 108 +++++++++++++++++- crates/ui-egui/src/i18n/bg.tsv | 2 + crates/ui-egui/src/i18n/bs.tsv | 2 + crates/ui-egui/src/i18n/ca.tsv | 2 + crates/ui-egui/src/i18n/cs.tsv | 2 + crates/ui-egui/src/i18n/da.tsv | 2 + crates/ui-egui/src/i18n/de.tsv | 2 + crates/ui-egui/src/i18n/el.tsv | 2 + crates/ui-egui/src/i18n/es.tsv | 2 + crates/ui-egui/src/i18n/fi.tsv | 2 + crates/ui-egui/src/i18n/fr.tsv | 2 + crates/ui-egui/src/i18n/gu.tsv | 2 + crates/ui-egui/src/i18n/hi.tsv | 2 + crates/ui-egui/src/i18n/hu.tsv | 2 + crates/ui-egui/src/i18n/id.tsv | 2 + crates/ui-egui/src/i18n/it.tsv | 2 + crates/ui-egui/src/i18n/ja.tsv | 2 + crates/ui-egui/src/i18n/ka.tsv | 2 + crates/ui-egui/src/i18n/ko.tsv | 2 + crates/ui-egui/src/i18n/nl.tsv | 2 + crates/ui-egui/src/i18n/pl.tsv | 2 + crates/ui-egui/src/i18n/pt-br.tsv | 2 + crates/ui-egui/src/i18n/ru.tsv | 2 + crates/ui-egui/src/i18n/sv.tsv | 2 + crates/ui-egui/src/i18n/tr.tsv | 2 + crates/ui-egui/src/i18n/uk.tsv | 2 + crates/ui-egui/src/i18n/vi.tsv | 2 + crates/ui-egui/src/i18n/zh-hans.tsv | 2 + crates/ui-egui/src/i18n/zh-hant.tsv | 2 + crates/ui-egui/src/panels/character.rs | 33 +++++- crates/ui-egui/src/panels/character/tests.rs | 60 +++++++++- docs/mcp.md | 30 ++++- docs/target-app-parity.md | 1 + docs/type-parity.md | 1 + 48 files changed, 612 insertions(+), 40 deletions(-) diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs index 06b71f8fc8..f149cf6b30 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -18,8 +18,8 @@ mod wrap; pub use area::{AreaFit, AreaOptions, PathAlign, PathEffect, TextFlow, TextWrap, VerticalAlign, WrapShape}; use char_style::yes; pub use char_style::{ - CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, GlyphChoice, GlyphForm, MAX_AKI, MAX_TSUME, MAX_WARICHU_GAP, ScriptMetrics, - WARICHU_LINES, WARICHU_SCALE, WarichuAlign, + CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, GlyphChoice, GlyphForm, MAX_AKI, MAX_DIACRITIC_POSITION, MAX_TSUME, + MAX_WARICHU_GAP, ScriptMetrics, WARICHU_LINES, WARICHU_SCALE, WarichuAlign, }; pub use composite::{ COMPOSITE_BASELINE, COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX, COMPOSITE_SCALE, COMPOSITE_SIZE, CharClass, CompositeFont, CompositePart, diff --git a/crates/doc/src/text/char_style.rs b/crates/doc/src/text/char_style.rs index 97f744dba8..30883ac95b 100644 --- a/crates/doc/src/text/char_style.rs +++ b/crates/doc/src/text/char_style.rs @@ -180,6 +180,18 @@ pub struct CharStyle { /// these characters are drawn in, whatever digits were typed. #[serde(default, skip_serializing_if = "crate::skip::is_default")] pub digits: Digits, + /// Adjust Horizontal Diacritic Position (Character panel, Middle Eastern options): the font's + /// mark glyphs among these characters (GDEF class 3, such as Arabic harakat and Hebrew points) + /// move right by a positive value and left by a negative one, relative to their letters, in + /// 1/1000 em of the size, from -[`MAX_DIACRITIC_POSITION`] to [`MAX_DIACRITIC_POSITION`]. + /// Saved only when not 0. + /// + #[serde(default, rename = "diacriticHorizontal", skip_serializing_if = "crate::skip::is_default")] + pub diacritic_horizontal: f64, + /// Adjust Vertical Diacritic Position: the mark glyphs move up by a positive value and down by + /// a negative one, as [`Self::diacritic_horizontal`] moves them across. + #[serde(default, rename = "diacriticVertical", skip_serializing_if = "crate::skip::is_default")] + pub diacritic_vertical: f64, /// Font height reference (Character panel menu › Show Font Height Options): the height of the /// font that [`Self::size`] measures, the em box by default. #[serde(default, rename = "fontHeightReference", skip_serializing_if = "crate::skip::is_default")] @@ -544,6 +556,10 @@ pub const MAX_AKI: f64 = 1000.0; /// The largest Tsume ([`CharStyle::tsume`]), in percent: all the blank space beside the ink. pub const MAX_TSUME: f64 = 100.0; +/// The largest Adjust Horizontal or Vertical Diacritic Position either way +/// ([`CharStyle::diacritic_horizontal`]), in 1/1000 em: one em. +pub const MAX_DIACRITIC_POSITION: f64 = 1000.0; + /// The number of lines a warichu block may be stacked on ([`CharStyle::warichu_lines`]). pub const WARICHU_LINES: std::ops::RangeInclusive = 1..=6; @@ -675,6 +691,8 @@ impl Default for CharStyle { warichu_align: WarichuAlign::Auto, small_caps: None, digits: Digits::Default, + diacritic_horizontal: 0.0, + diacritic_vertical: 0.0, font_height_reference: FontHeightReference::EmBox, no_break: false, language: None, @@ -698,7 +716,8 @@ impl CharStyle { /// same way. The Warichu Settings Lines and Scale /// are kept to [`WARICHU_LINES`] and [`WARICHU_SCALE`]; a gap or scale that is not a number becomes its default. The gap is kept to 0 to /// [`crate::MAX_COORD`], as the baseline shift is, since a scaled type object holds it in its - /// own units. + /// own units. The Adjust Horizontal and Vertical Diacritic Positions are kept within + /// [`MAX_DIACRITIC_POSITION`] either way, and one that is not a number becomes 0. pub fn keep_dimensions_in_range(&mut self) { let default = Self::default(); let within = |v: f64, or: f64| if v > 0.0 { v.min(crate::MAX_COORD) } else { or }; @@ -714,6 +733,9 @@ impl CharStyle { self.aki_left = aki(self.aki_left); self.aki_right = aki(self.aki_right); self.tsume = if self.tsume.is_nan() { 0.0 } else { self.tsume.clamp(0.0, MAX_TSUME) }; + let diacritic = |v: f64| if v.is_nan() { 0.0 } else { v.clamp(-MAX_DIACRITIC_POSITION, MAX_DIACRITIC_POSITION) }; + self.diacritic_horizontal = diacritic(self.diacritic_horizontal); + self.diacritic_vertical = diacritic(self.diacritic_vertical); self.warichu_lines = self.warichu_lines.clamp(*WARICHU_LINES.start(), *WARICHU_LINES.end()); self.warichu_gap = if self.warichu_gap.is_nan() { default.warichu_gap } else { self.warichu_gap.clamp(0.0, crate::MAX_COORD) }; self.warichu_scale = diff --git a/crates/doc/src/text/object.rs b/crates/doc/src/text/object.rs index b787cebfe0..46f86b68ca 100644 --- a/crates/doc/src/text/object.rs +++ b/crates/doc/src/text/object.rs @@ -511,6 +511,8 @@ impl crate::Document { st.aki_left = num("akiLeft").unwrap_or(st.aki_left); st.aki_right = num("akiRight").unwrap_or(st.aki_right); st.tsume = num("tsume").unwrap_or(st.tsume); + st.diacritic_horizontal = num("diacriticHorizontal").unwrap_or(st.diacritic_horizontal); + st.diacritic_vertical = num("diacriticVertical").unwrap_or(st.diacritic_vertical); st.warichu_gap = num("warichuGap").unwrap_or(st.warichu_gap); st.warichu_scale = num("warichuScale").unwrap_or(st.warichu_scale); st.keep_dimensions_in_range(); @@ -537,6 +539,8 @@ impl crate::Document { ("akiLeft", Some(st.aki_left)), ("akiRight", Some(st.aki_right)), ("tsume", Some(st.tsume)), + ("diacriticHorizontal", Some(st.diacritic_horizontal)), + ("diacriticVertical", Some(st.diacritic_vertical)), ("leading", st.leading), ]; for (k, v) in kept { diff --git a/crates/doc/src/text/tests.rs b/crates/doc/src/text/tests.rs index 0976edbb93..a5230d5d86 100644 --- a/crates/doc/src/text/tests.rs +++ b/crates/doc/src/text/tests.rs @@ -129,6 +129,42 @@ fn insert_aki_is_saved_only_when_set() { assert_eq!((d.char_styles[0].attrs["akiLeft"].as_f64(), d.char_styles[0].attrs["akiRight"].as_f64()), (Some(MAX_AKI), Some(0.0))); } +/// Adjust Horizontal and Vertical Diacritic Position are 0 by default and saved only when not 0, +/// each on its own; styles written before them read as 0, and a value out of range from a file is +/// kept within one em either way. +#[test] +fn diacritic_positions_are_saved_only_when_set() { + let st = CharStyle::default(); + assert_eq!((st.diacritic_horizontal, st.diacritic_vertical), (0.0, 0.0)); + let saved = serde_json::to_value(&st).unwrap(); + assert!(saved.get("diacriticHorizontal").is_none() && saved.get("diacriticVertical").is_none()); + for set in [ + CharStyle { diacritic_horizontal: -250.0, ..CharStyle::default() }, + CharStyle { diacritic_vertical: 500.0, ..CharStyle::default() }, + CharStyle { diacritic_horizontal: 12.5, diacritic_vertical: -1000.0, ..CharStyle::default() }, + ] { + let saved = serde_json::to_value(&set).unwrap(); + assert_eq!(saved.get("diacriticHorizontal").and_then(serde_json::Value::as_f64).unwrap_or(0.0), set.diacritic_horizontal); + assert_eq!(saved.get("diacriticVertical").and_then(serde_json::Value::as_f64).unwrap_or(0.0), set.diacritic_vertical); + assert_eq!(saved.get("diacriticHorizontal").is_some(), set.diacritic_horizontal != 0.0); + assert_eq!(saved.get("diacriticVertical").is_some(), set.diacritic_vertical != 0.0); + assert_eq!(serde_json::from_value::(saved).unwrap(), set); + } + let mut damaged = CharStyle { diacritic_horizontal: -4000.0, diacritic_vertical: 4000.0, ..CharStyle::default() }; + damaged.keep_dimensions_in_range(); + assert_eq!((damaged.diacritic_horizontal, damaged.diacritic_vertical), (-MAX_DIACRITIC_POSITION, MAX_DIACRITIC_POSITION)); + let mut damaged = CharStyle { diacritic_horizontal: f64::NAN, diacritic_vertical: f64::NEG_INFINITY, ..CharStyle::default() }; + damaged.keep_dimensions_in_range(); + assert_eq!((damaged.diacritic_horizontal, damaged.diacritic_vertical), (0.0, -MAX_DIACRITIC_POSITION)); + // A character style from a file is kept in range the same way. + let mut d = crate::Document::new(100.0, 100.0); + let attrs = serde_json::json!({"diacriticHorizontal": 5000, "diacriticVertical": -5000}); + d.char_styles.push(TextStyleDef { name: "Moved".into(), attrs: attrs.as_object().cloned().unwrap_or_default() }); + d.keep_type_values_in_range(); + let kept = |key: &str| d.char_styles[0].attrs[key].as_f64(); + assert_eq!((kept("diacriticHorizontal"), kept("diacriticVertical")), (Some(MAX_DIACRITIC_POSITION), Some(-MAX_DIACRITIC_POSITION))); +} + /// Tsume is 0 by default and saved only when not 0; styles written before it read as 0, and a /// value out of range from a file, in a run or a character style, is kept from 0 to 100. #[test] diff --git a/crates/engine/src/cmd/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index fa0492c2db..d0a1a43863 100644 --- a/crates/engine/src/cmd/panelcmds.rs +++ b/crates/engine/src/cmd/panelcmds.rs @@ -67,7 +67,7 @@ pub fn specs() -> Vec { "Character / Paragraph", [], None, - "{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; graph labels keep it for every label of their kind when the graph is drawn again; new type: \"sharp\"), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"yakumonoHankaku\"|\"gyomatsuYakumonoHankaku\"|\"gyomatsuYakumonoZenkaku\"|\"yakumonoZenkaku\"|\"lineEndHalf\" (Mojikumi Set: Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), kinsokuType?: \"pushInFirst\"|\"pushOutFirst\"|\"pushOutOnly\" (Paragraph panel menu › Kinsoku Shori Type: how area type keeps those characters off a line's ends; pushInFirst sets them on the line when its gaps next to CJK characters can close up enough, by at most a tenth of an em each, pushOutFirst does so only when moving the character before them to the next line would leave the line more than an em short, and pushOutOnly, the default, moves it unless Burasagari hangs an overflowing comma or full stop; no effect with kinsoku \"none\"), bunriKinshi?: bool (Paragraph panel menu › Bunri-Kinshi: a line never breaks inside an inseparable pair, two em dashes, two horizontal ellipses, two two-dot leaders or the two halves of a vertical kana repeat mark, and justification adds no space inside one; kept but without effect with kinsoku \"none\"; off by default), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings, as text.setRangeStyle: a tate-chu-yoko block moves up or down, right or left, and on a vertical path toward or away from the path's start, to its left or right), warichu?: bool, warichuLines?: 1..6, warichuGap?: pt 0..100, warichuScale?: % 10..100, warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Character panel menu › Warichu and Warichu Settings, as text.setRangeStyle: the characters set smaller and stacked on lines inside their line), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options, as text.setRangeStyle: space before and after each character in reading order), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options, as text.setRangeStyle: the share of the blank space beside each character's ink taken away in horizontal type), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, as text.setRangeStyle), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), glyphForm?: \"traditional\"|\"expert\"|\"jis04\"|\"jis90\"|\"jis78\"|\"jis83\"|\"fullWidth\"|\"halfWidth\"|\"thirdWidth\"|\"quarterWidth\"|\"default\" (Glyphs panel menu, with Show East Asian Options, as text.setRangeStyle: the characters drawn in one OpenType form of the font, or its default glyphs), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference, as text.setRangeStyle: the height of the font that the size measures), language?: name|tag (Character panel › Language, as text.setRangeStyle), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), koreanLineBreakAnywhere?: bool (Paragraph panel menu › Korean Line Break Anywhere: a line may break between any two Hangul syllables; off, a word with Hangul in it breaks only at its spaces and punctuation, or where it is wider than the line; new type: false, paragraphs saved before the option: true), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\" (line breaking, Every-line by default), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text, and graph labels keep the character and paragraph attributes for every label of their kind when the graph is drawn again, the graph still setting each label's alignment; a number or switch given as another type fails the call, and a null value leaves its attribute as it is, so a call with only null values fails with nothing to change; a call that gives the values the text already has records no undo step). Or {paragraphIndents: [{id, start: byte where the paragraph starts, leftIndent?, firstLineIndent?: pt -1296..1296}…]} alone (Tabs panel indent markers over paragraphs with indents of their own): each entry sets one paragraph of a type object, at least one indent each, at most 100000 entries; every entry is checked before anything changes, and an unknown key, a value out of range, an object that is not type, a byte where no paragraph starts or two entries for one paragraph with other values fail the call; all of it is one edit, a threaded story flowing again once, and when no paragraph's indents change nothing is recorded → {ids}", + "{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; graph labels keep it for every label of their kind when the graph is drawn again; new type: \"sharp\"), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"yakumonoHankaku\"|\"gyomatsuYakumonoHankaku\"|\"gyomatsuYakumonoZenkaku\"|\"yakumonoZenkaku\"|\"lineEndHalf\" (Mojikumi Set: Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), kinsokuType?: \"pushInFirst\"|\"pushOutFirst\"|\"pushOutOnly\" (Paragraph panel menu › Kinsoku Shori Type: how area type keeps those characters off a line's ends; pushInFirst sets them on the line when its gaps next to CJK characters can close up enough, by at most a tenth of an em each, pushOutFirst does so only when moving the character before them to the next line would leave the line more than an em short, and pushOutOnly, the default, moves it unless Burasagari hangs an overflowing comma or full stop; no effect with kinsoku \"none\"), bunriKinshi?: bool (Paragraph panel menu › Bunri-Kinshi: a line never breaks inside an inseparable pair, two em dashes, two horizontal ellipses, two two-dot leaders or the two halves of a vertical kana repeat mark, and justification adds no space inside one; kept but without effect with kinsoku \"none\"; off by default), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings, as text.setRangeStyle: a tate-chu-yoko block moves up or down, right or left, and on a vertical path toward or away from the path's start, to its left or right), warichu?: bool, warichuLines?: 1..6, warichuGap?: pt 0..100, warichuScale?: % 10..100, warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Character panel menu › Warichu and Warichu Settings, as text.setRangeStyle: the characters set smaller and stacked on lines inside their line), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options, as text.setRangeStyle: space before and after each character in reading order), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options, as text.setRangeStyle: the share of the blank space beside each character's ink taken away in horizontal type), 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), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference, as text.setRangeStyle: the height of the font that the size measures), language?: name|tag (Character panel › Language, as text.setRangeStyle), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), koreanLineBreakAnywhere?: bool (Paragraph panel menu › Korean Line Break Anywhere: a line may break between any two Hangul syllables; off, a word with Hangul in it breaks only at its spaces and punctuation, or where it is wider than the line; new type: false, paragraphs saved before the option: true), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\" (line breaking, Every-line by default), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text, and graph labels keep the character and paragraph attributes for every label of their kind when the graph is drawn again, the graph still setting each label's alignment; a number or switch given as another type fails the call, and a null value leaves its attribute as it is, so a call with only null values fails with nothing to change; a call that gives the values the text already has records no undo step). Or {paragraphIndents: [{id, start: byte where the paragraph starts, leftIndent?, firstLineIndent?: pt -1296..1296}…]} alone (Tabs panel indent markers over paragraphs with indents of their own): each entry sets one paragraph of a type object, at least one indent each, at most 100000 entries; every entry is checked before anything changes, and an unknown key, a value out of range, an object that is not type, a byte where no paragraph starts or two entries for one paragraph with other values fail the call; all of it is one edit, a threaded story flowing again once, and when no paragraph's indents change nothing is recorded → {ids}", has_doc, set_format ), @@ -614,6 +614,8 @@ fn set_format(s: &mut Session, p: &Value) -> Result { "akiLeft", "akiRight", "tsume", + "diacriticHorizontal", + "diacriticVertical", "standardVerticalRoman", "noBreak", "digits", @@ -661,6 +663,8 @@ fn set_format(s: &mut Session, p: &Value) -> Result { let aki_left = super::textedit::aki_param(p, "akiLeft", C)?; let aki_right = super::textedit::aki_param(p, "akiRight", C)?; let tsume = super::textedit::tsume_param(p, C)?; + let diacritic_horizontal = super::textedit::diacritic_param(p, "diacriticHorizontal", C)?; + let diacritic_vertical = super::textedit::diacritic_param(p, "diacriticVertical", C)?; let warichu_lines = super::textedit::warichu_lines_param(p, C)?; let warichu_gap = super::textedit::warichu_number_param(p, "warichuGap", C)?; let warichu_scale = super::textedit::warichu_number_param(p, "warichuScale", C)?; @@ -851,6 +855,8 @@ fn set_format(s: &mut Session, p: &Value) -> Result { if let Some(v) = tsume { st.tsume = v; } + st.diacritic_horizontal = diacritic_horizontal.unwrap_or(st.diacritic_horizontal); + st.diacritic_vertical = diacritic_vertical.unwrap_or(st.diacritic_vertical); if let Some(v) = flag("standardVerticalRoman") { st.standard_vertical_roman = v; } diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index 10f1d57342..fa6e556c6c 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -40,7 +40,7 @@ pub fn specs() -> Vec { "Character", [], None, - "{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), story?: bool = false (all the text of every frame of the threaded story `id` is a frame of, in one undo step; no `start` or `end`), font?, style?, size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\" (the space after each character), kerningBefore?: 1/1000 em -1000..10000 (the space before a character that starts a line by itself: the first character of the text, of a paragraph or after a forced line break; no effect elsewhere; 0 by default), baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), fill?: colour|\"none\", stroke?: colour|\"none\" (#rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", \"salt=2\", …] (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off; \"hkna\" is H or V Style, kana in the font's forms for the writing direction, shaped as `vkna` in vertical type, and \"ital\" is Roman Italics, half-width alphanumerics in the font's italic forms, both on or off only; the range is shaped with its word, so a letter's alternate keeps it joined to its neighbours), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings: in vertical type a block of tate-chu-yoko characters moves up by a positive Up/Down and down by a negative one, right by a positive Left/Right and left by a negative one, as one piece with the values of its first character; on a vertical path a positive Up/Down moves it toward the path's start and a positive Left/Right to the path's left; 0 by default; automatic digit blocks and horizontal type do not move; neither turns tateChuYoko on), warichu?: bool (Character panel menu › Warichu, with Show East Asian Options: the characters are set at warichuScale percent of their size and stacked on warichuLines lines inside their line, one above the other in horizontal type and side by side in vertical type, the first line above or to the right; a stretch of them is one block with the settings of its first character that stays whole on one line and may run past its end; type on a path sets them at their own size), warichuLines?: 1..6 (default 2), warichuGap?: pt 0..100 (the space between the lines, default 0), warichuScale?: % 10..100 (default 50), warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Warichu Settings: how the lines line up along the block, which is as long as its longest line; the justify values spread every line but the last, which is set left, centered or right, or spread with justifyAll; auto, the default, sets them as justifyLeft; left and right are top and bottom in vertical type; none of them turns warichu on), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options: space before and after each character in reading order, on its left and right in left-to-right type, on its right and left in right-to-left type, above and below it in vertical type; a ligature or a letter with its marks takes the values of its first character; line wrapping counts it, alignment keeps it at a line's ends and justification does not stretch or narrow it; 0 by default; a value that is not a number or is outside the range is refused, naming the key), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options: the share of the blank space on each side of each character's ink, inside its own width, that is taken away in horizontal type, the glyph keeping its shape; 100 sets the ink edge to edge; a character without ink, such as a space, keeps its width; a ligature or a letter with its marks takes the value of its first character; tracking, kerning and Insert Aki are added after it, and justification keeps it; vertical type keeps the characters' spacing; 0 by default; a value that is not a number or is outside the range is refused), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, with Show East Asian Options: in vertical type those half-width characters, such as Latin letters and digits, stand upright one below the other instead of being rotated; spaces and tate-chu-yoko blocks are not changed; kept on the characters and ignored in horizontal type; off by default), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), glyphForm?: \"traditional\"|\"expert\"|\"jis04\"|\"jis90\"|\"jis78\"|\"jis83\"|\"fullWidth\"|\"halfWidth\"|\"thirdWidth\"|\"quarterWidth\"|\"default\" (Glyphs panel menu, with Show East Asian Options: the characters are drawn in that form of the font, the OpenType feature trad, expt, jp04, jp90, jp78, jp83, fwid, hwid, twid or qwid, one form at a time; a character the font has no such glyph for keeps its own; \"default\", Revert To Default Forms, draws the font's default glyphs; another value is refused), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference: the height of the font that size measures, the em box by default; with a font that has no such height, or one outside 0.1 to 2 em, the em box), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such as \"Turkish\" or \"tr\"; the characters are shaped in it, so the font uses that language's forms (OpenType `locl`); saved as the tag, English: USA, the default, as none; new type takes the document's language), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes), glyphAlternate?: null (takes away the glyph choice text.setGlyphAlternate made on the characters, in the same undo step as the other attributes; any other value is refused)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", + "{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), story?: bool = false (all the text of every frame of the threaded story `id` is a frame of, in one undo step; no `start` or `end`), font?, style?, size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\" (the space after each character), kerningBefore?: 1/1000 em -1000..10000 (the space before a character that starts a line by itself: the first character of the text, of a paragraph or after a forced line break; no effect elsewhere; 0 by default), baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), fill?: colour|\"none\", stroke?: colour|\"none\" (#rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", \"salt=2\", …] (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off; \"hkna\" is H or V Style, kana in the font's forms for the writing direction, shaped as `vkna` in vertical type, and \"ital\" is Roman Italics, half-width alphanumerics in the font's italic forms, both on or off only; the range is shaped with its word, so a letter's alternate keeps it joined to its neighbours), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings: in vertical type a block of tate-chu-yoko characters moves up by a positive Up/Down and down by a negative one, right by a positive Left/Right and left by a negative one, as one piece with the values of its first character; on a vertical path a positive Up/Down moves it toward the path's start and a positive Left/Right to the path's left; 0 by default; automatic digit blocks and horizontal type do not move; neither turns tateChuYoko on), warichu?: bool (Character panel menu › Warichu, with Show East Asian Options: the characters are set at warichuScale percent of their size and stacked on warichuLines lines inside their line, one above the other in horizontal type and side by side in vertical type, the first line above or to the right; a stretch of them is one block with the settings of its first character that stays whole on one line and may run past its end; type on a path sets them at their own size), warichuLines?: 1..6 (default 2), warichuGap?: pt 0..100 (the space between the lines, default 0), warichuScale?: % 10..100 (default 50), warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Warichu Settings: how the lines line up along the block, which is as long as its longest line; the justify values spread every line but the last, which is set left, centered or right, or spread with justifyAll; auto, the default, sets them as justifyLeft; left and right are top and bottom in vertical type; none of them turns warichu on), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options: space before and after each character in reading order, on its left and right in left-to-right type, on its right and left in right-to-left type, above and below it in vertical type; a ligature or a letter with its marks takes the values of its first character; line wrapping counts it, alignment keeps it at a line's ends and justification does not stretch or narrow it; 0 by default; a value that is not a number or is outside the range is refused, naming the key), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options: the share of the blank space on each side of each character's ink, inside its own width, that is taken away in horizontal type, the glyph keeping its shape; 100 sets the ink edge to edge; a character without ink, such as a space, keeps its width; a ligature or a letter with its marks takes the value of its first character; tracking, kerning and Insert Aki are added after it, and justification keeps it; vertical type keeps the characters' spacing; 0 by default; a value that is not a number or is outside the range is refused), diacriticHorizontal?, diacriticVertical?: 1/1000 em -1000..1000 (Character panel › Adjust Horizontal and Vertical Diacritic Position, with Show Indic Options: the font's mark glyphs among the characters, those its GDEF table classes as marks such as Arabic harakat and Hebrew points, move right by a positive horizontal value and up by a positive vertical one, relative to their letters, in thousandths of the size; a harakat or Hebrew point styled apart from its letter takes its own values and stays attached to it, and another mark takes its letter's; letters and fonts without mark classes do not move; 0 by default; a value that is not a number or is outside the range is refused, naming the key), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, with Show East Asian Options: in vertical type those half-width characters, such as Latin letters and digits, stand upright one below the other instead of being rotated; spaces and tate-chu-yoko blocks are not changed; kept on the characters and ignored in horizontal type; off by default), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), glyphForm?: \"traditional\"|\"expert\"|\"jis04\"|\"jis90\"|\"jis78\"|\"jis83\"|\"fullWidth\"|\"halfWidth\"|\"thirdWidth\"|\"quarterWidth\"|\"default\" (Glyphs panel menu, with Show East Asian Options: the characters are drawn in that form of the font, the OpenType feature trad, expt, jp04, jp90, jp78, jp83, fwid, hwid, twid or qwid, one form at a time; a character the font has no such glyph for keeps its own; \"default\", Revert To Default Forms, draws the font's default glyphs; another value is refused), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference: the height of the font that size measures, the em box by default; with a font that has no such height, or one outside 0.1 to 2 em, the em box), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such as \"Turkish\" or \"tr\"; the characters are shaped in it, so the font uses that language's forms (OpenType `locl`); saved as the tag, English: USA, the default, as none; new type takes the document's language), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes), glyphAlternate?: null (takes away the glyph choice text.setGlyphAlternate made on the characters, in the same undo step as the other attributes; any other value is refused)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", has_doc, set_range_style ), @@ -470,6 +470,9 @@ pub(crate) struct CharChange { aki_right: Option, /// Tsume, in percent. tsume: Option, + /// Adjust Horizontal and Vertical Diacritic Position, in 1/1000 em. + diacritic_horizontal: Option, + diacritic_vertical: Option, standard_vertical_roman: Option, no_break: Option, digits: Option, @@ -548,6 +551,16 @@ pub(crate) fn aki_param(p: &Value, key: &str, cmd: &str) -> Result> if (lo..=hi).contains(&v) { Ok(Some(v)) } else { Err(bad(cmd, format!("`{key}` must be from {lo} to {hi}"))) } } +/// `diacriticHorizontal` or `diacriticVertical` (Adjust Horizontal and Vertical Diacritic +/// Position): a number of thousandths of an em within +/// [`vectorcraft_doc::text::MAX_DIACRITIC_POSITION`] either way. Any other value is an error. +pub(crate) fn diacritic_param(p: &Value, key: &str, cmd: &str) -> Result> { + let Some(v) = p.get(key).filter(|v| !v.is_null()) else { return Ok(None) }; + let v = v.as_f64().filter(|v| v.is_finite()).ok_or_else(|| bad(cmd, format!("`{key}` must be a number")))?; + let (lo, hi) = (-vectorcraft_doc::text::MAX_DIACRITIC_POSITION, vectorcraft_doc::text::MAX_DIACRITIC_POSITION); + if (lo..=hi).contains(&v) { Ok(Some(v)) } else { Err(bad(cmd, format!("`{key}` must be from {lo} to {hi}"))) } +} + /// `tsume` (Tsume): a percentage from 0 to [`vectorcraft_doc::text::MAX_TSUME`]. Any other value is /// an error. pub(crate) fn tsume_param(p: &Value, cmd: &str) -> Result> { @@ -852,6 +865,8 @@ impl CharChange { aki_left: aki_param(p, "akiLeft", cmd)?, aki_right: aki_param(p, "akiRight", cmd)?, tsume: tsume_param(p, cmd)?, + diacritic_horizontal: diacritic_param(p, "diacriticHorizontal", cmd)?, + diacritic_vertical: diacritic_param(p, "diacriticVertical", cmd)?, standard_vertical_roman: flag("standardVerticalRoman"), no_break: flag("noBreak"), digits: digits_param(p, cmd)?, @@ -918,6 +933,8 @@ impl CharChange { && self.aki_left.is_none() && self.aki_right.is_none() && self.tsume.is_none() + && self.diacritic_horizontal.is_none() + && self.diacritic_vertical.is_none() && self.standard_vertical_roman.is_none() && self.no_break.is_none() && self.digits.is_none() @@ -963,7 +980,8 @@ impl CharChange { } } - /// The character alignment, direction and East Asian settings of [`Self::apply`]. + /// The character alignment, direction, diacritic positions and East Asian settings of + /// [`Self::apply`]. fn apply_cjk(&self, st: &mut CharStyle) { if let Some(v) = self.char_align { st.char_align = v; @@ -1010,6 +1028,12 @@ impl CharChange { if let Some(v) = self.tsume { st.tsume = v; } + if let Some(v) = self.diacritic_horizontal { + st.diacritic_horizontal = v; + } + if let Some(v) = self.diacritic_vertical { + st.diacritic_vertical = v; + } if let Some(v) = self.standard_vertical_roman { st.standard_vertical_roman = v; } diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index 18f87d44f7..efcc078e65 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -223,6 +223,8 @@ pub fn char_attrs(v: &CharStyle) -> Map { ("akiLeft", json!(v.aki_left)), ("akiRight", json!(v.aki_right)), ("tsume", json!(v.tsume)), + ("diacriticHorizontal", json!(v.diacritic_horizontal)), + ("diacriticVertical", json!(v.diacritic_vertical)), ("standardVerticalRoman", json!(v.standard_vertical_roman)), ("noBreak", json!(v.no_break)), ("digits", json!(v.digits)), @@ -584,6 +586,13 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma if changed(key) && !(lo..=hi).contains(&st.tsume) { return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}"))); } + let hi = vectorcraft_doc::text::MAX_DIACRITIC_POSITION; + let lo = -hi; + for (key, value) in [("diacriticHorizontal", st.diacritic_horizontal), ("diacriticVertical", st.diacritic_vertical)] { + if changed(key) && !(lo..=hi).contains(&value) { + return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}"))); + } + } let lines = vectorcraft_doc::text::WARICHU_LINES; if changed("warichuLines") && !lines.contains(&st.warichu_lines) { return Err(bad(&c, format!("`warichuLines` must be a whole number from {} to {}", lines.start(), lines.end()))); @@ -1081,12 +1090,12 @@ fn unused(s: &mut Session, kind: Kind) -> Result { /// The styles of `kind` in `src` that load, with their source names so that art in the file keeps /// referring to them: not the Normal style, and not one whose attributes don't read, whose sizes, -/// scales, leading, shifts, Insert Aki, Tsume, Warichu Settings or stroke width are out of the range `charStyle.new` takes, whose +/// scales, leading, shifts, Insert Aki, Tsume, diacritic positions, Warichu Settings or stroke width are out of the range `charStyle.new` takes, whose /// indents, spacing, Hyphenation or Justification options or tab stops are out of the range /// `paraStyle.new` takes, or whose name is empty, which are skipped. → (the styles, the names in /// `src` of those skipped) fn loadable(src: &Document, kind: Kind) -> (Vec, Vec) { - const RANGED: [&str; 22] = [ + const RANGED: [&str; 24] = [ "size", "h_scale", "v_scale", @@ -1095,6 +1104,8 @@ fn loadable(src: &Document, kind: Kind) -> (Vec, Vec) { "akiLeft", "akiRight", "tsume", + "diacriticHorizontal", + "diacriticVertical", "tcyUpDown", "tcyLeftRight", "warichuLines", diff --git a/crates/engine/src/cmd/textstyles/tests.rs b/crates/engine/src/cmd/textstyles/tests.rs index c8da4b578c..5b2c19ed51 100644 --- a/crates/engine/src/cmd/textstyles/tests.rs +++ b/crates/engine/src/cmd/textstyles/tests.rs @@ -399,6 +399,8 @@ fn character_style_dimensions_are_checked_before_a_definition_changes() { json!({"akiRight": 1000.1}), json!({"tsume": -0.1}), json!({"tsume": 100.1}), + json!({"diacriticHorizontal": -1000.1}), + json!({"diacriticVertical": 1000.1}), ] { let key = attrs.as_object().unwrap().keys().next().unwrap(); for cmd in ["charStyle.edit", "charStyle.setAttrs", "charStyle.new"] { @@ -422,7 +424,8 @@ fn character_style_dimensions_are_checked_before_a_definition_changes() { "baseline_shift": -1296.0, "tcyUpDown": 1296.0, "tcyLeftRight": -1296.0, "akiLeft": 0.0, "akiRight": 1000.0, - "tsume": 100.0 + "tsume": 100.0, + "diacriticHorizontal": -1000.0, "diacriticVertical": 1000.0 }}), ) .unwrap(); diff --git a/crates/engine/src/cmd/typecmd/area_tests.rs b/crates/engine/src/cmd/typecmd/area_tests.rs index e0e5d8a926..17ac2c647e 100644 --- a/crates/engine/src/cmd/typecmd/area_tests.rs +++ b/crates/engine/src/cmd/typecmd/area_tests.rs @@ -1921,6 +1921,66 @@ fn tsume_is_a_character_attribute() { assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step for a refused call"); } +/// Adjust Horizontal and Vertical Diacritic Position (Character panel, Middle Eastern options): +/// character attributes in thousandths of an em, 0 by default and saved only when not 0. Both +/// commands set them in one undo step, setting one leaves the other, a call that gives the values +/// the text already has records none, and a value that is not a number or lies outside -1000 to +/// 1000 is refused, naming the key, before anything changes; the native file and a character style +/// captured from the characters carry them. +#[test] +fn diacritic_positions_are_character_attributes() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "بَب"})).unwrap()["id"].as_u64().unwrap(); + let runs = |s: &Session| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => t.runs.clone(), + _ => panic!("text"), + }; + let moved = |s: &Session| runs(s).iter().map(|r| (r.text.clone(), r.style.diacritic_horizontal, r.style.diacritic_vertical)).collect::>(); + let saved = serde_json::to_value(&runs(&s)[0].style).unwrap(); + assert!(saved.get("diacriticHorizontal").is_none() && saved.get("diacriticVertical").is_none()); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + s.execute("text.setFormat", &json!({"diacriticHorizontal": -150})).unwrap(); + s.execute("text.setFormat", &json!({"diacriticVertical": 250})).unwrap(); + assert_eq!(moved(&s), [("بَب".to_string(), -150.0, 250.0)], "setting one leaves the other"); + let undo = s.doc().unwrap().history.undo.len(); + s.execute("text.setFormat", &json!({"diacriticHorizontal": -150, "diacriticVertical": 250})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step without a change"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(moved(&s), [("بَب".to_string(), -150.0, 0.0)], "one undo step"); + s.execute("edit.redo", &json!({})).unwrap(); + + let mark = "بَ".len(); + s.execute("text.setRangeStyle", &json!({"id": id, "start": "ب".len(), "end": mark, "diacriticVertical": -1000})).unwrap(); + assert_eq!(moved(&s), [("ب".to_string(), -150.0, 250.0), ("\u{064E}".to_string(), -150.0, -1000.0), ("ب".to_string(), -150.0, 250.0)]); + let saved = serde_json::to_value(&runs(&s)[1].style).unwrap(); + assert_eq!((saved["diacriticHorizontal"].clone(), saved["diacriticVertical"].clone()), (json!(-150.0), json!(-1000.0))); + let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + let NodeKind::Text(t) = &back.node(NodeId(id)).unwrap().kind else { panic!("text") }; + let reopened: Vec<_> = t.runs.iter().map(|r| (r.text.clone(), r.style.diacritic_horizontal, r.style.diacritic_vertical)).collect(); + assert_eq!(reopened, moved(&s)); + let attrs = super::super::textstyles::char_attrs(&runs(&s)[1].style); + assert_eq!((attrs["diacriticHorizontal"].clone(), attrs["diacriticVertical"].clone()), (json!(-150.0), json!(-1000.0))); + + let before = moved(&s); + let undo = s.doc().unwrap().history.undo.len(); + for (cmd, p, want) in [ + ("text.setFormat", json!({"diacriticHorizontal": "50"}), "`diacriticHorizontal` must be a number"), + ("text.setFormat", json!({"diacriticVertical": 1000.5}), "`diacriticVertical` must be from -1000 to 1000"), + ("text.setRangeStyle", json!({"id": id, "diacriticVertical": true}), "`diacriticVertical` must be a number"), + ( + "text.setRangeStyle", + json!({"id": id, "start": 0, "end": mark, "diacriticHorizontal": -1001}), + "`diacriticHorizontal` must be from -1000 to 1000", + ), + ] { + let e = s.execute(cmd, &p).unwrap_err(); + assert!(matches!(&e, EngineError::BadParams { msg, .. } if msg == want), "{cmd} {p}: {e}"); + } + assert_eq!(moved(&s), before); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step for a refused call"); +} + /// Standard Vertical Roman Alignment (Character panel menu, East Asian options): a character /// attribute, off by default and saved only when on. Documents written before it read as off; a /// character style captured from the characters carries it. diff --git a/crates/svg/src/export/text.rs b/crates/svg/src/export/text.rs index 2f8e8b8a1b..f325387033 100644 --- a/crates/svg/src/export/text.rs +++ b/crates/svg/src/export/text.rs @@ -86,11 +86,15 @@ impl Writer<'_> { // type with warichu, whose stacked lines a reader's can't place either. So are // small capitals, superscript and subscript and tab leaders, which SVG text doesn't draw (#3869), // and a glyph chosen for a character, which a reader's draws with the default glyph. So - // is type in one of the document's composite fonts, which a reader can't find by its name. + // is type in one of the document's composite fonts, which a reader can't find by its name, + // and type with an Adjust Diacritic Position, whose marks a reader's draws where the + // font puts them. let unwritable = t.runs.iter().any(|r| { r.style.small_caps.is_some() || r.style.position != vectorcraft_doc::CharPosition::Normal || r.style.glyph_alternate.is_some() + || r.style.diacritic_horizontal != 0.0 + || r.style.diacritic_vertical != 0.0 || vectorcraft_doc::CompositeFont::named(&doc.composite_fonts, &r.style.font_family).is_some() }) || std::iter::once(&t.para).chain(&t.paras).any(|p| p.tabs.iter().any(|tab| !tab.leader.is_empty())); let outlined = self.opts.outline_text diff --git a/crates/svg/tests/it/text_layout.rs b/crates/svg/tests/it/text_layout.rs index c53318c358..8c61087e3e 100644 --- a/crates/svg/tests/it/text_layout.rs +++ b/crates/svg/tests/it/text_layout.rs @@ -357,6 +357,19 @@ fn a_chosen_glyph_is_written_as_outlines() { assert!(!svg.contains("` would draw +/// the marks where the font puts them. +#[test] +fn moved_diacritics_are_written_as_outlines() { + let svg = export(&area_doc(vec![run("re\u{301}sume\u{301}", style(12.0))], 280.0, Justify::Left), &ExportOptions::default()); + assert!(svg.contains("` element's 12. diff --git a/crates/text/src/harakat.rs b/crates/text/src/harakat.rs index ab5aa593bd..9ea14d0f08 100644 --- a/crates/text/src/harakat.rs +++ b/crates/text/src/harakat.rs @@ -13,6 +13,12 @@ //! a mark on a ligature (for example Geeza Pro's Allah ligature) painted as its letter. Renderers //! and exporters read the glyph's run as they always did, so they need no change. The text itself //! is never changed. +//! +//! The Adjust Horizontal and Vertical Diacritic Positions ([`CharStyle::diacritic_horizontal`]) +//! move the face's mark glyphs (GDEF class 3) by the values of the glyph's run. Runs that differ +//! only in paint and those positions stay one shaping cluster at an Arabic harakat or a Hebrew +//! point ([`diacritic_mark_boundary`]), so a mark set apart from its letter takes its own values +//! the same way it takes its own paint. use skrifa::raw::TableProvider; use skrifa::raw::tables::layout::ClassDef; @@ -36,11 +42,24 @@ pub(crate) fn is_harakat(c: char) -> bool { ) } +/// Is `c` a Hebrew point or cantillation mark (U+0591–U+05BD, U+05BF, U+05C1–U+05C2, +/// U+05C4–U+05C5, U+05C7)? +fn is_hebrew_mark(c: char) -> bool { + matches!(c as u32, 0x0591..=0x05BD | 0x05BF | 0x05C1..=0x05C2 | 0x05C4..=0x05C5 | 0x05C7) +} + +/// Is `c` a diacritical mark the Adjust Diacritic Position fields set apart from its letter: an +/// Arabic harakat ([`is_harakat`]) or a Hebrew point? +pub(crate) fn is_diacritic(c: char) -> bool { + is_harakat(c) || is_hebrew_mark(c) +} + /// Do character styles `a` and `b` differ, if at all, only in paint: fill, stroke and how the /// stroke is drawn, overprint, and the character style name? OpenType feature differences are /// ignored here: they already apply to their own character ranges during shaping. Nor is the /// space before a line's first character read inside a cluster, which takes it from its first -/// character (#5111). Stricter than [`crate::shape`]'s `shapes_alike` (which also ignores baseline +/// character (#5111), nor the Adjust Diacritic Positions, which move a mark glyph by its own run's +/// values. Stricter than [`crate::shape`]'s `shapes_alike` (which also ignores baseline /// shift, tracking, underline, …). pub(crate) fn paint_only(a: &CharStyle, b: &CharStyle) -> bool { // Exhaustive: a new attribute must explicitly keep or relax this boundary rule. @@ -82,6 +101,8 @@ pub(crate) fn paint_only(a: &CharStyle, b: &CharStyle) -> bool { warichu_scale, warichu_align, digits, + diacritic_horizontal: _, + diacritic_vertical: _, font_height_reference, no_break, language, @@ -150,6 +171,16 @@ pub(crate) fn paint_only_mark_boundary(text: &str, at: usize, before: &CharStyle (next.is_some_and(is_harakat) || previous.is_some_and(is_harakat)) && paint_only(before, after) } +/// Is the run boundary at byte `at` of `text`, between styles `before` and `after`, one where the +/// Adjust Diacritic Positions differ, nothing but paint differs besides, and an Arabic harakat or a +/// Hebrew point is on either side? It stays inside a shaping cluster as a paint-only one does. +pub(crate) fn diacritic_mark_boundary(text: &str, at: usize, before: &CharStyle, after: &CharStyle) -> bool { + let next = text.get(at..).and_then(|s| s.chars().next()); + let previous = text.get(..at).and_then(|s| s.chars().next_back()); + let moved = before.diacritic_horizontal != after.diacritic_horizontal || before.diacritic_vertical != after.diacritic_vertical; + moved && (next.is_some_and(is_diacritic) || previous.is_some_and(is_diacritic)) && paint_only(before, after) +} + /// The byte ranges of the harakat in `text[range]`, each run of consecutive harakat as one range. /// The range is normalised as [`crate::edit::style_range`] takes one: its ends clamped to the /// text, each moved back to the start of the character it falls in, and put in order. @@ -194,7 +225,8 @@ pub(crate) fn mark_classes(face: &FontFace) -> Option> { /// by glyph): repeated glyph ids alone could hide a changed correspondence. A glyph whose character /// lies outside its own shaping cluster of `raw` (from its cluster value up to the next larger one, /// else `end`) gets its cluster's first character instead. A later in-cluster character is kept -/// only when the glyph is a GDEF mark and that character is a harakat; otherwise the cluster start +/// only when the glyph is a GDEF mark and that character is a harakat or a Hebrew point +/// ([`is_diacritic`]); otherwise the cluster start /// is kept (conservative: a mark may miss its colour; a base must never take a mark's). `raw`'s /// clusters are never changed. These are HarfBuzz shaping clusters, which can span more than one /// grapheme (a ligature). @@ -224,8 +256,9 @@ pub(crate) fn own_chars( if c.1 == r.1 { return c.1; } - // Later in-cluster character: only a positively identified mark glyph on a harakat. - let mark_char = text.get(c.1 as usize..).and_then(|s| s.chars().next()).is_some_and(is_harakat); + // Later in-cluster character: only a positively identified mark glyph on a harakat or + // a Hebrew point. + let mark_char = text.get(c.1 as usize..).and_then(|s| s.chars().next()).is_some_and(is_diacritic); if is_gdef_mark(r.0) && mark_char { c.1 } else { r.1 } }) .collect() diff --git a/crates/text/src/shape.rs b/crates/text/src/shape.rs index 9d36eed28b..d89561117c 100644 --- a/crates/text/src/shape.rs +++ b/crates/text/src/shape.rs @@ -1032,6 +1032,10 @@ fn drawn_alike(a: &CharStyle, b: &CharStyle, vertical: bool) -> bool { warichu_scale: _, warichu_align: _, digits, + // A mark glyph moves by its own run's values ([`shape_segment`]), so a mark keeps its + // letter whatever they are. + diacritic_horizontal: _, + diacritic_vertical: _, font_height_reference, no_break, language, @@ -1106,7 +1110,8 @@ pub(crate) fn warichu_alike(a: &CharStyle, b: &CharStyle) -> bool { /// character style's name, leading, baseline shift, rotation, Character Alignment, Character /// Direction (text is shaped apart where its bidi level changes), Kashidas, the kerning (each glyph takes its /// run's, see [`shape_segment`]), the space before a line's first character ([`space_before`]), -/// Insert Aki ([`aki`]), Tsume ([`tighten`]), the OpenType features and the East Asian glyph form (each run's apply to its own characters, as features +/// Insert Aki ([`aki`]), Tsume ([`tighten`]), the Adjust Diacritic Positions (each mark glyph takes +/// its run's), the OpenType features and the East Asian glyph form (each run's apply to its own characters, as features /// over a range of the one buffer) and the tracking, as long as the tracking keeps or drops /// standard ligatures alike ([`crate::features::ligatures_suppressed_by`]). fn shapes_alike(a: &CharStyle, b: &CharStyle) -> bool { @@ -1165,6 +1170,8 @@ fn shapes_alike(a: &CharStyle, b: &CharStyle) -> bool { warichu_scale: _, warichu_align: _, digits, + diacritic_horizontal: _, + diacritic_vertical: _, font_height_reference, no_break, language, @@ -1437,11 +1444,21 @@ fn shape_segment(text: &str, context: &Range, seg: &Segment, feats: &OtFe if !manual_ends.is_empty() { return shape_apart(manual_ends, out); } - // Harakat styled apart from their letters (paint only): shaped with them, each glyph then - // takes its own character's run ([`crate::harakat`]). + // Harakat styled apart from their letters (paint only), and harakat and Hebrew points with + // diacritic positions of their own: shaped with them, each glyph then takes its own + // character's run ([`crate::harakat`]). let mark_boundaries: Vec = boundaries() - .filter(|&b| run_at(b - 1).1 != run_at(b).1 && crate::harakat::paint_only_mark_boundary(text, b, run_at(b - 1).1, run_at(b).1)) + .filter(|&b| { + let (before, after) = (run_at(b - 1).1, run_at(b).1); + before != after + && (crate::harakat::paint_only_mark_boundary(text, b, before, after) + || crate::harakat::diacritic_mark_boundary(text, b, before, after)) + }) .collect(); + // The face's mark classes, read once when any of the segment's runs moves its marks. + let moves_marks = + runs.get(source_runs.clone()).unwrap_or_default().iter().any(|(_, s)| s.diacritic_horizontal != 0.0 || s.diacritic_vertical != 0.0); + let diacritic_classes = if moves_marks { crate::harakat::mark_classes(face) } else { None }; // Source run starts are sorted. Reuse their classification when checking cluster splits. let styled_marks = !mark_boundaries.is_empty(); let char_level = std::cell::Cell::new(false); @@ -1734,11 +1751,21 @@ fn shape_segment(text: &str, context: &Range, seg: &Segment, feats: &OtFe for (gi, &(gid, cl, xa, xo, yo)) in raw.iter().enumerate() { let cl = cl as usize; let (run, gst) = run_at(cl); - // A glyph of a harakat styled apart takes its own character's run (paint only). - let run = match chars.get(gi).map(|&c| run_at(c as usize)) { - Some((own, own_st)) if crate::harakat::paint_only(gst, own_st) => own, - _ => run, + // A glyph of a harakat styled apart takes its own character's run (paint and diacritic + // positions only). + let (run, run_st) = match chars.get(gi).map(|&c| run_at(c as usize)) { + Some((own, own_st)) if crate::harakat::paint_only(gst, own_st) => (own, own_st), + _ => (run, gst), }; + // A mark glyph (GDEF class 3) moves by its run's Adjust Diacritic Positions, thousandths + // of the em it is set in: right and up for positive values. + let (mut dx, mut dy) = (xo as f64 * k * hs, -(yo as f64) * k * vs); + if let Some(classes) = &diacritic_classes + && classes.get(skrifa::GlyphId::new(gid)) == 3 + { + dx += run_st.diacritic_horizontal / 1000.0 * size * hs; + dy -= run_st.diacritic_vertical / 1000.0 * size * vs; + } let end = cluster_end(cl); let last_in_cluster = gi + 1 == n || raw[gi + 1].1 as usize != cl; let ch = first_char(cl); @@ -1793,8 +1820,8 @@ fn shape_segment(text: &str, context: &Range, seg: &Segment, feats: &OtFe run, adv, tracking: tracked, - dx: xo as f64 * k * hs, - dy: -(yo as f64) * k * vs, + dx, + dy, kern_shift, aki_shift, aki: aki_in_adv, diff --git a/crates/text/src/tests/harakat.rs b/crates/text/src/tests/harakat.rs index 0b401a5cd3..4e11921a6f 100644 --- a/crates/text/src/tests/harakat.rs +++ b/crates/text/src/tests/harakat.rs @@ -173,6 +173,8 @@ fn paint_only_keeps_every_drawing_attribute_and_partial_equality() { b.style_name = a.style_name.clone(); b.kerning_before = a.kerning_before; b.features = a.features.clone(); + b.diacritic_horizontal = a.diacritic_horizontal; + b.diacritic_vertical = a.diacritic_vertical; *a == b } @@ -226,6 +228,8 @@ fn paint_only_keeps_every_drawing_attribute_and_partial_equality() { field!(tcy_left_right, 1.0, false); field!(standard_vertical_roman, true, false); field!(digits, Digits::Hindi, false); + field!(diacritic_horizontal, 100.0, true); + field!(diacritic_vertical, -100.0, true); field!(font_height_reference, FontHeightReference::CapHeight, false); field!(no_break, true, false); field!(language, Some("ar".into()), false); @@ -331,6 +335,74 @@ fn feature_only_harakat_boundaries_keep_attachment_and_ownership() { } } +/// Adjust Horizontal and Vertical Diacritic Position move the mark glyphs (GDEF class 3) by +/// thousandths of an em of the glyph size, right and up for positive values, and leave the letters +/// where they were. A mark styled apart from its letter takes its own values. +#[test] +fn diacritic_positions_move_marks_and_keep_letters() { + let db = FontDb::with_font_dirs(vec![]); + assert_eq!(db.add_font(crate::test_fonts::lam_alef_font(b"rlig").expect("the test font builds")), 1); + let family = crate::test_fonts::lam_alef_family(b"rlig"); + let face = db.face(family, "Regular").expect("the test face"); + const WORD: &str = "بَبَبَ"; + let plain = TextObject::point(Point::ZERO, WORD, style(family)); + let before = layout(&db, &plain); + assert_eq!(before.glyphs.len(), 6, "three bases with their attached marks"); + let (h, v) = (200.0, 100.0); + let moved = (h / 1000.0 * 48.0, -v / 1000.0 * 48.0); + // (letters set, marks set): which glyphs move. + for (letters, marks) in [(true, true), (false, true), (true, false), (false, false)] { + let mut text = plain.clone(); + for (byte, ch) in WORD.char_indices() { + if (is_harakat(ch) && marks) || (!is_harakat(ch) && letters) { + crate::edit::style_range(&mut text.runs, byte, byte + ch.len_utf8(), |st| { + st.diacritic_horizontal = h; + st.diacritic_vertical = v; + }); + } + } + let after = layout(&db, &text); + assert_eq!(after.glyphs.len(), before.glyphs.len(), "letters {letters}, marks {marks}"); + let mut marks_seen = 0; + for (a, b) in before.glyphs.iter().zip(&after.glyphs) { + assert_eq!((a.gid, a.byte, a.origin, a.advance), (b.gid, b.byte, b.origin, b.advance), "letters {letters}, marks {marks}"); + let (ta, tb) = (a.xf.translation(), b.xf.translation()); + let delta = (tb.x - ta.x, tb.y - ta.y); + let mark = is_gdef_mark(&face, a.gid); + marks_seen += usize::from(mark); + let want = if mark && marks { moved } else { (0.0, 0.0) }; + assert!( + (delta.0 - want.0).abs() < 1e-9 && (delta.1 - want.1).abs() < 1e-9, + "letters {letters}, marks {marks}: glyph {} moved {delta:?}, want {want:?}", + a.gid + ); + } + assert_eq!(marks_seen, 3, "the three fathas are marks"); + } +} + +/// Hebrew points count as diacritics as well as Arabic harakat; Latin accents and letters do not. +/// A boundary where only the diacritic positions differ asks for the character-level pass only +/// at such a mark. +#[test] +fn hebrew_points_and_harakat_are_diacritics() { + use crate::harakat::{diacritic_mark_boundary, is_diacritic}; + for c in ['\u{05B8}', '\u{05C1}', '\u{05BC}', '\u{064E}', '\u{0651}'] { + assert!(is_diacritic(c), "{c:?}"); + } + for c in ['\u{05D0}', '\u{0628}', '\u{0301}', 'a', '\u{05BE}'] { + assert!(!is_diacritic(c), "{c:?}"); + } + let a = style(FAMILY); + let b = CharStyle { diacritic_vertical: 150.0, ..a.clone() }; + assert!(diacritic_mark_boundary("שָׁ", 2, &a, &b), "a Hebrew point styled apart"); + assert!(diacritic_mark_boundary("بَ", 2, &a, &b), "a fatha styled apart"); + assert!(!diacritic_mark_boundary("e\u{301}", 1, &a, &b), "a Latin accent keeps its cluster's values"); + assert!(!diacritic_mark_boundary("بَ", 2, &a, &a), "the same values"); + let c = CharStyle { size: 20.0, ..b.clone() }; + assert!(!diacritic_mark_boundary("بَ", 2, &a, &c), "a size change splits the run anyway"); +} + /// A range is normalised as `edit::style_range` takes one: clamped, each end moved back to the /// start of its character, put in order. Never a silent empty result for a usable range. #[test] diff --git a/crates/ui-egui/src/dialogs/char_style_options.rs b/crates/ui-egui/src/dialogs/char_style_options.rs index 8915c48216..02515a3b89 100644 --- a/crates/ui-egui/src/dialogs/char_style_options.rs +++ b/crates/ui-egui/src/dialogs/char_style_options.rs @@ -26,13 +26,40 @@ const NUMBERS: &[&str] = &["size", "leading", "kerning", "tracking"]; /// The on, off or unset checkboxes. const SWITCHES: &[&str] = &["underline", "strikethrough", "standardVerticalRoman"]; /// The attributes of Advanced Character Formats, in the order the section shows them. -const ADVANCED: &[&str] = - &["h_scale", "v_scale", "baseline_shift", "tcyUpDown", "tcyLeftRight", "rotation", "akiLeft", "akiRight", "tsume", "language"]; +const ADVANCED: &[&str] = &[ + "h_scale", + "v_scale", + "baseline_shift", + "tcyUpDown", + "tcyLeftRight", + "rotation", + "akiLeft", + "akiRight", + "tsume", + "diacriticHorizontal", + "diacriticVertical", + "language", +]; /// The number fields of Advanced Character Formats. -const ADVANCED_NUMBERS: &[&str] = &["h_scale", "v_scale", "baseline_shift", "tcyUpDown", "tcyLeftRight", "rotation", "akiLeft", "akiRight", "tsume"]; +const ADVANCED_NUMBERS: &[&str] = &[ + "h_scale", + "v_scale", + "baseline_shift", + "tcyUpDown", + "tcyLeftRight", + "rotation", + "akiLeft", + "akiRight", + "tsume", + "diacriticHorizontal", + "diacriticVertical", +]; /// The Insert Aki Left and Right fields, which take the Character panel's presets and stop at /// [`vectorcraft_doc::text::MAX_AKI`]. const AKI: [&str; 2] = ["akiLeft", "akiRight"]; +/// The Adjust Horizontal and Vertical Diacritic Position fields, which take the Character panel's +/// presets and stop at [`vectorcraft_doc::text::MAX_DIACRITIC_POSITION`] either way. +const DIACRITIC: [&str; 2] = ["diacriticHorizontal", "diacriticVertical"]; /// The attributes of Character Color. const COLOR: &[&str] = &["fill", "stroke", "stroke_width", "overprint_fill", "overprint_stroke"]; /// The fields of Character Color: the fill and stroke paints, their tints in percent, the stroke @@ -103,6 +130,8 @@ pub(super) const SPEC: DialogSpec = DialogSpec { "akiLeft", "akiRight", "tsume", + "diacriticHorizontal", + "diacriticVertical", "language", "fill", "fill_tint", @@ -295,6 +324,8 @@ fn optional_number(d: &Dialog, key: &str) -> Result, String> { "akiLeft" => tl!("Insert Aki Left"), "akiRight" => tl!("Insert Aki Right"), "tsume" => tl!("Tsume"), + "diacriticHorizontal" => tl!("Adjust Horizontal Diacritic Position"), + "diacriticVertical" => tl!("Adjust Vertical Diacritic Position"), "fill_tint" => tl!("Fill Tint"), "stroke_tint" => tl!("Stroke Tint"), "stroke_width" => tl!("Weight"), @@ -344,6 +375,9 @@ fn optional_number(d: &Dialog, key: &str) -> Result, String> { let n = if AKI.contains(&key) { n.clamp(0.0, vectorcraft_doc::text::MAX_AKI) } else { n }; // Tsume stops at 0% and 100% the same way. let n = if key == "tsume" { n.clamp(0.0, vectorcraft_doc::text::MAX_TSUME) } else { n }; + // The diacritic positions stop at the largest value the style takes either way. + let max = vectorcraft_doc::text::MAX_DIACRITIC_POSITION; + let n = if DIACRITIC.contains(&key) { n.clamp(-max, max) } else { n }; Ok(Some(json!(n))) } } @@ -622,7 +656,7 @@ pub(crate) fn reset_basic(d: &mut Dialog) { } } -/// Reset Panel in Advanced Character Formats: its ten attributes become unset. +/// Reset Panel in Advanced Character Formats: its twelve attributes become unset. pub(crate) fn reset_advanced(d: &mut Dialog) { d.fields.insert("__resetAdvanced".into(), json!(true)); for key in ADVANCED_NUMBERS { @@ -777,8 +811,9 @@ pub(crate) fn basic_body(ui: &mut egui::Ui, d: &mut Dialog) { } /// Advanced Character Formats: Horizontal Scale, Vertical Scale, Baseline Shift, the Tate-chu-yoko -/// Up/Down and Left/Right, Character Rotation, Insert Aki Left and Right and Tsume (with the -/// Character panel's presets) and Language, each empty (unset) or set. +/// Up/Down and Left/Right, Character Rotation, Insert Aki Left and Right, Tsume and the Adjust +/// Horizontal and Vertical Diacritic Positions (with the Character panel's presets) and Language, +/// each empty (unset) or set. pub(crate) fn advanced_body(ui: &mut egui::Ui, d: &mut Dialog) { egui::Grid::new("character-style-advanced").num_columns(2).spacing([18.0, 8.0]).show(ui, |ui| { for (key, caption, unit) in [ @@ -820,6 +855,18 @@ pub(crate) fn advanced_body(ui: &mut egui::Ui, d: &mut Dialog) { ui.label("%"); }); ui.end_row(); + let presets: Vec = crate::panels::character::DIACRITIC_PRESETS.iter().map(f64::to_string).collect(); + let presets: Vec<&str> = presets.iter().map(String::as_str).collect(); + for (key, caption) in + [("diacriticHorizontal", tl!("Adjust Horizontal Diacritic Position")), ("diacriticVertical", tl!("Adjust Vertical Diacritic Position"))] + { + let row = ui.label(caption); + let value = if d.fields.get(key).is_none_or(Value::is_null) { String::new() } else { d.str(key) }; + if let Some(v) = ui.label_inputs_by(row.id, |ui| crate::widgets::text_presets(ui, (KIND, key), &value, &presets, 160.0)) { + d.fields.insert(key.into(), json!(v)); + } + ui.end_row(); + } let row = ui.label(tl!("Language:")); let names: Vec<&str> = std::iter::once(" ").chain(vectorcraft_doc::setup::LANGUAGES.iter().map(|(name, _, _)| *name)).collect(); let current = d.fields.get("language").and_then(Value::as_str).unwrap_or("").to_string(); @@ -1882,6 +1929,55 @@ mod tests { assert!(t.runs.iter().all(|r| (r.style.aki_left, r.style.aki_right) == (250.0, 1000.0))); } + /// The Adjust Diacritic Positions in Advanced Character Formats: empty is unset, a typed value + /// stops at -1000 and 1000, Reset Panel unsets them, and the fields are drawn and commit to the + /// style and the text set in it. + #[test] + fn diacritic_position_fields_show_set_reset_and_commit() { + let d = dialog_for(json!({"diacriticHorizontal": -250.0, "size": 12.0})); + assert_eq!((d.fields["diacriticHorizontal"].clone(), d.fields["diacriticVertical"].clone()), (json!(-250.0), json!(""))); + assert_eq!(edited_attrs(&d).unwrap(), attrs(json!({"diacriticHorizontal": -250.0, "size": 12.0}))); + let mut d = dialog_for(json!({"diacriticHorizontal": -250.0})); + d.fields.insert("diacriticHorizontal".into(), json!("")); + for (typed, kept) in [("0", 0.0), ("150", 150.0), ("5000", 1000.0), ("-5000", -1000.0)] { + d.fields.insert("diacriticVertical".into(), json!(typed)); + assert_eq!(edited_attrs(&d).unwrap(), attrs(json!({"diacriticVertical": kept})), "{typed}"); + } + d.fields.insert("diacriticHorizontal".into(), json!("left")); + assert_eq!(edited_attrs(&d).unwrap_err(), "Adjust Horizontal Diacritic Position must be a number"); + let mut d = dialog_for(json!({"diacriticHorizontal": 100.0, "diacriticVertical": 200.0, "size": 12.0})); + d.fields.insert("section".into(), json!("advanced")); + reset_section(&mut d); + assert_eq!(edited_attrs(&d).unwrap(), attrs(json!({"size": 12.0}))); + + let mut app = app(); + app.run("charStyle.new", json!({"name": "Body", "attrs": {"size": 24.0}})).unwrap(); + let id = app.run("text.create", json!({"x": 10, "y": 40, "text": "بَب"})).unwrap()["id"].as_u64().unwrap(); + app.run("charStyle.apply", json!({"name": "Body", "id": id})).unwrap(); + open(&mut app, "Body").unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(900.0, 900.0)); + let mut d = app.ui.dialog.clone().unwrap(); + let input = egui::RawInput { screen_rect: Some(screen), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| advanced_body(ui, &mut d)); + let texts = texts_of(&out); + out.textures_delta.clear(); + for label in ["Adjust Horizontal Diacritic Position", "Adjust Vertical Diacritic Position"] { + assert!(texts.iter().any(|(text, _)| text == label), "{label} is drawn: {texts:?}"); + } + { + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("diacriticHorizontal".into(), json!("-120")); + d.fields.insert("diacriticVertical".into(), json!("3000")); + } + super::super::confirm(&mut app).unwrap(); + let state = app.session.doc().unwrap(); + assert_eq!(state.doc.char_styles[0].attrs, attrs(json!({"size": 24.0, "diacriticHorizontal": -120.0, "diacriticVertical": 1000.0}))); + let vectorcraft_doc::NodeKind::Text(t) = &state.doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind else { panic!("text") }; + assert!(t.runs.iter().all(|r| (r.style.diacritic_horizontal, r.style.diacritic_vertical) == (-120.0, 1000.0))); + } + /// Tsume in Advanced Character Formats: empty is unset, an explicit 0 stays set, a typed value /// stops at 0 and 100, Reset Panel unsets it, and the field is drawn and commits to the style /// and the text set in it. diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 948b295e17..632ba4cb06 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -2598,6 +2598,8 @@ font-technology Variable Променливи Insert Aki Left Вмъкване на аки отляво Insert Aki Right Вмъкване на аки отдясно Tsume Цуме + Adjust Horizontal Diacritic Position Коригиране на хоризонталната позиция на диакритиците + Adjust Vertical Diacritic Position Коригиране на вертикалната позиция на диакритиците Character Direction Посока на знаците Digits Цифри Arabic Арабски diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index f8d6fa263b..11e6ad182c 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -1589,6 +1589,8 @@ lighting Light Svjetlo Insert Aki Left Umetni aki lijevo Insert Aki Right Umetni aki desno Tsume Tsume + Adjust Horizontal Diacritic Position Podesi vodoravni položaj dijakritika + Adjust Vertical Diacritic Position Podesi okomiti položaj dijakritika Character Direction Smjer znakova Digits Cifre Arabic Arapski diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 3ed3ca8331..3622512c2d 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -3367,6 +3367,8 @@ digits Malayalam Malaiàlam Insert Aki Left Insereix aki a l'esquerra Insert Aki Right Insereix aki a la dreta Tsume Tsume + Adjust Horizontal Diacritic Position Ajusta la posició horitzontal dels diacrítics + Adjust Vertical Diacritic Position Ajusta la posició vertical dels diacrítics Proportional Lining Xifres proporcionals alineades Position: Posició: Default Position Posició predeterminada diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 161e235c56..0b6aceda0a 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1617,6 +1617,8 @@ lighting Light Světlo Insert Aki Left Vložit aki vlevo Insert Aki Right Vložit aki vpravo Tsume Tsume + Adjust Horizontal Diacritic Position Upravit vodorovnou polohu diakritiky + Adjust Vertical Diacritic Position Upravit svislou polohu diakritiky Character Direction Směr znaků Digits Číslice Arabic Arabské diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index fd0b7c042e..aac2f9dd7a 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -2134,6 +2134,8 @@ lighting Light Lys Insert Aki Left Indsæt aki til venstre Insert Aki Right Indsæt aki til højre Tsume Tsume + Adjust Horizontal Diacritic Position Juster vandret placering af diakritiske tegn + Adjust Vertical Diacritic Position Juster lodret placering af diakritiske tegn Character Direction Tegnretning Digits Cifre Arabic Arabisk diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 2a5f32a5d9..2be671ca22 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -2642,6 +2642,8 @@ mark-style Japanese Japanisch Insert Aki Left Aki links einfügen Insert Aki Right Aki rechts einfügen Tsume Tsume + Adjust Horizontal Diacritic Position Horizontale Position diakritischer Zeichen anpassen + Adjust Vertical Diacritic Position Vertikale Position diakritischer Zeichen anpassen Character Direction Zeichenrichtung Digits Ziffern Arabic Arabisch diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index b1b7b4d039..1ca28c8ff6 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -3439,6 +3439,8 @@ theme Appearance Εμφάνιση Insert Aki Left Εισαγωγή aki αριστερά Insert Aki Right Εισαγωγή aki δεξιά Tsume Tsume + Adjust Horizontal Diacritic Position Προσαρμογή οριζόντιας θέσης διακριτικών + Adjust Vertical Diacritic Position Προσαρμογή κατακόρυφης θέσης διακριτικών Arabic Αραβικά Hindi Χίντι Farsi Περσικά diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 5b3c675f7b..cff46bf68e 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -2676,6 +2676,8 @@ font-technology Variable Variables Insert Aki Left Insertar aki a la izquierda Insert Aki Right Insertar aki a la derecha Tsume Tsume + Adjust Horizontal Diacritic Position Ajustar posición horizontal de los diacríticos + Adjust Vertical Diacritic Position Ajustar posición vertical de los diacríticos Character Direction Dirección de caracteres Digits Dígitos Arabic Árabes diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index e77a617c52..49f96667b0 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -1592,6 +1592,8 @@ lighting Light Valo Insert Aki Left Lisää aki vasemmalle Insert Aki Right Lisää aki oikealle Tsume Tsume + Adjust Horizontal Diacritic Position Säädä tarkkeiden vaakasijaintia + Adjust Vertical Diacritic Position Säädä tarkkeiden pystysijaintia Character Direction Merkkien suunta Digits Numerot Arabic Arabia diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 2762d2a954..6f1b854373 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -2668,6 +2668,8 @@ font-technology Variable Variables Insert Aki Left Insérer un aki à gauche Insert Aki Right Insérer un aki à droite Tsume Tsume + Adjust Horizontal Diacritic Position Ajuster la position horizontale des signes diacritiques + Adjust Vertical Diacritic Position Ajuster la position verticale des signes diacritiques Character Direction Direction des caractères Digits Chiffres Arabic Arabes diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 1c96900b2b..6eee1d7d0f 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -4381,6 +4381,8 @@ antiAlias Sharp શાર્પ Preview: પ્રીવ્યૂ: Insert Aki Left ડાબે અકી ઉમેરો Insert Aki Right જમણે અકી ઉમેરો + Adjust Horizontal Diacritic Position ડાયાક્રિટિકની આડી સ્થિતિ ગોઠવો + Adjust Vertical Diacritic Position ડાયાક્રિટિકની ઊભી સ્થિતિ ગોઠવો Conic Gradient કોનિક ગ્રેડિયન્ટ Diamond Gradient ડાયમંડ ગ્રેડિયન્ટ Include Placed Images પ્લેસ કરેલી ઇમેજો સામેલ કરો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 548f961f51..fa3a5a4cf8 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -3714,6 +3714,8 @@ antiAlias Sharp शार्प Insert Aki Left बाईं ओर आकी जोड़ें Insert Aki Right दाईं ओर आकी जोड़ें Tsume त्सुमे + Adjust Horizontal Diacritic Position डायक्रिटिक की क्षैतिज स्थिति समायोजित करें + Adjust Vertical Diacritic Position डायक्रिटिक की लंबवत स्थिति समायोजित करें Proportional Oldstyle आनुपातिक ओल्डस्टाइल Protect Corners कॉर्नर को सुरक्षित रखें Proximity Guides निकटता गाइड diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 200b45d1b1..17fb9430a1 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -3233,6 +3233,8 @@ mark-style Japanese Japán Insert Aki Left Aki beszúrása balra Insert Aki Right Aki beszúrása jobbra Tsume Tsume + Adjust Horizontal Diacritic Position Mellékjelek vízszintes helyzetének igazítása + Adjust Vertical Diacritic Position Mellékjelek függőleges helyzetének igazítása Proportional Lining Arányos modern Position: Pozíció: Default Position Alapértelmezett pozíció diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index f3dcca3874..613d45b370 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -1525,6 +1525,8 @@ lighting Light Cahaya Insert Aki Left Sisipkan aki kiri Insert Aki Right Sisipkan aki kanan Tsume Tsume + Adjust Horizontal Diacritic Position Sesuaikan posisi horizontal diakritik + Adjust Vertical Diacritic Position Sesuaikan posisi vertikal diakritik Character Direction Arah karakter Digits Digit Arabic Arab diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 90ec79404c..27e8fd40c6 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -2718,6 +2718,8 @@ mark-style Japanese Giapponese Insert Aki Left Inserisci aki a sinistra Insert Aki Right Inserisci aki a destra Tsume Tsume + Adjust Horizontal Diacritic Position Regola posizione orizzontale dei segni diacritici + Adjust Vertical Diacritic Position Regola posizione verticale dei segni diacritici Character Direction Direzione caratteri Digits Cifre Arabic Arabe diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index d98acfa22d..3ae17e5abb 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -55,6 +55,8 @@ font-technology Variable バリアブル Insert Aki Left 前にアキを挿入 Insert Aki Right 後ろにアキを挿入 Tsume 文字ツメ + Adjust Horizontal Diacritic Position 発音区別符号の水平位置を調整 + Adjust Vertical Diacritic Position 発音区別符号の垂直位置を調整 Character Direction 文字の方向 Digits 数字 Arabic アラビア数字 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 794e5454a9..8228dfebbb 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -1462,6 +1462,8 @@ lighting Light სინათლე Insert Aki Left აკის ჩასმა მარცხნივ Insert Aki Right აკის ჩასმა მარჯვნივ Tsume ცუმე + Adjust Horizontal Diacritic Position დიაკრიტიკის ჰორიზონტალური პოზიციის მორგება + Adjust Vertical Diacritic Position დიაკრიტიკის ვერტიკალური პოზიციის მორგება Character Direction სიმბოლოების მიმართულება Digits ციფრები Arabic არაბული diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index bb8676df71..0b8fcf490a 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -49,6 +49,8 @@ font-technology Variable 가변 Insert Aki Left 앞 아키 삽입 Insert Aki Right 뒤 아키 삽입 Tsume 츠메 + Adjust Horizontal Diacritic Position 발음 구별 기호 가로 위치 조정 + Adjust Vertical Diacritic Position 발음 구별 기호 세로 위치 조정 Character Direction 문자 방향 Digits 숫자 Arabic 아라비아어 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index a597a03fd0..4369f2e89b 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -2043,6 +2043,8 @@ lighting Light Licht Insert Aki Left Aki links invoegen Insert Aki Right Aki rechts invoegen Tsume Tsume + Adjust Horizontal Diacritic Position Horizontale positie van diakritische tekens aanpassen + Adjust Vertical Diacritic Position Verticale positie van diakritische tekens aanpassen Character Direction Tekenrichting Digits Cijfers Arabic Arabisch diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 99ee2080b8..cd19504fea 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -1530,6 +1530,8 @@ lighting Light Światło Insert Aki Left Wstaw aki z lewej Insert Aki Right Wstaw aki z prawej Tsume Tsume + Adjust Horizontal Diacritic Position Dostosuj poziome położenie znaków diakrytycznych + Adjust Vertical Diacritic Position Dostosuj pionowe położenie znaków diakrytycznych Character Direction Kierunek znaków Digits Cyfry Arabic Arabskie diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 677c8e460f..e4b68bfa9a 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -2240,6 +2240,8 @@ antiAlias Sharp Nítido Insert Aki Left Inserir Aki à Esquerda Insert Aki Right Inserir Aki à Direita Tsume Tsume + Adjust Horizontal Diacritic Position Ajustar Posição Horizontal dos Diacríticos + Adjust Vertical Diacritic Position Ajustar Posição Vertical dos Diacríticos Character Direction Direção de Caracteres Digits Dígitos Arabic Arábicos diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 106343cddd..36dee93d9f 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -2705,6 +2705,8 @@ mark-style Japanese Японский Insert Aki Left Вставить аки слева Insert Aki Right Вставить аки справа Tsume Цумэ + Adjust Horizontal Diacritic Position Настроить горизонтальное положение диакритических знаков + Adjust Vertical Diacritic Position Настроить вертикальное положение диакритических знаков Character Direction Направление символов Digits Цифры Arabic Арабские diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index cc854aa362..ca48397e4e 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -2613,6 +2613,8 @@ font-technology Variable Variabla Insert Aki Left Infoga aki till vänster Insert Aki Right Infoga aki till höger Tsume Tsume + Adjust Horizontal Diacritic Position Justera vågrät position för diakritiska tecken + Adjust Vertical Diacritic Position Justera lodrät position för diakritiska tecken Character Direction Teckenriktning Digits Siffror Arabic Arabiska diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index f2888a30f0..45cf7540ca 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -2460,6 +2460,8 @@ shape Open Açık Insert Aki Left Sola Aki Ekle Insert Aki Right Sağa Aki Ekle Tsume Tsume + Adjust Horizontal Diacritic Position Yatay Aksan İşareti Konumunu Ayarla + Adjust Vertical Diacritic Position Dikey Aksan İşareti Konumunu Ayarla Digits Rakamlar Arabic Arapça Hindi Hintçe diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 411b2c3baf..0c9e86ac0c 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -2710,6 +2710,8 @@ mark-style Japanese Японський Insert Aki Left Вставити акі ліворуч Insert Aki Right Вставити акі праворуч Tsume Цуме + Adjust Horizontal Diacritic Position Налаштувати горизонтальне положення діакритичних знаків + Adjust Vertical Diacritic Position Налаштувати вертикальне положення діакритичних знаків Character Direction Напрямок символів Digits Цифри Arabic Арабські diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 1460910197..0e81bd1a2f 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3022,6 +3022,8 @@ mark-style Japanese Kiểu Nhật Insert Aki Left Chèn aki bên trái Insert Aki Right Chèn aki bên phải Tsume Tsume + Adjust Horizontal Diacritic Position Điều chỉnh vị trí ngang của dấu phụ + Adjust Vertical Diacritic Position Điều chỉnh vị trí dọc của dấu phụ Proportional Lining Số tỷ lệ đứng Position: Vị trí: Default Position Vị trí mặc định diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 3fe2f9e009..e32526d75b 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -2572,6 +2572,8 @@ font-script Japanese 汉字 Insert Aki Left 在前方插入空白 Insert Aki Right 在后方插入空白 Tsume 比例间距 + Adjust Horizontal Diacritic Position 调整变音符号水平位置 + Adjust Vertical Diacritic Position 调整变音符号垂直位置 Character Direction 字符方向 Digits 数字 Arabic 阿拉伯数字 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index ab7f9d9dd2..8cea64775b 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -3792,6 +3792,8 @@ font-script Japanese 漢字 Insert Aki Left 在前方插入空白 Insert Aki Right 在後方插入空白 Tsume 比例間距 + Adjust Horizontal Diacritic Position 調整變音符號水平位置 + Adjust Vertical Diacritic Position 調整變音符號垂直位置 Character Direction 字元方向 Digits 數字 Arabic 阿拉伯數字 diff --git a/crates/ui-egui/src/panels/character.rs b/crates/ui-egui/src/panels/character.rs index 32de20ec95..746a8fbdf4 100644 --- a/crates/ui-egui/src/panels/character.rs +++ b/crates/ui-egui/src/panels/character.rs @@ -28,6 +28,8 @@ pub const SCALE_PRESETS: [f64; 8] = [25.0, 50.0, 75.0, 90.0, 100.0, 110.0, 125.0 pub const AKI_PRESETS: [f64; 4] = [0.0, 250.0, 500.0, 1000.0]; /// Tsume presets, in percent. pub const TSUME_PRESETS: [f64; 5] = [0.0, 25.0, 50.0, 75.0, 100.0]; +/// Adjust Horizontal and Vertical Diacritic Position presets, in thousandths of an em. +pub const DIACRITIC_PRESETS: [f64; 7] = [-200.0, -100.0, -50.0, 0.0, 50.0, 100.0, 200.0]; /// The stored character style: the selected range's (or the caret's) while the Type /// tool edits text, else the first selected text object's first run (including groups). With it, the paragraph @@ -881,9 +883,10 @@ fn cell(ui: &mut Ui, label: &str, tip: &str, add: impl FnOnce(&mut Ui)) { /// The Character panel's grid of fields, `w` wide: Font Size, Leading, Kerning and Tracking, /// then with `more` the scales, Baseline Shift and Character Rotation, and a row with the /// Anti-aliasing Method dropdown under Character Rotation (`s`: the style shown), and with Show East -/// Asian Options on a row with Insert Aki Left and Right and a row with Tsume. With Show Font -/// Height Options on, a row under Font Size holds the Set Font Height Reference dropdown. The -/// Properties panel shows its first rows. +/// Asian Options on a row with Insert Aki Left and Right and a row with Tsume, and with Show Indic +/// Options (the Middle Eastern options) on a row with Adjust Horizontal and Vertical Diacritic +/// Position. With Show Font Height Options on, a row under Font Size holds the Set Font Height +/// Reference dropdown. The Properties panel shows its first rows. pub(crate) fn metrics_grid(app: &mut VectorcraftApp, ui: &mut Ui, id: &str, s: &CharStyle, w: f32, more: bool) { let fw = ((w - 66.0) / 2.0).clamp(60.0, 100.0); let unit = app.session.type_unit(); @@ -986,6 +989,24 @@ pub(crate) fn metrics_grid(app: &mut VectorcraftApp, ui: &mut Ui, id: &str, s: & }); ui.end_row(); } + // Adjust Horizontal and Vertical Diacritic Position, with the Middle Eastern options: the + // marks of the characters move across and up, in thousandths of an em. + if app.session.prefs.show_indic_options { + let max = vectorcraft_doc::text::MAX_DIACRITIC_POSITION; + for (field, label, key, icon) in [ + ("ch-diacritic-h", tl!("Adjust Horizontal Diacritic Position"), "diacriticHorizontal", "´↔"), + ("ch-diacritic-v", tl!("Adjust Vertical Diacritic Position"), "diacriticVertical", "´↕"), + ] { + cell(ui, icon, label, |ui| { + let value = shared(app, |s| if key == "diacriticHorizontal" { s.diacritic_horizontal } else { s.diacritic_vertical }); + if let Some(v) = widgets::spin_plain(ui, field, value, "", 0, fw, 10.0, -max, &DIACRITIC_PRESETS) { + // The field stops at the largest value the command takes. + format(app, json!({ key: v.min(max) })); + } + }); + } + ui.end_row(); + } }); } @@ -1730,7 +1751,8 @@ fn fractional_widths_on(app: &VectorcraftApp) -> bool { /// character alignment, Proportional Metrics, Tate-chu-yoko, Warichu, Standard Vertical Roman Alignment and /// No Break off, Tate-chu-yoko Settings Up/Down and Left/Right 0, the default Warichu Settings (2 lines, no /// line gap, 50%, Auto alignment), Insert Aki Left and Right 0, Tsume 0, the Default character direction, -/// Kashidas on, the Default digits and the Em Box font height reference, whether or not Show East Asian +/// Kashidas on, the Default digits, Adjust Horizontal and Vertical Diacritic Position 0 and the Em Box +/// font height reference, whether or not Show East Asian /// Options, Show Indic Options and Show Font Height Options are on. Inside an undo group that is /// already open, the reset is part of that group's step. fn reset_panel(app: &mut VectorcraftApp) { @@ -1752,7 +1774,8 @@ fn reset_panel(app: &mut VectorcraftApp) { "tsume": d.tsume, "warichu": d.warichu, "warichuLines": d.warichu_lines, "warichuGap": d.warichu_gap, "warichuScale": d.warichu_scale, "warichuAlign": d.warichu_align, "standardVerticalRoman": d.standard_vertical_roman, "noBreak": d.no_break, "charDirection": "default", "kashidas": d.kashidas, - "digits": d.digits, "fontHeightReference": d.font_height_reference + "digits": d.digits, "diacriticHorizontal": d.diacritic_horizontal, "diacriticVertical": d.diacritic_vertical, + "fontHeightReference": d.font_height_reference }), ); set_anti_alias(app, TypeAntiAlias::Sharp); diff --git a/crates/ui-egui/src/panels/character/tests.rs b/crates/ui-egui/src/panels/character/tests.rs index adaf523e53..1e3e6acec4 100644 --- a/crates/ui-egui/src/panels/character/tests.rs +++ b/crates/ui-egui/src/panels/character/tests.rs @@ -782,6 +782,57 @@ fn insert_aki_fields_show_with_the_east_asian_options() { assert!(left(&app).iter().all(|v| *v == 1000.0), "{:?}", left(&app)); } +/// Adjust Horizontal and Vertical Diacritic Position are fields of the panel with the Middle +/// Eastern options only, and show the selected characters' values, blank where they differ. A value +/// typed past -1000 sets -1000. Bad values sent to the commands are errors that change nothing. +#[test] +fn diacritic_position_fields_show_with_the_middle_eastern_options() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let id = app.run("text.create", json!({"x": 20, "y": 50, "text": "بَبَ"})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + app.run("text.setFormat", json!({"diacriticHorizontal": 125, "diacriticVertical": -375})).unwrap(); + let text = crate::tests_labels::painted_text(&mut app, show); + assert!(!text.contains("´↔") && !text.contains("-375"), "{text}"); + app.session.prefs.show_indic_options = true; + let text = crate::tests_labels::painted_text(&mut app, show); + assert!(text.contains("´↔") && text.contains("´↕") && text.contains("125") && text.contains("-375"), "{text}"); + let undo = app.session.active().unwrap().history.undo.len(); + let doc = app.session.active().unwrap().doc.clone(); + for (cmd, params) in [ + ("text.setFormat", json!({"diacriticHorizontal": 1000.5})), + ("text.setFormat", json!({"diacriticVertical": "up"})), + ("text.setRangeStyle", json!({"id": id, "start": 0, "end": 2, "diacriticVertical": -1001})), + ("text.setRangeStyle", json!({"id": id, "start": 0, "end": 2, "diacriticHorizontal": true})), + ] { + let error = app.run(cmd, params.clone()).unwrap_err().to_string(); + assert!(error.contains("`diacritic"), "{cmd} {params}: {error}"); + } + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert!(app.session.active().unwrap().doc == doc); + // Setting the value the characters already have records no undo step. + app.run("text.setFormat", json!({"diacriticVertical": -375})).unwrap(); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + // Only the first letter and its fatha have -375: the Vertical field is blank. + app.run("text.setRangeStyle", json!({"id": id, "start": 4, "end": 8, "diacriticVertical": 0})).unwrap(); + let text = crate::tests_labels::painted_text(&mut app, show); + assert!(text.contains("125") && !text.contains("-375"), "{text}"); + use super::super::tests_appearance::{click, frame_events, text_rect}; + let ctx = egui::Context::default(); + let texts = frame_events(&ctx, &mut app, vec![], show); + click(&ctx, &mut app, text_rect(&texts, "125").center(), show); + let key = |key, modifiers| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }; + frame_events(&ctx, &mut app, vec![key(egui::Key::A, egui::Modifiers::COMMAND)], show); + frame_events(&ctx, &mut app, vec![egui::Event::Text("-1500".into())], show); + frame_events(&ctx, &mut app, vec![key(egui::Key::Enter, egui::Modifiers::NONE)], show); + frame_events(&ctx, &mut app, vec![], show); + let horizontal = |app: &VectorcraftApp| match &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => t.runs.iter().map(|r| r.style.diacritic_horizontal).collect::>(), + _ => panic!("text"), + }; + assert!(horizontal(&app).iter().all(|v| *v == -1000.0), "{:?}", horizontal(&app)); +} + /// Tsume is a field of the panel with the East Asian options only, and shows the selected /// characters' value, blank where they differ. A value typed past 100 sets 100. #[test] @@ -1487,6 +1538,8 @@ fn reset_panel_resets_every_attribute_but_the_font() { s.char_direction != d.char_direction, s.digits != d.digits, s.font_height_reference != d.font_height_reference, + s.diacritic_horizontal != d.diacritic_horizontal, + s.diacritic_vertical != d.diacritic_vertical, ] }; let custom = |app: &mut VectorcraftApp| { @@ -1496,16 +1549,17 @@ fn reset_panel_resets_every_attribute_but_the_font() { "id": id, "tracking": 50, "leading": 30, "kerning": 20, "baselineShift": 3, "hScale": 120, "vScale": 90, "rotation": 15, "underline": true, "strikethrough": true, "allCaps": true, "smallCaps": true, "position": "superscript", "charAlign": "emBoxCenter", "proportionalMetrics": true, "tateChuYoko": true, "tcyUpDown": 2, "tcyLeftRight": -3, - "akiLeft": 250, "akiRight": 500, "tsume": 50, "standardVerticalRoman": true, "noBreak": true, "charDirection": "rightToLeft", "digits": "hindi", "fontHeightReference": "capHeight" + "akiLeft": 250, "akiRight": 500, "tsume": 50, "standardVerticalRoman": true, "noBreak": true, "charDirection": "rightToLeft", "digits": "hindi", "fontHeightReference": "capHeight", + "diacriticHorizontal": 120, "diacriticVertical": -80 }), ) .unwrap(); }; let plain = runs(&app)[0].1.clone(); - assert_eq!(differs(&plain, &CharStyle::default()), [false; 25]); + assert_eq!(differs(&plain, &CharStyle::default()), [false; 27]); custom(&mut app); let styled = runs(&app)[0].1.clone(); - assert_eq!(differs(&styled, &CharStyle::default()), [true; 25]); + assert_eq!(differs(&styled, &CharStyle::default()), [true; 27]); app.run("select.set", json!({"ids": [id]})).unwrap(); reset_panel(&mut app); assert_eq!(runs(&app), [("One 12".to_string(), plain.clone())]); diff --git a/docs/mcp.md b/docs/mcp.md index 8ca4121032..d00c10decc 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9696,6 +9696,30 @@ A digit the font lacks comes from a fallback font. Default and saved only when s {"name":"run_command","arguments":{"command":"text.setFormat","params":{"digits":"hindi"}}} ``` +## Adjust Diacritic Position + +`text.setFormat {diacriticHorizontal?, diacriticVertical?}` (the selected type, or `ids`) and +`text.setRangeStyle {id, start, end, diacriticHorizontal?, diacriticVertical?}` (a range) move the characters' diacritical +marks relative to their letters, as the Character panel's Adjust Horizontal and Adjust Vertical Diacritic Position do +([the reference, page 549](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=549)). +The units, range and direction are VectorCraft's own rules: each value is in thousandths of an em of the characters' size, +from -1000 to 1000; a positive horizontal value moves the marks right and a positive vertical value moves them up. Only +glyphs the font classes as marks (GDEF class 3) move; the letters keep their places and advances, and a font without +mark classes moves nothing. An Arabic harakat or a Hebrew point styled apart from its letter takes its own values; +other marks take the values of their letter. Setting one value leaves the other as it is. Both are 0 by default and +saved only when not 0, and character styles carry them (`charStyle.new`, `charStyle.setAttrs` and `charStyle.edit` +refuse a value outside the range). A value that is not a number is refused with `` `diacriticHorizontal` must be a +number ``, and one outside the range with `` `diacriticHorizontal` must be from -1000 to 1000 ``, naming the key. One +undo step, and a `text.setFormat` call that gives the values the characters already have records none. With Show Middle Eastern +Options on, the Character panel shows both fields, blank where the selected characters differ, with -200, -100, -50, +0, 50, 100 and 200 in their menus, and a value typed past either end sets that end; Reset Panel sets both to 0. +Character Style Options shows both fields in Advanced Character Formats. The canvas, PDF export and outlines draw the +moved marks; SVG export writes type with a moved mark as outlines. + +```json +{"name":"run_command","arguments":{"command":"text.setRangeStyle","params":{"id":12,"start":2,"end":4,"diacriticVertical":150}}} +``` + ## Font height reference `text.setFormat {fontHeightReference: "emBox"|"capHeight"|"xHeight"|"icfBox"}` (the selected type, or `ids`) and @@ -10017,7 +10041,7 @@ attribute map in one undo step. `to` is trimmed and must be unique. The command while preserving local overrides; Undo/Redo restores the definition and its users. The `charStyleOptions` dialog exposes `name`, `font_family`, `font_style`, `size`, `leading`, `kerning`, `tracking`, `case`, `position`, `underline`, `strikethrough`, `charAlign`, `h_scale`, `v_scale`, `baseline_shift`, `tcyUpDown`, -`tcyLeftRight`, `rotation`, `akiLeft`, `akiRight`, `tsume`, `language`, `fill`, `fill_tint`, `stroke`, `stroke_tint`, `stroke_width`, `overprint_fill`, `overprint_stroke`, +`tcyLeftRight`, `rotation`, `akiLeft`, `akiRight`, `tsume`, `diacriticHorizontal`, `diacriticVertical`, `language`, `fill`, `fill_tint`, `stroke`, `stroke_tint`, `stroke_width`, `overprint_fill`, `overprint_stroke`, `ot_figure`, `ot_position`, `ot_liga`, `ot_calt`, `ot_dlig`, `ot_swsh`, `ot_salt`, `ot_titl`, `ot_ordn`, `ot_frac`, `ot_sets`, `section` (`general`, `basic`, `advanced`, `color` or `opentype`), and `preview`. An empty field leaves its attribute unset. `leading` and `kerning` also accept `Auto` to store an explicit automatic value. @@ -10026,7 +10050,9 @@ Advanced Character Formats holds `h_scale` and `v_scale` (percent, 1 to 10000), -1296 to 1296, as `text.setRangeStyle` takes them; an explicit 0 stays distinct from unset), `rotation` (degrees, stored from -180 to 180), Insert Aki Left and Right `akiLeft` and `akiRight` (thousandths of an em, with the Character panel's 0, 250, 500 and 1000 in their menus; a value typed below 0 or past 1000 sets 0 or 1000), Tsume `tsume` (percent, with the Character panel's 0, 25, 50, 75 and 100 in its menu; a value typed below 0 or -past 100 sets 0 or 100; an explicit 0 stays distinct from unset) and `language` (a name or tag from Document +past 100 sets 0 or 100; an explicit 0 stays distinct from unset), Adjust Horizontal and Vertical Diacritic Position +`diacriticHorizontal` and `diacriticVertical` (thousandths of an em, with the Character panel's -200, -100, -50, 0, 50, +100 and 200 in their menus; a value typed below -1000 or past 1000 sets -1000 or 1000) and `language` (a name or tag from Document Setup's languages; English: USA stores the explicit default `null`, and a tag not in the list that the style already has is kept). Language sets the language the characters are shaped in; it does not change hyphenation or spelling. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f4424700be..fa30157c24 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1437,6 +1437,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Paragraph panel's Insert Kashidas (with the Indic options; `text.setFormat {kashida}`) lengthens each Arabic word of a justified horizontal area type line with a kashida, a tatweel between its last pair of joined letters, before the word spaces widen: Short, Medium and Long kashidas are at most a quarter, half and a whole em long, Stylistic ones are whole tatweels up to an em, and None (the default) leaves the line as before; paragraph styles and the native file keep the setting. The Character panel menu's Kashidas switch (with the Indic options; `text.setFormat` / `text.setRangeStyle {kashidas}`) allows Kashidas on selected characters, on by default for new and old text. A pair of joined letters receives one only when both characters allow it; turning one off leaves other eligible pairs in the word available. Character styles and the native file keep the switch. [Public help](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/justify-text-using-kashida-and-hyphenation.html) documents the menu control and the separate paragraph length choices; the default and pair rule are VectorCraft choices. Paint-only Arabic harakat (marks whose character styles differ only in fill, stroke and related paint) stay inside one shaping cluster so letters keep their joining forms; when a second character-level shaping pass matches the monotone glyphs, a glyph may take a later in-cluster character's run only when GDEF classifies it as a mark (class 3) and that character is a harakat; otherwise it keeps the shaping cluster's first character. Insert Kashidas tatweels take the base letter's paint rather than a trailing mark's. Fonts without GDEF and some AAT/`morx` ligatures can leave a mark painted as its letter (`crates/text/src/tests/harakat.rs`). + Character panel › Adjust Horizontal and Adjust Vertical Diacritic Position (with the Middle Eastern options; `text.setFormat` or `text.setRangeStyle {diacriticHorizontal, diacriticVertical}`, VectorCraft's own thousandths of an em from -1000 to 1000, 0 by default) move the selected characters' mark glyphs (GDEF class 3) right or left and up or down while the letters stay in place ([the reference, page 549](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=549)); an Arabic harakat or Hebrew point styled apart takes its own values, character styles carry both (Character Style Options › Advanced Character Formats edits them), the canvas and PDF draw the moved marks and SVG writes such type as outlines (`tests::harakat::diacritic_positions_move_marks_and_keep_letters`). The Paragraph panel's Bullets button, Type › Bullets and Numbering › Apply Bullets and the context menu's Apply Bullets (`text.setFormat {list, bullet}`, `type.applyBullets`) make paragraphs a bulleted list with the documented presets (none, filled dot, dash, hollow circle, filled square; [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)): the bullet starts each paragraph's first line in its first character's font, size and color, the first line's text starts at the next tab stop after the bullet (the left indent counts as a stop), the lines it wraps to start at the left indent, a paragraph with no indents gets 18 pt and -18 pt, and Return continues the list; Reset Panel turns it off, and paragraph styles and the native file keep it. The Paragraph panel's Bullets button, Type › Bullets and Numbering › Apply Bullets and the context menu's Apply Bullets (`text.setFormat {list, bullet}`, `type.applyBullets`) make paragraphs a bulleted list with the documented presets (none, filled dot, dash, hollow circle, filled square; [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)): the bullet starts each paragraph's first line in its first character's font, size and color, the first line's text starts at the next tab stop after the bullet (the left indent counts as a stop), the lines it wraps to start at the left indent, a paragraph with no indents gets 18 pt and -18 pt, and Return continues the list; Reset Panel turns it off, and paragraph styles and the native file keep it. The Bullets and Numbering dialog, levels and Convert to Text are not built yet. 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. diff --git a/docs/type-parity.md b/docs/type-parity.md index fa76290e94..150c495d97 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -62,6 +62,7 @@ against Illustrator's public documentation; **estimated** unless noted. | Middle Eastern: bidirectional layout, Paragraph Direction | done | 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 still needs ActualText support (#6165); separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. | | Middle Eastern and Indic: digit types (Character panel menu › Digits: Default, Arabic, Hindi, Farsi; Devanagari, Bengali, Gurmukhi, Gujarati, Odia, Tamil, Telugu, Kannada, Malayalam) | done | `text.setFormat` / `text.setRangeStyle {digits}` (`"devanagari"`, `"bengali"`, `"gurmukhi"`, `"gujarati"`, `"odia"`, `"tamil"`, `"telugu"`, `"kannada"`, `"malayalam"` added, #4942); the text keeps the typed digits, the glyphs and SVG export follow the style; carried by character styles. Not yet: `.ai` export of the setting; Indic digits typed as such stay as typed under another system. Evidence: `text::tests::indic_digits_map_to_their_scripts_block`, `tests::bidi::indic_digits_draw_the_scripts_own_digits`, `typecmd::area_tests::indic_digits_round_trip_through_the_commands_and_the_file` | | Middle Eastern: Kashidas | done | Paragraph Insert Kashidas sets the length for justified Arabic area type; Character-menu Kashidas allows or excludes selected characters, on by default. A kashida is inserted only between two allowed joined characters. The character switch is retained in character styles and the native file; the length is retained in paragraph styles and the native file. Paint-only harakat (coloured or hidden marks) stay in one shaping cluster so letters keep joining; when the character-level pass matches, a glyph may take a later in-cluster character's run only if GDEF names it a mark (class 3) and that character is a harakat—otherwise the cluster start (a mark may miss its colour; a base never takes a mark's). Inserted tatweels take the base letter's paint—not a trailing mark's. Fonts without GDEF and some AAT/`morx` ligatures (e.g. Geeza Pro Allah) can leave a mark painted as its letter. No Character-panel harakat colour command yet. Evidence: `tests::harakat`. [Public help](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/justify-text-using-kashida-and-hyphenation.html). | +| Middle Eastern: Adjust Horizontal and Vertical Diacritic Position | done | `text.setFormat` / `text.setRangeStyle {diacriticHorizontal, diacriticVertical}` and the Character panel's fields (with the Middle Eastern options) move mark glyphs (GDEF class 3) by VectorCraft's own thousandths of an em, -1000 to 1000; letters keep their places, harakat and Hebrew points styled apart take their own values, character styles and the native file keep both, and SVG writes such type as outlines. Not yet: `.ai` import and export of the values. Evidence: `tests::harakat::diacritic_positions_move_marks_and_keep_letters`. [Reference, page 549](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=549). | | Middle Eastern: Middle Eastern composers, split caret | missing | Character Direction is done; editable bidirectional SVG text remains incomplete. | | CJK: input methods (marked text, candidate window) | done | | | CJK: kinsoku (Hard, Soft, None), the predefined mojikumi sets (None, YakumonoHankaku, GyomatsuYakumonoHankaku, GyomatsuYakumonoZenkaku, YakumonoZenkaku, with VectorCraft's own spacing for each) and Line-end Punctuation Half Width, tate-chu-yoko (auto) | done / partial | custom kinsoku sets, custom mojikumi sets and the Mojikumi Settings dialog missing | From f459465407a01d893b39d3fcf38971c17c262b07 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 03:56:40 -0800 Subject: [PATCH 08/31] Contextual Task Bar: the Smooth tool shows its Fidelity and Tool Options While the Smooth tool is in use with a path it can smooth selected, the bar shows the tool's Fidelity field and Tool Options..., which opens the Smooth tool's options. The field sets Fidelity through tool.setOption with the same range, unit and steps as the field in the options dialog. With nothing smoothable selected, the tool shows no bar. The bar leaves out the selection tools' actions and the Fill, Stroke, Recolor Artwork and Lock controls. On a canvas too narrow for the field, More Options lists Fidelity, which opens the tool's options. The Smooth tool's cursor and the bar share one check of the selection, which the bar keeps for the document's revision. --- crates/tools/src/draw2.rs | 2 +- crates/tools/src/draw2/gesture.rs | 11 +- crates/ui-egui/src/canvas/task_bar.rs | 138 ++++++++++++++++++++----- crates/ui-egui/src/dialogs/freehand.rs | 23 ++++- crates/ui-egui/src/tests/taskbar.rs | 83 ++++++++++++++- docs/target-app-parity.md | 3 +- 6 files changed, 227 insertions(+), 33 deletions(-) diff --git a/crates/tools/src/draw2.rs b/crates/tools/src/draw2.rs index 46e77314b6..9401dcd4c2 100644 --- a/crates/tools/src/draw2.rs +++ b/crates/tools/src/draw2.rs @@ -21,7 +21,7 @@ pub use curvature::{ CurvatureTool, EndCurve, curvature_close, curvature_extend, curvature_insert, curvature_move, curvature_remove, curvature_smooth, }; pub use family::FamilyTool; -pub use gesture::GestureTool; +pub use gesture::{GestureTool, can_smooth}; /// Colour of tool feedback (Illustrator's selection blue). pub const FEEDBACK: [u8; 3] = [0x4f, 0x9d, 0xff]; diff --git a/crates/tools/src/draw2/gesture.rs b/crates/tools/src/draw2/gesture.rs index 75b71ec8df..a1f1785923 100644 --- a/crates/tools/src/draw2/gesture.rs +++ b/crates/tools/src/draw2/gesture.rs @@ -791,9 +791,16 @@ fn redraw_targets(cx: &ToolContext, id: NodeId) -> Vec { /// Whether the selection contains a path the Smooth command can act on: one with a subpath of three /// or more anchors, or of two anchors joined by a curve. fn has_selected_smooth_path(cx: &ToolContext) -> bool { - let editable = cx.doc.editable(); + can_smooth(cx.doc, cx.selection) +} + +/// Whether `selection` in `doc` holds an editable path, selected or inside a selected object, that +/// the Smooth tool can smooth: one with a subpath of three or more anchors, or of two anchors +/// joined by a curve. +pub fn can_smooth(doc: &vectorcraft_doc::Document, selection: &vectorcraft_doc::Selection) -> bool { + let editable = doc.editable(); let smoothable = |sp: &vectorcraft_geom::SubPath| sp.anchors.len() >= 3 || (0..sp.segment_count()).any(|i| !super::segment_is_straight(sp, i)); - cx.selection.objects.iter().filter_map(|id| cx.doc.node(*id)).any(|n| { + selection.objects.iter().filter_map(|id| doc.node(*id)).any(|n| { let mut found = false; n.walk(&mut |child| { if !found diff --git a/crates/ui-egui/src/canvas/task_bar.rs b/crates/ui-egui/src/canvas/task_bar.rs index c3321195c0..9c6bcadd71 100644 --- a/crates/ui-egui/src/canvas/task_bar.rs +++ b/crates/ui-egui/src/canvas/task_bar.rs @@ -75,6 +75,27 @@ fn shape_tool_on_shape(app: &VectorcraftApp) -> bool { }) } +/// Whether the Smooth tool is in use with a selected path it can smooth +/// ([`vectorcraft_tools::draw2::can_smooth`]). The answer is kept in `ctx` for the document's +/// revision, which moves with every change of the document or the selection, so an unchanged +/// selection is not walked again each frame. +fn smooth_tool_on_paths(app: &VectorcraftApp, ctx: &egui::Context) -> bool { + if app.session.tool_id() != "smooth" { + return false; + } + let Some(st) = app.session.active() else { return false }; + let id = task_bar_id().with("smooth"); + 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 found = vectorcraft_tools::draw2::can_smooth(&st.doc, &st.selection); + 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 { @@ -130,7 +151,9 @@ pub(crate) fn task_bar_shows_type(app: &VectorcraftApp) -> bool { /// While a basic shape tool (Rectangle, Rounded Rectangle, Ellipse, Polygon or Star) has one closed /// path selected, as after it draws one, the bar offers Edit Path, Fill and Stroke, and Shape /// Properties for a live rectangle, rounded rectangle, ellipse or polygon; with nothing selected, or -/// any other selection, those tools show no bar. Selected type also shows the font family, font +/// any other selection, those tools show no bar. While the Smooth tool has a path it can smooth +/// selected, the bar shows the tool's Fidelity field and Tool Options…; with no such path it shows +/// no bar. Selected type also shows the font family, font /// style and Font Size controls before its Fill. /// While a Type tool edits type, or has type selected, the bar shows only those controls and the /// Fill. When one row would be wider than the canvas, the font controls take a row of their own, @@ -150,7 +173,10 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { // A basic shape tool with its shape selected offers Edit Path, Fill, Stroke and the shape's // properties, as the same help page describes. let shaping = shape_tool_on_shape(app); - if !(on_artboards || typing || blank || shaping || selection_tool_with_selection(app)) { + // The Smooth tool with a path to smooth offers its option, Fidelity, as the same help page + // describes for the Smooth tool, and Tool Options… for its dialog. + let smoothing = smooth_tool_on_paths(app, ui.ctx()); + if !(on_artboards || typing || blank || shaping || smoothing || selection_tool_with_selection(app)) { return; } // Selected type has the font controls too, as the help page describes @@ -197,15 +223,7 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { // Edit Path: the Direct Selection tool, to edit the path's anchors. let edit_path = || (tl!("Edit Path"), "dc-direct", "tool.select", json!({"tool": "directSelection"})); if on_artboards { - // As in the reference app, the Artboard tool offers to resize, duplicate and export the - // artboards (), - // and to rearrange them (). - items.push((tl!("Resize"), "move-diagonal-2", TASK_BAR_ARTBOARD_OPTIONS, none())); - items.push((tl!("Duplicate"), "copy", TASK_BAR_DUPLICATE_ARTBOARDS, none())); - if st.doc.artboards.len() > 1 { - items.push((tl!("Rearrange All"), "dc-rearrange", TASK_BAR_REARRANGE_ARTBOARDS, none())); - } - items.push((tl!("Export"), "share-2", "file.exportForScreens", none())); + artboard_items(&mut items, st.doc.artboards.len()); } else if blank { // Draw (Pencil) switches to the Pencil tool; Place Image picks files for the Place dialog. items.push((tl!("Draw (Pencil)"), "pencil", "tool.select", json!({"tool": "pencil"}))); @@ -213,6 +231,10 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { } else if shaping { // A basic shape tool's one action; its Fill, Stroke and Shape Properties follow as chips. items.push(edit_path()); + } else if smoothing { + // The Fidelity field, then Tool Options… for the dialog that shows it with its slider. + items.push((tl!("Fidelity:"), "", TASK_BAR_FIDELITY, none())); + items.push((tl!("Tool Options…"), "settings", "tool.options", json!({"tool": "smooth"}))); } else if !typing { // The selection tools' object actions. A Type tool's bar leaves them out, Create Outlines // and the type conversions included. @@ -319,8 +341,9 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { // The selected objects' Fill, Stroke, Recolor Artwork (when they have colours to recolour) and // Lock (a basic shape's properties instead), left out with the Artboard tool and on a blank // canvas, which have no selected objects. A Type tool's bar has the Fill alone. A basic shape - // tool's bar has the Fill, the Stroke and a live shape's Shape Properties. - let objects = !on_artboards && !blank; + // tool's bar has the Fill, the Stroke and a live shape's Shape Properties. The Smooth tool's bar + // has none of them. + let objects = !on_artboards && !blank && !smoothing; let chips: Vec = [ (objects, Chip::Fill), (objects && !typing, Chip::Stroke), @@ -330,7 +353,8 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { .into_iter() .filter_map(|(shown, chip)| shown.then_some(chip)) .collect(); - let widths: Vec = items.iter().map(|(label, _, cmd, _)| if icon_only(cmd) { BAR_MORE } else { action_width(ui, label) }).collect(); + let widths: Vec = items.iter().map(|(label, _, cmd, _)| item_width(ui, label, cmd)).collect(); + let fidelity = app.session.tool_options()["fidelity"].as_f64(); let font_w = fonts.then(|| { let w = crate::panels::character::TASK_BAR_WIDTHS; w.iter().sum::() + BAR_GAP * (w.len() - 1) as f32 @@ -408,16 +432,7 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { if *at != Some(row) { continue; } - // The convert buttons show their icon alone, named by their hover text, as - // the Control bar's do. - let clicked = if icon_only(cmd) { - widgets::icon_button(ui, icon, label, false, BAR_MORE).clicked() - } else { - action_button(ui, &t, label, icon) - }; - if clicked { - run = Some((*cmd, params.clone())); - } + run = bar_item(ui, &t, (*label, *icon, *cmd, params), fidelity).or(run.take()); } // Type's font family, font style and Font Size, which act as the Character // panel's do: on the characters a Type tool selects, else on the selected type. @@ -510,6 +525,9 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { // The convert buttons convert the direct-selected anchors, as the Control bar's buttons do. Some((TASK_BAR_TO_CORNER, _)) => crate::menus::invoke(app, "path.convertAnchors", json!({"to": "corner"})), Some((TASK_BAR_TO_SMOOTH, _)) => crate::menus::invoke(app, "path.convertAnchors", json!({"to": "smooth"})), + // Fidelity listed in More Options, on a canvas too narrow for its field: the Smooth tool's + // Tool Options, which show it. + Some((TASK_BAR_FIDELITY, _)) => crate::menus::invoke(app, "tool.options", json!({"tool": "smooth"})), Some((c, p)) => crate::menus::invoke(app, c, p), None => {} } @@ -658,6 +676,61 @@ fn action_width(ui: &Ui, label: &str) -> f32 { ui.painter().layout_no_wrap(label.to_string(), egui::FontId::proportional(13.0), Color32::PLACEHOLDER).size().x + 38.0 } +/// The width of the Smooth tool's Fidelity on the Contextual Task Bar: its label, the gap and the +/// field. +fn fidelity_width(ui: &Ui) -> f32 { + widgets::text_width(ui, fidelity_label(tl!("Fidelity:"), &Tokens::get(ui.ctx()))) + BAR_GAP + crate::dialogs::freehand::FIDELITY_FIELD_W +} + +/// The Fidelity field's label, `label`, as the bar draws it. +fn fidelity_label(label: &str, t: &Tokens) -> egui::RichText { + egui::RichText::new(label).size(13.0).color(t.text_strong) +} + +/// The width of the Contextual Task Bar's item `label` that runs `cmd`. +fn item_width(ui: &Ui, label: &str, cmd: &str) -> f32 { + match cmd { + TASK_BAR_FIDELITY => fidelity_width(ui), + _ if icon_only(cmd) => BAR_MORE, + _ => action_width(ui, label), + } +} + +/// One of the Contextual Task Bar's items, `label` with `icon`, which runs `cmd` with `params`, and +/// the Smooth tool's `fidelity`. Returns the command to run when it was used. +fn bar_item( + ui: &mut Ui, + t: &Tokens, + (label, icon, cmd, params): (&str, &str, &'static str, &serde_json::Value), + fidelity: Option, +) -> Option<(&'static str, serde_json::Value)> { + // The Smooth tool's Fidelity, labeled, sets the tool's option as it is typed or stepped. + if cmd == TASK_BAR_FIDELITY { + return fidelity_slot(ui, t, label, fidelity); + } + // The convert buttons show their icon alone, named by their hover text, as the Control bar's do. + let clicked = if icon_only(cmd) { widgets::icon_button(ui, icon, label, false, BAR_MORE).clicked() } else { action_button(ui, t, label, icon) }; + clicked.then(|| (cmd, params.clone())) +} + +/// The Smooth tool's Fidelity on the Contextual Task Bar, `label` and a field showing the tool's +/// `fidelity` (nothing without one). Returns the command that sets a new value typed or stepped to. +fn fidelity_slot(ui: &mut Ui, t: &Tokens, label: &str, fidelity: Option) -> Option<(&'static str, serde_json::Value)> { + let v = fidelity?; + let x = fidelity_field(ui, t, label, v).filter(|x| *x != v)?; + Some(("tool.setOption", json!({"tool": "smooth", "values": {"fidelity": x}}))) +} + +/// The Smooth tool's Fidelity on the Contextual Task Bar: `label` and a field showing `v`, centered +/// in a row of the bar. Returns the value typed or stepped to. +fn fidelity_field(ui: &mut Ui, t: &Tokens, label: &str, v: f64) -> Option { + ui.allocate_ui_with_layout(vec2(fidelity_width(ui), BAR_ROW), egui::Layout::left_to_right(egui::Align::Center), |ui| { + widgets::field_label(ui, fidelity_label(label, t)); + crate::dialogs::freehand::fidelity_field(ui, "task-bar-fidelity", v, "smooth") + }) + .inner +} + /// One of the Contextual Task Bar's action buttons: `icon` and `label`, named for screen readers. /// Returns whether it was clicked. fn action_button(ui: &mut Ui, t: &Tokens, label: &str, icon: &str) -> bool { @@ -743,6 +816,20 @@ fn paint_chip(ui: &mut Ui, t: &Tokens, paint: &vectorcraft_color::Paint, mixed: resp.on_hover_text(tip).clicked() } +/// The Contextual Task Bar's items with the Artboard tool in a document of `artboards` artboards: +/// Resize, Duplicate, Rearrange All (with two or more) and Export. +fn artboard_items(items: &mut Vec<(&'static str, &'static str, &'static str, serde_json::Value)>, artboards: usize) { + // As in the reference app, the Artboard tool offers to resize, duplicate and export the + // artboards (), + // and to rearrange them (). + items.push((tl!("Resize"), "move-diagonal-2", TASK_BAR_ARTBOARD_OPTIONS, json!({}))); + items.push((tl!("Duplicate"), "copy", TASK_BAR_DUPLICATE_ARTBOARDS, json!({}))); + if artboards > 1 { + items.push((tl!("Rearrange All"), "dc-rearrange", TASK_BAR_REARRANGE_ARTBOARDS, json!({}))); + } + items.push((tl!("Export"), "share-2", "file.exportForScreens", json!({}))); +} + /// The Contextual Task Bar's Center on Top and Center on Bottom, as in the Type menu, for type on a /// closed path. fn center_on_path_items(app: &VectorcraftApp, items: &mut Vec<(&'static str, &'static str, &'static str, serde_json::Value)>) { @@ -755,6 +842,9 @@ fn center_on_path_items(app: &VectorcraftApp, items: &mut Vec<(&'static str, &'s } } +/// The Contextual Task Bar's Fidelity field with the Smooth tool. +const TASK_BAR_FIDELITY: &str = "taskBar.fidelity"; + /// The Contextual Task Bar's Image Trace button: a trace with the Default preset. const TASK_BAR_IMAGE_TRACE: &str = "taskBar.imageTrace"; diff --git a/crates/ui-egui/src/dialogs/freehand.rs b/crates/ui-egui/src/dialogs/freehand.rs index bc7dd47212..93e3a1c2ff 100644 --- a/crates/ui-egui/src/dialogs/freehand.rs +++ b/crates/ui-egui/src/dialogs/freehand.rs @@ -104,6 +104,23 @@ fn fidelity_step(v: f64, n: f64) -> f64 { v } +/// The unit of tool `tool`'s Fidelity. The Pencil's, the Paintbrush's and the Smooth tool's +/// Fidelity is on screen, the same at any zoom (#5729); the Blob Brush's is in points. +fn fidelity_unit(tool: &str) -> &'static str { + if matches!(tool, "pencil" | "paintbrush" | "smooth") { "px" } else { "pt" } +} + +/// Width of the Fidelity field. +pub(crate) const FIDELITY_FIELD_W: f32 = FIELD_W; + +/// The Fidelity field of tool `tool`, showing `v` to two decimals from the tool's lowest Fidelity to +/// 100 and stepping by [`fidelity_step`], named by the label drawn just before it. Returns the value +/// typed or stepped to. The Contextual Task Bar shows the Smooth tool's. +pub(crate) fn fidelity_field(ui: &mut egui::Ui, id: &str, v: f64, tool: &str) -> Option { + let min = vectorcraft_tools::draw2::min_fidelity(tool); + widgets::range_field_stepped(ui, id, v, min..=100.0, fidelity_unit(tool), 2, FIELD_W, fidelity_step) +} + /// Where Fidelity `v` sits on a slider over `(min, max)`, from 0 to 1. The rail is logarithmic, so /// the low values, where the stroke is followed closely, get as much of it as the high ones /// (0.01–1 takes most of a 0.01–20 rail, in the tool's unit). @@ -211,9 +228,7 @@ fn fidelity(ui: &mut egui::Ui, d: &mut Dialog) { let v = d.f64("fidelity", 1.5); let tool = d.str("tool"); let rail = (vectorcraft_tools::draw2::min_fidelity(&tool), FIDELITY_MAX); - // The Pencil's, the Paintbrush's and the Smooth tool's Fidelity is on screen, the same at any - // zoom (#5729). - let unit = if matches!(tool.as_str(), "pencil" | "paintbrush" | "smooth") { "px" } else { "pt" }; + let unit = fidelity_unit(&tool); let rail_w = label_w(ui); let mut new = None; ui.label(egui::RichText::new(tl!("Fidelity:")).size(12.5).color(t.text)); @@ -222,7 +237,7 @@ fn fidelity(ui: &mut egui::Ui, d: &mut Dialog) { let (x, _, keyed) = widgets::color_slider_stepped(ui, "freehand-fidelity", tl!("Fidelity:"), Some(shown), fidelity_at(v, rail), rail_w, &|_| t.input_border); new = x.map(|x| fidelity_from(x, rail)).or(keyed); - if let Some(x) = widgets::range_field_stepped(ui, "freehand-fidelity-field", v, rail.0..=100.0, unit, 2, FIELD_W, fidelity_step) { + if let Some(x) = fidelity_field(ui, "freehand-fidelity-field", v, &tool) { new = Some(x); } }); diff --git a/crates/ui-egui/src/tests/taskbar.rs b/crates/ui-egui/src/tests/taskbar.rs index 4a48309dbe..b6d04ff12b 100644 --- a/crates/ui-egui/src/tests/taskbar.rs +++ b/crates/ui-egui/src/tests/taskbar.rs @@ -2,7 +2,8 @@ //! Path, compound paths and clipping masks their Release, images selected with vector art Make //! Clipping Mask, type converts between point and area type, type on a path opens its options, and //! a basic shape shows its properties in place of Lock. The basic shape tools show Edit Path, Fill, -//! Stroke and Shape Properties for the shape they draw. Type, and the Type tools while they edit it, +//! Stroke and Shape Properties for the shape they draw, and the Smooth tool its Fidelity and Tool +//! Options… for a path it can smooth. Type, and the Type tools while they edit it, //! show the font family, font style and Font Size controls. use egui::{Event, PointerButton, Pos2, Rect, vec2}; @@ -721,6 +722,86 @@ fn shape_tool_bar_retargets_after_another_shape_and_undo() { assert_eq!(app.session.tool_id(), "directSelection"); } +/// Where the text the bar draws just right of `label`, on the same row, centers: the field after +/// the label. +fn field_after(texts: &[(String, Rect)], label: &str) -> Pos2 { + let l = texts.iter().find(|(t, _)| t == label).unwrap_or_else(|| panic!("no `{label}` in {texts:?}")).1; + texts + .iter() + .filter(|(_, r)| r.left() > l.right() && (r.center().y - l.center().y).abs() < 8.0) + .min_by(|a, b| a.1.left().total_cmp(&b.1.left())) + .unwrap_or_else(|| panic!("no field after `{label}` in {texts:?}")) + .1 + .center() +} + +/// The Smooth tool, with a path it can smooth selected, shows its Fidelity field and Tool Options…, +/// and none of the selection tools' actions or chips. A value typed in the field sets the tool's +/// Fidelity, and Tool Options… opens the tool's options with that value. +#[test] +fn the_smooth_tool_shows_fidelity_and_tool_options_for_a_path() { + let mut app = app(); + let path = id(app.run("shape.ellipse", json!({"x": 60, "y": 60, "width": 120, "height": 80})).unwrap()); + select(&mut app, &[path]); + app.run("tool.select", json!({"tool": "smooth"})).unwrap(); + let (_, named) = buttons(&mut app); + let names = names(&named); + for name in ["Tool Options…", "More Options"] { + assert!(names.contains(&name), "{name} in {names:?}"); + } + for name in ["Fill", "Stroke", "Recolor Artwork", "Lock (⌘2)", "Duplicate", "Edit Path", "Offset Path", "Simplify", "Smooth"] { + assert!(!names.contains(&name), "{name} is left out of {names:?}"); + } + let (ctx, texts) = bar(&mut app); + let p = field_after(&texts, "Fidelity:"); + let press = |pressed| Event::PointerButton { pos: p, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(&mut app, &ctx, vec![Event::PointerMoved(p), press(true), press(false)]); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![Event::Text("7".into())]); + let enter = Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + frame(&mut app, &ctx, vec![enter]); + frame(&mut app, &ctx, vec![]); + assert_eq!(app.session.tool_options()["fidelity"].as_f64(), Some(7.0)); + assert_eq!(app.session.tool_id(), "smooth"); + assert_eq!(app.session.active().unwrap().selection.objects, [NodeId(path)], "the selection is kept"); + click_button(&mut app, "Tool Options…"); + let d = app.ui.dialog.as_ref().expect("the Smooth tool's options"); + assert_eq!((d.kind.as_str(), d.str("tool").as_str()), (crate::dialogs::freehand::KIND, "smooth")); + assert_eq!(d.f64("fidelity", 0.0), 7.0); +} + +/// The Smooth tool shows no bar without a selected path it can smooth: with nothing selected, a +/// straight line or type. With a selection tool the bar has the selection's actions again, without +/// Fidelity. +#[test] +fn the_smooth_tool_shows_no_bar_without_a_path_to_smooth() { + let mut app = app(); + let path = id(app.run("shape.ellipse", json!({"x": 60, "y": 60, "width": 120, "height": 80})).unwrap()); + let line = id(app.run("shape.line", json!({"x1": 150, "y1": 200, "x2": 300, "y2": 240})).unwrap()); + let text = id(app.run("text.create", json!({"x": 220, "y": 60, "text": "Type"})).unwrap()); + app.run("tool.select", json!({"tool": "smooth"})).unwrap(); + for (what, ids) in [("nothing", vec![]), ("a straight line", vec![line]), ("type", vec![text])] { + select(&mut app, &ids); + let (ctx, _) = bar(&mut app); + assert!(canvas::task_bar_rect(&ctx).is_none(), "{what}: no bar"); + } + select(&mut app, &[path, line]); + let (ctx, texts) = bar(&mut app); + assert!(canvas::task_bar_rect(&ctx).is_some() && has(&texts, "Fidelity:"), "a path with a line: the bar, {texts:?}"); + // On one canvas the bar follows each change of the selection. + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + for (ids, shown) in [(vec![path], true), (vec![line], false), (vec![], false), (vec![path], true)] { + select(&mut app, &ids); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + assert_eq!(canvas::task_bar_rect(&ctx).is_some(), shown, "{ids:?}"); + } + app.run("tool.select", json!({"tool": "selection"})).unwrap(); + let (_, texts) = bar(&mut app); + assert!(has(&texts, "Duplicate") && !has(&texts, "Fidelity:"), "{texts:?}"); +} + /// A compound path under the Direct Selection tool isn't offered Edit Path, which would only switch /// to the tool already in use; the Selection tool still offers it. #[test] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f08f2b9f19..e27c577127 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -902,7 +902,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - With automation read roots in force, `svgInteractivity.info`, `addFile` and `removeFile`, the JavaScript Files dialog in a frame a request drives and `ui_inspect`'s selected file name a linked JavaScript file outside the roots by its file name alone, as `document.json` does; `removeFile` unlinks it by that name and refuses a name that fits more than one linked file (`tests/interactivity.rs`). - Numeric fields keep the pointer's pressed character as the text-drag start when movement exceeds the click threshold (#1326); a completed focus click selects the unit too. Pixel/point, plain and optional fields are regression-tested in both directions, before/after focus, with replacement text; keyboard focus, double-click, arrows and wheel keep their prior behavior. Native egui input confirms partial replacement gives 17 px instead of 700 px, one Undo/Redo, window captures and an exact saved-document read in a separate CLI process. A focus click released more than 1 pt from its press keeps the caret, and a tap within 1 pt still selects all (#6659; short-drag and jitter-tap regressions in `tests/numfields.rs`). - Unit fields and length strings take `%` in arithmetic: `3cm*50%` reads as 1.5 cm, and `50pt+25%` reads as 62.5 pt. - - The contextual task bar's handle drags it anywhere on the canvas (kept whole on it as the window resizes); unpinned it keeps that offset as it follows the selection, and its More Options menu hides it, pins its position across selection changes (`window.taskBar.pin`), resets it under the selection (`window.taskBar.reset`) and shows the Properties panel. As in Illustrator the position isn't kept across launches. Not done: the bar's variants for other tools (only the selection tools, the Type tools, the basic shape tools and the Artboard tool show it). + - The contextual task bar's handle drags it anywhere on the canvas (kept whole on it as the window resizes); unpinned it keeps that offset as it follows the selection, and its More Options menu hides it, pins its position across selection changes (`window.taskBar.pin`), resets it under the selection (`window.taskBar.reset`) and shows the Properties panel. As in Illustrator the position isn't kept across launches. Not done: the bar's variants for other tools (only the selection tools, the Type tools, the basic shape tools, the Smooth tool and the Artboard tool show it). - A click on another object moves the contextual task bar under it without hiding it for the press; it gives way only to a drag (#4681). - With one image selected, the contextual task bar offers Image Trace, which traces the image at once with the Default preset (the Image Trace panel is left as it was), and Crop Image; with an Image Trace object it offers Expand, which keeps only the traced paths. This follows Illustrator's bar: for a selected image it includes Image Trace, Retype and Crop Image, and traced artwork can be expanded from it ([Contextual Task Bar announcement](https://community.adobe.com/announcements-651/contextual-task-bar-in-illustrator-2025-quick-actions-when-you-need-them-1546580)). Offset Path and Simplify, which don't apply to an image, aren't offered for one. Not done: Retype, which the app doesn't have. - With the Artboard tool, the contextual task bar sits under the selected artboards and offers Resize (Artboard Options for the active artboard), Duplicate (each selected artboard, in one undo step, the copies then selected), Rearrange All (with two or more artboards) and Export (Export for Screens with the selected artboards checked). This follows Illustrator's bar: while the Artboard tool is in use, it has options for resizing, duplicating and exporting artboards (the [Contextual Task Bar announcement](https://community.adobe.com/questions-652/contextual-task-bar-in-illustrator-2025-quick-actions-when-you-need-them-1546580); Rearrange and Export on the bar: [Managing Artboards in Illustrator](https://creativepro.com/managing-artboards-in-illustrator/)). @@ -912,6 +912,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The help page describes the contextual task bar as one horizontal row () and gives no rule for a canvas narrower than that row. VectorCraft's own rule: the bar stays whole on the canvas. When its actions don't fit in one row, they wrap, in order, onto rows under the row with the handle, the chips and More Options; an action wider than any row, or one that would need a row past the canvas's height, is listed in More Options instead; when the chips don't fit beside the handle and More Options, they take rows after the actions; with no row to spare for the font controls, the bar leaves them out; a canvas too small for the handle and More Options shows no bar. Evidence: `a_task_bars_actions_wrap_on_a_narrow_canvas` and `a_task_bar_action_wider_than_the_canvas_goes_in_more_options` in `crates/ui-egui/src/tests/taskbar.rs`. - With a live rectangle, rounded rectangle, ellipse or polygon selected with the Selection tool, the contextual task bar shows a Shape Properties button in place of Lock. It opens a popup with the shape's rows from the Transform panel (corner radius, pie angles, or sides, angle, corner and radius), which edit it through `object.setLiveShape`. The overview describes this: when a shape drawn with a shape tool (Rectangle, Star) is selected, the bar offers to change its properties where Lock Object would be ([Contextual Task Bar overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/contextual-task-bar-overview.html)). Object › Lock and ⌘2 still lock the shape. Not done: stars, which the app draws as plain paths. Evidence: `a_basic_shape_shows_its_properties_in_place_of_lock`, `the_shape_properties_popup_edits_the_shape` and `other_selections_keep_lock` in `crates/ui-egui/src/tests/taskbar.rs`. - While the Rectangle, Rounded Rectangle, Ellipse, Polygon or Star tool is in use, the contextual task bar offers Edit Path (the Direct Selection tool), the Fill and Stroke chips, and Shape Properties for the shape it draws, as the help page lists for those five tools (). VectorCraft's own rules: the bar shows while one of those tools has one closed path selected whole, as right after it draws one, and not with nothing selected, several objects, a group, an open path, type or picked-out anchors; it shows nothing during the drag that draws the shape; it leaves out the selection tools' Duplicate, Offset Path, Simplify, Recolor Artwork and Lock; the Line Segment tool shows no bar. Not done: Shape Properties for a star, which the app draws as a plain path, and Gen Shape Fill and Generate Vectors, which the app doesn't have. Evidence: `shape_tools_show_edit_path_paint_and_properties_after_drawing`, `shape_tools_have_no_shape_bar_without_a_single_shape` and `shape_tool_bar_retargets_after_another_shape_and_undo` in `crates/ui-egui/src/tests/taskbar.rs`. + - While the Smooth tool is in use with a path it can smooth selected (a path with three or more anchors, or two joined by a curve, on its own or inside a selected group), the contextual task bar shows the tool's Fidelity field and Tool Options…, which opens the Smooth tool's options. The overview says the Smooth tool's bar has its tool options (), and the tool's help page names Fidelity as its option (). A value typed or stepped in the field sets the tool's Fidelity through `tool.setOption`, with the same range, unit (screen pixels) and steps as the field in its options. VectorCraft's own rules: with nothing selected, or only straight lines or type selected, the tool shows no bar; the bar leaves out the selection tools' actions, the Fill and Stroke chips, Recolor Artwork and Lock; on a canvas too narrow for the field, More Options lists Fidelity, which opens the tool's options. Evidence: `the_smooth_tool_shows_fidelity_and_tool_options_for_a_path` and `the_smooth_tool_shows_no_bar_without_a_path_to_smooth` in `crates/ui-egui/src/tests/taskbar.rs`. - The contextual task bar has a Stroke chip beside the Fill chip, drawn with the paint the Stroke proxy shows (a "?" when the selected objects' strokes differ, as on the Fill chip); a click brings the Stroke proxy forward and shows the Swatches panel wherever it is docked, floating or closed, as a click on the Fill chip does for the Fill proxy. The reference app's bar has Fill and Stroke controls for changing an object's colors ([Contextual Task Bar overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/contextual-task-bar-overview.html)). Evidence: `the_task_bar_shows_a_stroke_chip_beside_fill` and `the_task_bar_chips_follow_the_proxies_and_show_swatches_anywhere` in `crates/ui-egui/src/canvas/tests.rs`. - With anchor points selected with Direct Selection, the contextual task bar offers Remove Anchor Points, Connect (`path.join`), Cut Path, and Convert Selected Anchor Points to Corner and to Smooth (`path.convertAnchors` with `to` set to `corner` or `smooth`), the commands of the Control bar's anchor buttons; the two convert buttons show their icons alone, named by their tool tips as on the Control bar (VectorCraft's own choice). The overview lists items that delete the selected anchors, join selected end points, split the path at the selected anchors, and make the selected anchors corner or smooth points ([Contextual Task Bar overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/contextual-task-bar-overview.html)). With a path selected whole with Direct Selection, the bar also offers Simplify and Smooth, which open the Simplify and Smooth sliders as Object › Path › Simplify… and Smooth… do; the same overview names Smooth as adjusting the path's curvature (#6784). VectorCraft's own rule: while anchors are picked out, the bar offers the anchor items without Simplify and Smooth. Evidence: `direct_selection_smooth_opens_the_smooth_slider` in `crates/ui-egui/src/tests/taskbar.rs`. - Tool flyouts tear off: dragging or clicking the tear-off bar on a flyout's right side (or releasing the long press over it) floats its group as a strip of tool buttons, moved by the same bar and put back in the toolbar by the × at its top (`window.floatTools`). While a group floats, the presses that would open its flyout raise the strip instead. Floating strips are kept with the preferences and in user workspaces. Not done: turning a strip vertical, docking it. From b977086e13ce920789104ee8de7a6b89d3a24381 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 06:25:40 -0800 Subject: [PATCH 09/31] Docs: queued PSD files ask for their import options with Show Import Options on docs/mcp.md said every PSD or PSB file of a loaded place cursor comes in with the choices made last. With Show Import Options on, each such file that has import options shows PSD Import Options when it is clicked or dragged (place::place_from_cursor, and the psd_import test a_cursor_loaded_with_show_import_options_on_asks_for_each_psd_file); only with it off do the last choices apply. --- docs/mcp.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index c38d6fc7a2..f0b7450d37 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -8672,8 +8672,9 @@ is offered only for a file with slices and applies to either choice. File › Pl file placed without Link, and so does a file dropped on the canvas with Shift held. The dialog starts from the choices made last, at first Convert Layers to Objects without hidden layers, with Import Slices. A file with fewer than two layers and no slices, a file placed with Link, and `document.open` and `file.place` run as commands don't -show it. Several files placed together without Link load the place cursor without asking, and each PSD or PSB file -among them comes in with the choices made last. +show it. Several files placed together without Link load the place cursor without asking. With Show Import Options +on, each PSD or PSB file among them that would show the dialog shows it when it is clicked or dragged; with it off, +each one comes in with the choices made last. ```json {"name":"run_command","arguments":{"command":"file.place","params":{"path":"/tmp/poster.psd","layers":true,"hiddenLayers":true}}} From 74bf5c26184fac5bae566db6d83fdd40ab5270f7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 06:36:16 -0800 Subject: [PATCH 10/31] Selection: an Intertwine group's members in symbol art count toward a click's object limit A click walks a symbol instance's art within one limit of objects, but the members of an Intertwine group in that art, and the objects of groups nested deeper than the part path depth, were tested without taking from it. Each object hit_any visits in placed symbol art now takes one object from the limit, and testing stops once the limit is used up. --- crates/doc/src/hit.rs | 43 +++++++++++++++++++++++++++++++++---- crates/doc/src/hit/tests.rs | 31 ++++++++++++++++++++++++++ 2 files changed, 70 insertions(+), 4 deletions(-) diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index d49776b2cb..a286c25ffc 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -1121,10 +1121,12 @@ fn on_type_path(n: &Node, t: &crate::TextObject, p: Point, tol: f64) -> bool { stroke_contains(&path.to_bezpath(), 0.0, tol, p) } -/// Hit anywhere in an evaluated subtree (groups recurse; leaves use [`hit_leaf`]). +/// Hit anywhere in an evaluated subtree (groups recurse; leaves use [`hit_leaf`]). In symbol art +/// placed by [`FindPart`], each object visited takes one object of the [`ArtWalk`] limit, and +/// nothing more is tested once the limit is used up. fn hit_any(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option { // Hidden art does not hit. - if !n.visible { + if !n.visible || ArtWalk::charged() && !ArtWalk::take(1) { return None; } // Nor art whose reach does not hold `p`, as in [`may_hit`]: a blend's steps far from `p` are @@ -1257,8 +1259,12 @@ struct FindPart<'a> { } impl FindPart<'_> { + /// What a click at `p` hits on object `n` of the art, placed. [`hit_any`] takes `n` and each + /// object it visits inside `n` from the [`ArtWalk`] limit. fn hit(&self, n: &Node, whole: Option, opt: HitOptions) -> Option { - self.art.place(n, whole).and_then(|n| hit_any(&n, self.p, opt, self.symbols)) + let placed = self.art.place(n, whole)?; + let _charged = ArtWalk::charge(); + hit_any(&placed, self.p, opt, self.symbols) } fn skips_guide(&self, n: &Node) -> bool { @@ -1268,7 +1274,7 @@ impl FindPart<'_> { /// What a click at `p` hits on object `n` of the art, with `path` the child indices that lead /// to what it hits. `outline`: the view is in Outline, or a layer around `n` has Preview off. fn find(&self, n: &Node, path: &mut Vec, whole: Option, outline: bool) -> Option { - if !n.visible || !self.whole_instance && (n.locked || n.is_template()) || self.skips_guide(n) || !ArtWalk::take(1) { + if !n.visible || !self.whole_instance && (n.locked || n.is_template()) || self.skips_guide(n) || ArtWalk::used_up() { return None; } let outline = outline || previews_off(n); @@ -1277,6 +1283,9 @@ impl FindPart<'_> { if path.len() >= crate::symbol_overrides::MAX_PATH_DEPTH { return self.hit(n, whole, opt); } + if !ArtWalk::take(1) { + return None; + } let whole = self.art.whole(n, whole); if n.clips() && let Some(first) = children.first() @@ -1370,6 +1379,8 @@ thread_local! { /// How many more objects of symbol art the click or marquee under way may visit ([`ArtWalk`]), /// `None` outside one. static ART_WALK_LEFT: std::cell::Cell> = const { std::cell::Cell::new(None) }; + /// Whether [`hit_any`] is testing symbol art that [`FindPart`] placed ([`ArtWalk::charge`]). + static ART_WALK_CHARGED: std::cell::Cell = const { std::cell::Cell::new(false) }; } #[cfg(test)] @@ -1420,6 +1431,19 @@ impl ArtWalk { ART_WALK_LEFT.set(Some(rest.unwrap_or(0))); rest.is_some() } + + /// While the guard lives, each object [`hit_any`] visits takes one object from what is left: + /// [`FindPart`] holds one while it tests a placed object of symbol art, so that the members of an + /// Intertwine group, and the objects of groups nested deeper than + /// [`crate::symbol_overrides::MAX_PATH_DEPTH`], count toward the limit. + fn charge() -> ArtWalkCharge { + ArtWalkCharge { was: ART_WALK_CHARGED.replace(true) } + } + + /// Does [`hit_any`] take the objects it visits from what is left ([`Self::charge`])? + fn charged() -> bool { + ART_WALK_CHARGED.get() + } } impl Drop for ArtWalk { @@ -1430,6 +1454,17 @@ impl Drop for ArtWalk { } } +/// The guard of [`ArtWalk::charge`]. +struct ArtWalkCharge { + was: bool, +} + +impl Drop for ArtWalkCharge { + fn drop(&mut self) { + ART_WALK_CHARGED.set(self.was); + } +} + /// Is `n` below a layer whose Preview is off, so that the canvas draws it in outline? As for clicks /// ([`path_options`]), the Preview of the isolated container `scope` and of the layers around it /// does not count. diff --git a/crates/doc/src/hit/tests.rs b/crates/doc/src/hit/tests.rs index 74bd959a7f..f2582c17fa 100644 --- a/crates/doc/src/hit/tests.rs +++ b/crates/doc/src/hit/tests.rs @@ -2140,6 +2140,37 @@ fn a_click_and_a_marquee_walk_repeated_nested_symbol_instances_within_one_limit( assert_eq!(with_art_limit(100, || marquee(&d, edge, None, false)).0, [inst], "marquee across the art's edge"); } +/// The members of an Intertwine group in symbol art count toward the art walk's limit of objects +/// for a click, as the members of a plain group do. A click on a member's path past the instance's +/// box is still found within the limit. +#[test] +fn a_click_counts_the_members_of_an_intertwine_group_in_symbol_art_toward_one_limit() { + set_clip_region(moved_clip_region); + // A clip group whose clipping region `test.move` moves to 100..200 × 0..100, past the 0..100 + // box, over an Intertwine group of 200 squares at 140..160 × 40..60. + let mut d = Document::new(600.0, 400.0); + let l = d.layers[0].id; + let (mut mask, _) = half_clipped(&mut d); + mask.appearance.effects.push(test_move()); + let squares = (0..200) + .map(|_| Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(140.0, 40.0, 160.0, 60.0)), Appearance::default_art()))) + .collect(); + let woven = Arc::new(Node::new(d.alloc_id(), NodeKind::Intertwine { children: squares })); + let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), woven]); + clip.set_clips(true); + group_symbol(&mut d, "Woven", vec![Arc::new(clip)]); + let inst = instance_of(&mut d, "Woven"); + let id = inst.id; + d.insert(Some(l), 0, Arc::unwrap_or_clone(inst)).unwrap(); + let opt = HitOptions { path_only: true, ..HitOptions::default() }; + let at = |x: f64| hit_test(&d, Point::new(x, 50.0), opt).map(|h| h.leaf); + // Inside the squares and away from their paths, every member is tested and none is hit. + let (hit, leaves, _) = with_art_limit(100, || at(150.0)); + assert_eq!(hit, None); + assert!(leaves <= 100, "{leaves} leaves tested"); + assert_eq!(with_art_limit(100, || at(140.0)).0, Some(id), "on the squares' paths"); +} + /// In a dynamic symbol's art that placing through its 9-slice guides could make more than /// [`crate::MAX_SYMBOL_NODES`] objects of, Direct Selection picks and outlines nothing, as the /// canvas draws nothing of it. At the art's natural size the same art is picked. From e3551a92e4ed00c20be0f508ac7303dcd74d743b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 06:39:44 -0800 Subject: [PATCH 11/31] Variables: the Data Set box renames the current data set The Data Set row at the top of the Variables panel now holds a text box with the current data set's name. A new name entered there renames the data set through dataset.rename, as one undo step. The same name runs nothing, so no undo step is added. An empty name or the name of another data set is refused, and the status bar shows the error. A list button beside the box still chooses a data set, and the arrows still step through them. With no data set the box is disabled. --- crates/ui-egui/src/panels/variables.rs | 138 ++++++++++++++++++++++++- docs/target-app-parity.md | 1 + 2 files changed, 137 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/panels/variables.rs b/crates/ui-egui/src/panels/variables.rs index 3ab5fc2484..2c1c8a815c 100644 --- a/crates/ui-egui/src/panels/variables.rs +++ b/crates/ui-egui/src/panels/variables.rs @@ -97,6 +97,18 @@ pub(crate) fn delete_active_dataset(app: &mut VectorcraftApp) { app.run("dataset.delete", json!({})).ok(); } +/// The Data Set box: a new name typed over the current data set's renames it with +/// `dataset.rename`, in one undo step. The same name runs nothing, so no undo step is added; an +/// empty or taken name is refused, and the status bar says why. +pub(crate) fn rename_active_dataset(app: &mut VectorcraftApp, from: &str, to: &str) { + if from.is_empty() || to.trim() == from { + return; + } + if let Err(e) = app.run("dataset.rename", json!({"name": from, "newName": to})) { + app.status(e); + } +} + /// Draw document variables, data sets and their two-row footer of capture and binding controls. pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let Some(st) = app.session.active() else { @@ -140,12 +152,17 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // Lock Variables: no variable is defined, deleted or renamed until they are unlocked. let locked = st.doc.variables.locked; - // The current data set across the top: its name, and the arrows that step through them. + // The current data set across the top: its name in a box that renames it, the list that + // chooses another, and the arrows that step through them. ui.horizontal(|ui| { widgets::field_label(ui, tl!("Data Set")); let names: Vec<&str> = sets.iter().map(|s| s.name.as_str()).collect(); let current = active.map(|s| s.name.as_str()).unwrap_or(""); - let picked = widgets::dropdown_names(ui, "variables-active", current, &names, 160.0); + let typed = ui.add_enabled_ui(active.is_some(), |ui| widgets::text_field(ui, "variables-active-name", Some(current), 134.0, 1)).inner; + if let Some(to) = typed { + rename_active_dataset(app, current, &to); + } + let picked = widgets::dropdown_names_named(ui, "variables-active", Some(tl!("Data Sets")), "", &names, 26.0); if let Some(name) = picked.and_then(|i| names.get(i)) && *name != current { @@ -406,6 +423,123 @@ mod tests { assert!(text.contains("Name") && text.contains("Data Sets") && text.contains("Data Set 1"), "{text}"); } + /// Frames of the panel with input events, for typing into its Data Set box. + struct Driver { + ctx: egui::Context, + time: f64, + } + + impl Driver { + fn new() -> Self { + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + Self { ctx, time: 0.0 } + } + + fn frame(&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(320.0, 600.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)); + out.textures_delta.clear(); + out + } + + /// The center of the panel's one text box, the Data Set box. + fn data_set_box(&mut self, app: &mut VectorcraftApp) -> egui::Pos2 { + use egui::accesskit::Role; + self.frame(app, vec![]); + let out = self.frame(app, vec![]); + let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; + let (_, node) = nodes.iter().find(|(_, n)| matches!(n.role(), Role::TextInput | Role::MultilineTextInput)).expect("the Data Set box"); + let b = node.bounds().expect("bounds"); + egui::pos2((b.x0 + b.x1) as f32 * 0.5, (b.y0 + b.y1) as f32 * 0.5) + } + + /// Clicks the Data Set box, replaces its text with `text` and presses Enter. + fn type_name(&mut self, app: &mut VectorcraftApp, text: &str) { + use egui::{Event, Key, Modifiers, PointerButton}; + let pos = self.data_set_box(app); + let (button, none) = (PointerButton::Primary, Modifiers::default()); + self.frame(app, vec![Event::PointerMoved(pos), Event::PointerButton { pos, button, pressed: true, modifiers: none }]); + self.frame(app, vec![Event::PointerButton { pos, button, pressed: false, modifiers: none }]); + let all = Modifiers { ctrl: true, command: true, ..Default::default() }; + let select_all = Event::Key { key: Key::A, physical_key: None, pressed: true, repeat: false, modifiers: all }; + self.frame(app, vec![select_all, Event::Text(text.into())]); + self.frame(app, vec![Event::Key { key: Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: none }]); + self.frame(app, vec![]); + } + } + + fn set_names(app: &mut VectorcraftApp) -> Vec { + let sets = app.run("dataset.list", json!({})).unwrap(); + sets["datasets"].as_array().unwrap().iter().map(|d| d["name"].as_str().unwrap_or_default().to_string()).collect() + } + + fn undo_steps(app: &VectorcraftApp) -> usize { + app.session.active().unwrap().history.undo.len() + } + + /// A name typed in the Data Set box and entered renames the current data set in one undo step; + /// the list still chooses another data set afterward. + #[test] + fn the_data_set_box_renames_the_current_data_set() { + let mut app = app_with_data(); + app.session.execute("dataset.capture", &json!({})).unwrap(); + app.session.execute("dataset.select", &json!({"name": "Data Set 1"})).unwrap(); + let before = undo_steps(&app); + let mut d = Driver::new(); + d.type_name(&mut app, "Spring"); + assert_eq!(set_names(&mut app), ["Spring", "Data Set 2"]); + assert_eq!(app.session.active().unwrap().doc.variables.active_dataset.as_deref(), Some("Spring")); + assert_eq!(undo_steps(&app), before + 1); + assert_eq!(app.session.active().unwrap().history.undo.last().map(|e| e.label.as_str()), Some("Rename Data Set")); + // The new name is what the box shows, and what the list offers with the other row. + let text = crate::tests_labels::painted_text(&mut app, show); + assert!(text.contains("Spring"), "{text}"); + app.run("dataset.select", json!({"name": "Data Set 2"})).unwrap(); + assert_eq!(app.session.active().unwrap().doc.variables.active_dataset.as_deref(), Some("Data Set 2")); + } + + /// The same name adds no undo step; an empty name or another data set's name is refused with a + /// status message, and the names stay as they were. + #[test] + fn the_data_set_box_refuses_an_empty_or_taken_name() { + let mut app = app_with_data(); + app.session.execute("dataset.capture", &json!({})).unwrap(); + app.session.execute("dataset.select", &json!({"name": "Data Set 1"})).unwrap(); + let before = undo_steps(&app); + let mut d = Driver::new(); + d.type_name(&mut app, "Data Set 1"); + assert_eq!(undo_steps(&app), before, "the same name runs nothing"); + assert_eq!(app.ui.status, ""); + for name in ["Data Set 2", " "] { + app.ui.status.clear(); + d.type_name(&mut app, name); + assert_eq!(set_names(&mut app), ["Data Set 1", "Data Set 2"], "{name:?}"); + assert_eq!(undo_steps(&app), before, "{name:?}"); + assert!(!app.ui.status.is_empty(), "{name:?} gives no status message"); + } + assert!(app.ui.status.contains("newName"), "{}", app.ui.status); + // Through the helper too: an unchanged or padded name runs nothing. + rename_active_dataset(&mut app, "Data Set 1", " Data Set 1 "); + assert_eq!(undo_steps(&app), before); + } + + /// With no data set the box is disabled, so typing in it renames nothing. + #[test] + fn the_data_set_box_is_disabled_without_a_data_set() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 300, "height": 200})).unwrap(); + let before = undo_steps(&app); + let mut d = Driver::new(); + d.type_name(&mut app, "Spring"); + assert!(set_names(&mut app).is_empty()); + assert_eq!(undo_steps(&app), before); + assert_eq!(app.ui.status, ""); + } + #[test] fn a_row_the_art_left_behind_is_in_italics() { let mut app = app_with_data(); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index a8b5cb97e8..8a5195c888 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -788,6 +788,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Variables: `dataset.select`, `dataset.next` and `dataset.prev` name the area type and type on a path whose text they rewrote and that doesn't fit, in the reply's `overflow` key, as `text.setText` does. - Variables: when no object is bound to a variable that the data set has a value for, for example after Import Data Sets… defines new variables without binding them, choosing the data set in the Variables panel or stepping to it with the panel's arrows shows a status message, and `dataset.select`, `dataset.next` and `dataset.prev` add the message to the reply as `warning`. - Variables: Lock Variables (`variable.lock`, in the Variables panel's bottom bar and menu) stops variables from being defined, deleted or renamed until they are unlocked, while objects can still be bound and unbound and data sets still change and apply; the lock is saved with the document. + - Variables: the Data Set box at the top of the Variables panel takes typed text, and a new name entered there renames the current data set with `dataset.rename` in one undo step; the same name adds no undo step, an empty or taken name is refused with a status message, and the list button beside the box still chooses a data set. - 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}`. From 9afdbe2b03962aa29cd6fb31ed7b074d808bfdeb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 06:41:20 -0800 Subject: [PATCH 12/31] SVG import: a blur that differs by direction is kept as its SVG filter A feGaussianBlur or feDropShadow whose blur is not the same in every direction in the document came in as an even Gaussian Blur or Drop Shadow of the mean standard deviation. That covers two different standard deviations (stdDeviation="4 1") and an even one in a skewed or unevenly scaled user space. An SVG Filters effect in such a user space is exported live under that transform, so on reopening its blur lost the difference between directions. Such a filter is now kept as an SVG Filters effect, which draws it as it is. A blur in a turned, flipped or evenly scaled user space still becomes the live effect, and a filter that no SVG Filters effect can keep still comes in as the nearest even effect, as before. --- crates/svg/src/import/fx.rs | 69 ++++++++++++++++++++++++------ crates/svg/src/import/importer.rs | 8 ++-- crates/svg/tests/it/import_live.rs | 57 ++++++++++++++++++++++++ docs/effects-parity.md | 2 +- 4 files changed, 119 insertions(+), 17 deletions(-) diff --git a/crates/svg/src/import/fx.rs b/crates/svg/src/import/fx.rs index 91180981db..08e2dfeb9a 100644 --- a/crates/svg/src/import/fx.rs +++ b/crates/svg/src/import/fx.rs @@ -315,9 +315,51 @@ impl V { } } -/// σ of a blur with standard deviations `x`, `y` (their mean: the effects blur evenly). -fn sd(x: f32, y: f32) -> f64 { - (x as f64 + y as f64) / 2.0 +/// σ of a blur with standard deviations `x`, `y` in a user space the document scales by the same +/// amount in every direction when `even` (turned, flipped or scaled alike along both axes). The +/// effects blur evenly: `None` when the blur differs by direction in the document, unless `blurs` +/// is [`Blurs::Nearest`], which takes the mean. +fn sd(x: f32, y: f32, even: bool, blurs: Blurs) -> Option { + let uneven = (x > 0.0 || y > 0.0) && (x != y || !even); + (blurs == Blurs::Nearest || !uneven).then_some((x as f64 + y as f64) / 2.0) +} + +/// How [`effects`] reads a blur that differs by direction in the document, which the effects +/// draw the same in every direction. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Blurs { + /// Not as an effect: the filter is left for an SVG Filters effect ([`kept`]), which draws it. + Exact, + /// As the even blur of the mean standard deviation. + Nearest, +} + +/// Whether the linear part of `ts` scales every direction by the same amount (a turn, a flip and +/// an even scale), so an even blur stays even in the document. +fn even_space(ts: Affine) -> bool { + let [a, b, c, d, _, _] = ts.as_coeffs(); + let tol = 1e-9 * ts.determinant().abs().sqrt().max(1.0); + let near = |p: f64, q: f64| (p - q).abs() <= tol; + (near(a, d) && near(b, -c)) || (near(a, -d) && near(b, c)) +} + +/// `filters` (in the order they apply) imported in user space mapped to the document by `ts`: as +/// the live effects they draw as ([`effects`]), else as SVG Filters effects that keep their XML +/// ([`kept`]), else as the live effects nearest them (a blur that differs by direction drawn as +/// an even one). With whether they are live effects. `None` when none of these takes them. +pub(super) fn imported( + filters: &[Arc], + ts: Affine, + blends: &HashMap, + sources: &HashMap, +) -> Option<(Vec, bool)> { + if let Some(fx) = effects(filters, ts, blends, Blurs::Exact) { + return Some((fx, true)); + } + if let Some(fx) = kept(filters, ts, sources) { + return Some((fx, false)); + } + effects(filters, ts, blends, Blurs::Nearest).map(|fx| (fx, true)) } fn color(c: usvg::Color) -> Color { @@ -364,9 +406,10 @@ fn transferred(v: V, [r, g, b, a]: [&TransferFunction; 4], srgb: bool) -> Option } } -/// Evaluate one filter's primitives, `k` the scale from its user space to the document. +/// Evaluate one filter's primitives, `k` the scale from its user space to the document, `even` +/// when that scale is the same in every direction ([`even_space`]), blurs read as `blurs` says. /// `None` when one does something the effects cannot represent. -fn eval(f: &Filter, k: f64) -> Option { +fn eval(f: &Filter, k: f64, even: bool, blurs: Blurs) -> Option { let mut results: HashMap<&str, V> = HashMap::new(); let mut last = V::Graphic; for p in f.primitives() { @@ -380,7 +423,7 @@ fn eval(f: &Filter, k: f64) -> Option { let v = match p.kind() { Kind::GaussianBlur(b) => { let linear = p.color_interpolation() == ColorInterpolation::LinearRGB; - input(b.input())?.blur(sd(b.std_dev_x().get(), b.std_dev_y().get()), linear)? + input(b.input())?.blur(sd(b.std_dev_x().get(), b.std_dev_y().get(), even, blurs)?, linear)? } Kind::Offset(o) => input(o.input())?.offset(o.dx() as f64, o.dy() as f64)?, Kind::Flood(fl) => V::Flood(color(fl.color()), fl.opacity().get()), @@ -450,8 +493,8 @@ fn eval(f: &Filter, k: f64) -> Option { } } Kind::DropShadow(d) if matches!(input(d.input())?, V::Graphic) => { - let shape = - Shape { sd: sd(d.std_dev_x().get(), d.std_dev_y().get()), dx: d.dx() as f64, dy: d.dy() as f64, moved: true, inverted: false }; + let sd = sd(d.std_dev_x().get(), d.std_dev_y().get(), even, blurs)?; + let shape = Shape { sd, dx: d.dx() as f64, dy: d.dy() as f64, moved: true, inverted: false }; V::Stack(vec![V::Paint { shape, color: color(d.color()), opacity: d.opacity().get(), clipped: false }, V::Graphic]) } _ => return None, @@ -463,10 +506,12 @@ fn eval(f: &Filter, k: f64) -> Option { } /// The live effects `filters` (in the order they apply) stand for, in user space mapped to the -/// document by `ts`; `blends`: the modes our export recorded ([`blends`]). `None` when one of -/// them isn't an effect the canvas draws. -pub(super) fn effects(filters: &[Arc], ts: Affine, blends: &HashMap) -> Option> { +/// document by `ts`; `blends`: the modes our export recorded ([`blends`]); `blurs`: how a blur +/// that differs by direction reads ([`Blurs`]). `None` when one of them isn't an effect the +/// canvas draws. +fn effects(filters: &[Arc], ts: Affine, blends: &HashMap, blurs: Blurs) -> Option> { let k = ts.determinant().abs().sqrt(); + let even = even_space(ts); let [a, b, c, d, _, _] = ts.as_coeffs(); let along = |dx: f64, dy: f64| Vec2::new(a * dx + c * dy, b * dx + d * dy); let num = |v: f64| (v * 1000.0).round() / 1000.0; @@ -475,7 +520,7 @@ pub(super) fn effects(filters: &[Arc], ts: Affine, blends: &HashMap continue, // SVG blurs in linear light unless the filter asks for sRGB (`color-interpolation-filters`). V::Blurred(sd, true) => ("blur.gaussian", json!({ "radius": blur(sd), "linear": true })), diff --git a/crates/svg/src/import/importer.rs b/crates/svg/src/import/importer.rs index 2eede1f7be..5c62eb10b3 100644 --- a/crates/svg/src/import/importer.rs +++ b/crates/svg/src/import/importer.rs @@ -303,11 +303,11 @@ impl Importer { (None, id) => format!("'{id}'"), }; let mask = g.mask().and_then(|m| self.opacity_mask(m, ts, &label)); - // Blurs, shadows and glows become live effects (see [`fx`]); other filters become Effect › - // SVG Filters effects that keep their XML. + // Blurs, shadows and glows become live effects (see [`fx`]); other filters, and blurs that + // differ by direction in the document, become Effect › SVG Filters effects that keep their XML. let effects = match g.filters() { [] => vec![], - filters => fx::effects(filters, ts, &self.blends).or_else(|| fx::kept(filters, ts, &self.filter_sources)).unwrap_or_else(|| { + filters => fx::imported(filters, ts, &self.blends, &self.filter_sources).map(|(fx, _)| fx).unwrap_or_else(|| { // usvg wraps a filtered element in a group of its own: name the element then. let on = match g.children() { [usvg::Node::Group(_)] | [] => label.clone(), @@ -383,7 +383,7 @@ impl Importer { /// () cuts a filter's result at /// its region. A filter that didn't import (drawn without it) clips nothing. fn filter_regions(&mut self, g: &usvg::Group, ts: Affine, mut n: Node) -> Option { - if g.filters().is_empty() || fx::effects(g.filters(), ts, &self.blends).is_none() { + if g.filters().is_empty() || !fx::imported(g.filters(), ts, &self.blends, &self.filter_sources).is_some_and(|(_, live)| live) { return Some(n); } for f in g.filters() { diff --git a/crates/svg/tests/it/import_live.rs b/crates/svg/tests/it/import_live.rs index b39842e4fa..5e1757ae8b 100644 --- a/crates/svg/tests/it/import_live.rs +++ b/crates/svg/tests/it/import_live.rs @@ -284,6 +284,63 @@ fn a_gaussian_blur_becomes_the_effect_with_its_radius() { assert_eq!(effects(&d)[0].params["radius"], json!(12.0)); } +/// A blur that differs by direction in the document (standard deviations that differ, or an even +/// one in a user space scaled unevenly or skewed) is kept as an SVG filter, which draws it as it +/// is, not as an even Gaussian Blur. In a turned, flipped or evenly scaled user space an even blur +/// stays the effect. +#[test] +fn a_blur_that_differs_by_direction_is_kept_as_its_filter() { + let ids = |body: &str| { + let (d, w) = open(body); + assert!(w.is_empty(), "{w:?}"); + effects(&d).iter().map(|e| e.id.clone()).collect::>() + }; + let blur = |sd: &str, transform: &str| { + format!( + r##""## + ) + }; + assert_eq!(ids(&blur("4 1", "translate(0)")), ["svg.filter"]); + assert_eq!(ids(&blur("3", "scale(1 4)")), ["svg.filter"]); + assert_eq!(ids(&blur("3", "skewX(30)")), ["svg.filter"]); + assert_eq!(ids(&blur("3", "rotate(30) scale(2)")), ["blur.gaussian"]); + assert_eq!(ids(&blur("3", "scale(-2 2)")), ["blur.gaussian"]); + let shadow = |sd: &str| { + format!( + r##""## + ) + }; + assert_eq!(ids(&shadow("3 1")), ["svg.filter"]); + assert_eq!(ids(&shadow("3")), ["stylize.dropShadow"]); +} + +/// An SVG filter's blur in a user space scaled unevenly is written live and opens again as the +/// same effect, which blurs more along the stretched axis, not as an even Gaussian Blur. +#[test] +fn an_exported_blur_in_a_stretched_user_space_opens_as_the_same_effect() { + let xml = r#""#; + let mut d = Document::new(200.0, 120.0); + let mut n = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(60.0, 40.0, 140.0, 80.0)), + Appearance::basic(Paint::solid(Color::rgb(0.9, 0.1, 0.1)), Paint::None, 0.0), + ); + let params = json!({ "xml": xml, "scale": 2.0, "origin": [0.0, 0.0], "axes": [0.5, 0.0, 0.0, 2.0] }); + n.appearance.effects = vec![Effect { id: "svg.filter".into(), params, visible: true }]; + let l = d.layers[0].id; + d.insert(Some(l), 0, n).unwrap(); + let out = export(&d, &ExportOptions::default()); + assert!(out.contains(">(), ["svg.filter"], "{out}"); + let num = |v: &serde_json::Value| v.as_f64().unwrap(); + let axes: Vec = fx[0].params["axes"].as_array().unwrap().iter().map(num).collect(); + assert!(axes.iter().zip([0.5, 0.0, 0.0, 2.0]).all(|(a, b)| (a - b).abs() < 1e-6), "{axes:?}"); + assert_similar(&render_artboard(&d), &render_artboard(&back), 40.0, 0.02); +} + /// `color-interpolation-filters` (SVG 1.1 §15.7.6, initially linearRGB: /// https://www.w3.org/TR/SVG11/painting.html#ColorInterpolationFiltersProperty) picks whether the /// blur mixes colours in linear light; sRGB, on the primitive or the filter, keeps them as they diff --git a/docs/effects-parity.md b/docs/effects-parity.md index 290148b89d..0bb12a65ed 100644 --- a/docs/effects-parity.md +++ b/docs/effects-parity.md @@ -27,7 +27,7 @@ Part of [target-app-parity.md](target-app-parity.md); open work is in [gaps.md]( | Pathfinder | Add, Intersect, Exclude, Subtract, Minus Back, Divide, Trim, Merge, Crop, Outline, Hard Mix, Soft Mix, Trap | 13/13 | Trap traps only solid fills (gradients and patterns hide what is below them but don't trap) and spreads each colour's visible area as a whole; the public page gives no default values, so Trap's 0.25 pt, 100% and 40% are VectorCraft's own | | Rasterize | Rasterize… (as a live effect) | 1/1 | — | | Stylize | Drop Shadow, Feather, Inner Glow, Outer Glow, Round Corners, Scribble | 6/6 | Scribble Options' Settings presets | -| SVG Filters | Apply SVG Filter… and the filter list | 1/1 | The submenu lists 14 default filters and then the document's own; the public page names no default set, so the set, names and values are VectorCraft's own, and a default is copied into the document when it is applied or edited. A filter that is the object's last effect is written to SVG as a `` element; otherwise SVG export draws the object as an image. A filter on a turned, skewed or unevenly scaled object in an imported SVG is kept and runs in that object's user space, and SVG export writes it back under the same transform | +| SVG Filters | Apply SVG Filter… and the filter list | 1/1 | The submenu lists 14 default filters and then the document's own; the public page names no default set, so the set, names and values are VectorCraft's own, and a default is copied into the document when it is applied or edited. A filter that is the object's last effect is written to SVG as a `` element; otherwise SVG export draws the object as an image. A filter on a turned, skewed or unevenly scaled object in an imported SVG is kept and runs in that object's user space, and SVG export writes it back under the same transform. A blur or drop shadow that blurs more in one direction than another in the document (two different standard deviations, or one in a skewed or unevenly scaled user space) is kept as this effect rather than opened as an even Gaussian Blur or Drop Shadow | | Warp | Arc, Arc Lower, Arc Upper, Arch, Bulge, Shell Lower, Shell Upper, Flag, Wave, Fish, Rise, Fisheye, Inflate, Squeeze, Twist | 15/15 | warp point editing in envelopes; each style bends the bounds as one Bézier patch (`version` 1), so Arc's edges are cubic curves close to concentric arcs; warps saved without a version keep the earlier map, where Arc is a circular arc in the object's own proportions (#1578) | Document Raster Effects Settings exists. When the 64 million pixel cap on an effect image lowers From 6523a3322434a7a030af6e2b760f7baab50970b9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 06:41:48 -0800 Subject: [PATCH 13/31] 3D and Materials: Export 3D Object adds the selection to Asset Export The 3D and Materials panel gets an Export 3D Object button. It adds the selected objects that have a visible 3D effect to Asset Export as 3D assets through assets.add3D, the command behind Asset Export's own Export 3D Object, selects their assets there and shows the Asset Export panel. Objects without a 3D effect, and a 3D object inside another selected one, are left out. The button is unavailable while no selected object has a visible 3D effect. Adding is one undo step, and nothing is recorded when every object is an asset already. Docs: docs/three-d.md, docs/mcp.md, docs/effects-parity.md, docs/target-app-parity.md. --- crates/ui-egui/src/panels/asset_export.rs | 17 ++++-- crates/ui-egui/src/panels/tests_three_d.rs | 67 ++++++++++++++++++++++ crates/ui-egui/src/panels/three_d.rs | 58 ++++++++++++++++++- docs/effects-parity.md | 2 +- docs/mcp.md | 4 +- docs/target-app-parity.md | 1 + docs/three-d.md | 10 ++++ 7 files changed, 151 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/panels/asset_export.rs b/crates/ui-egui/src/panels/asset_export.rs index 39b3a0ea85..3fe249b7e3 100644 --- a/crates/ui-egui/src/panels/asset_export.rs +++ b/crates/ui-egui/src/panels/asset_export.rs @@ -7,7 +7,7 @@ //! desktop with Background Export on, on the background thread); the web downloads them. The //! screen button opens Export for Screens on its Assets tab. //! -//! Export 3D Object (the panel menu) collects the selected objects with a 3D effect as 3D assets, +//! Export 3D Object (the panel menu, and the 3D and Materials panel's button) collects the selected objects with a 3D effect as 3D assets, //! marked 3D on their tiles. While the panel's assets include 3D assets, a Format row picks their //! mesh format (USDA, USDZ, glTF or OBJ), and Export writes them as mesh files beside the pictures. //! @@ -207,6 +207,16 @@ fn run(app: &mut VectorcraftApp, cmd: &str, params: Value) -> Option { app.run(cmd, params).map_err(|e| app.status(e)).ok() } +/// Export 3D Object: collects objects `ids` (else the selection) as 3D assets (`assets.add3D`), and +/// selects their assets in the panel, including those that were assets already. +pub(crate) fn add_3d(app: &mut VectorcraftApp, ctx: &egui::Context, ids: Option<&[u64]>) -> Result<(), String> { + let p = ids.map_or_else(|| json!({}), |ids| json!({ "ids": ids })); + let r = app.run("assets.add3D", p)?; + let assets: Vec = r["assets"].as_array().into_iter().flatten().filter_map(Value::as_u64).collect(); + set_pstate(ctx, SELECTED, assets); + Ok(()) +} + /// Collect `ids` (else the selection) as assets (one of them all with `single`), and select them /// in the panel. fn collect(app: &mut VectorcraftApp, ctx: &egui::Context, ids: Option>, single: bool) { @@ -630,10 +640,9 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { collect(app, &ctx, None, false); } if menu_item(ui, tl!("Export 3D Object"), has_art, false) - && let Some(r) = run(app, "assets.add3D", json!({})) + && let Err(e) = add_3d(app, &ctx, None) { - let ids: Vec = r["assets"].as_array().into_iter().flatten().filter_map(Value::as_u64).collect(); - set_pstate(&ctx, SELECTED, ids); + app.status(e); } ui.separator(); if menu_item(ui, tl!("Select All Assets"), !all.is_empty(), false) { diff --git a/crates/ui-egui/src/panels/tests_three_d.rs b/crates/ui-egui/src/panels/tests_three_d.rs index 6146bc4852..35e17797b1 100644 --- a/crates/ui-egui/src/panels/tests_three_d.rs +++ b/crates/ui-egui/src/panels/tests_three_d.rs @@ -1026,6 +1026,73 @@ fn the_arrow_keys_move_the_light_pressed_last() { assert_eq!(rotations, [json!(0.0), json!(-179.0)]); } +fn assets(app: &mut VectorcraftApp) -> Vec { + app.run("assets.list", json!({})).unwrap()["assets"].as_array().unwrap().clone() +} + +/// The panel always shows Export 3D Object; it adds only the selected objects that have a 3D +/// effect to Asset Export as 3D assets, in one undo step, selects their assets there and shows the +/// Asset Export panel. Run again, it records nothing and still selects them. +#[test] +fn export_3d_object_adds_the_selected_3d_objects_to_asset_export() { + let mut app = app(); + assert!(painted_text(&mut app, show).contains("Export 3D Object")); + let ctx = egui::Context::default(); + // Without a 3D object: an error, nothing recorded, no asset. + let history = undo_len(&app); + assert!(super::export_3d_object(&mut app, &ctx).is_err()); + assert_eq!((undo_len(&app), assets(&mut app).len()), (history, 0)); + let a = app.session.active().unwrap().selection.objects[0].0; + set_type(&mut app, "extrude").unwrap(); + app.run("layer.setProps", json!({"id": a, "name": "Box"})).unwrap(); + assert!(painted_text(&mut app, show).contains("Export 3D Object")); + let plain = app.run("shape.rectangle", json!({"x": 250, "y": 100, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap(); + // A hidden 3D effect draws nothing to export: the object is left out like one without. + let hidden = app.run("shape.rectangle", json!({"x": 100, "y": 250, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap(); + app.run("effect.apply", json!({"effect": "threeD.extrude", "item": null})).unwrap(); + app.run("effect.setParams", json!({"index": 0, "item": null, "visible": false})).unwrap(); + assert!(super::export_3d_object(&mut app, &ctx).is_err()); + app.run("select.set", json!({"ids": [plain, a, hidden]})).unwrap(); + assert_eq!(super::selected_3d_objects(&app), [a]); + assert!(!crate::panel_docking::visible(&app.ui, crate::panels::asset_export::ID)); + let history = undo_len(&app); + super::export_3d_object(&mut app, &ctx).unwrap(); + assert_eq!(undo_len(&app), history + 1); + let list = assets(&mut app); + assert_eq!(list.len(), 1, "{list:?}"); + assert_eq!((list[0]["name"].clone(), list[0]["format3D"].clone()), (json!("Box"), json!("usda"))); + let asset = list[0]["id"].as_u64().unwrap(); + assert_eq!(super::pstate::>(&ctx, "asset-export-selected"), [asset]); + assert!(crate::panel_docking::visible(&app.ui, crate::panels::asset_export::ID)); + // Already an asset: no undo step, the same asset selected again, the panel left showing. + super::set_pstate(&ctx, "asset-export-selected", Vec::::new()); + super::export_3d_object(&mut app, &ctx).unwrap(); + assert_eq!((undo_len(&app), assets(&mut app).len()), (history + 1, 1)); + assert_eq!(super::pstate::>(&ctx, "asset-export-selected"), [asset]); + assert!(crate::panel_docking::visible(&app.ui, crate::panels::asset_export::ID)); + // Undo takes the asset away. + app.run("edit.undo", json!({})).unwrap(); + assert!(assets(&mut app).is_empty()); +} + +/// A selected 3D object inside another selected 3D object is not collected on its own: the outer +/// object's asset holds it. +#[test] +fn export_3d_object_leaves_out_a_3d_object_inside_another() { + let mut app = app(); + let inner = app.session.active().unwrap().selection.objects[0].0; + set_type(&mut app, "extrude").unwrap(); + let other = app.run("shape.rectangle", json!({"x": 250, "y": 100, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [inner, other]})).unwrap(); + let group = app.run("object.group", json!({})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [group]})).unwrap(); + app.run("effect.apply", json!({"effect": "threeD.extrude", "item": null})).unwrap(); + app.run("select.set", json!({"ids": [inner, group]})).unwrap(); + let selected: Vec = app.session.active().unwrap().selection.objects.iter().map(|id| id.0).collect(); + assert!(selected.contains(&inner) && selected.contains(&group), "{selected:?}"); + assert_eq!(super::selected_3d_objects(&app), [group]); +} + #[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 231a755de2..2611824cda 100644 --- a/crates/ui-egui/src/panels/three_d.rs +++ b/crates/ui-egui/src/panels/three_d.rs @@ -4,11 +4,13 @@ //! dialogs' own Object, Rotation and Lighting controls and the panel's Materials tab //! ([`materials`]); each change runs `effect.setParams` as one undo step, and a drag previews and //! commits once, when the pointer is released. While the Materials tab is open, the artboard shows -//! a handle on each mapped graphic, which drags it over its face. +//! a handle on each mapped graphic, which drags it over its face. At the bottom, Export 3D Object +//! adds the selected objects that have a 3D effect to Asset Export as 3D assets (`assets.add3D`) +//! and shows that panel with their assets selected. use egui::Ui; use serde_json::{Map, Value, json}; -use vectorcraft_doc::{Effect, Node}; +use vectorcraft_doc::{Effect, Node, NodeId}; use vectorcraft_effects::{CLASSIC_EXTRUDE, CLASSIC_REVOLVE, EXTRUDE, INFLATE, THREE_D_TYPES, is_three_d}; use super::{live_run, pstate, set_pstate}; @@ -49,6 +51,13 @@ fn find(n: &Node) -> Option { in_list(&n.appearance.effects, None).or_else(|| n.appearance.items.iter().enumerate().find_map(|(k, item)| in_list(item.effects(), Some(k)))) } +/// Does object `n` have a visible 3D effect (where [`find`] looks, in a visible fill or stroke), +/// the kind Export 3D Object exports, without copying its settings? +fn has_three_d(n: &Node) -> bool { + let in_list = |fx: &[Effect]| fx.iter().any(|e| e.visible && is_three_d(&e.id)); + in_list(&n.appearance.effects) || n.appearance.items.iter().any(|item| item.visible() && in_list(item.effects())) +} + /// The panel's object type of effect `id` (`plane`, `extrude`, `revolve` or `inflate`). pub(crate) fn type_of(id: &str) -> Option<&'static str> { THREE_D_TYPES.iter().find(|(_, effect)| *effect == id).map(|(kind, _)| *kind) @@ -229,6 +238,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if let Some(action) = materials::library(app, ui, false) { run_action(app, &ctx, action); } + export_button(app, ui, &ctx); return; }; if takes_render(&t.effect) { @@ -271,6 +281,50 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if let Some(action) = action { run_action(app, &ctx, action); } + export_button(app, ui, &ctx); +} + +/// The Export 3D Object button, available while a selected object has a 3D effect. An error goes +/// to the status bar. +fn export_button(app: &mut VectorcraftApp, ui: &mut Ui, ctx: &egui::Context) { + let any = app.session.active().is_some_and(|st| st.selection.objects.iter().any(|id| st.doc.node(*id).is_some_and(has_three_d))); + ui.add_space(10.0); + if ui.add_enabled(any, egui::Button::new(tl!("Export 3D Object"))).clicked() { + finish(app, ctx); + if let Err(e) = export_3d_object(app, ctx) { + app.ui.status = e; + } + } +} + +/// The selected objects that have a 3D effect, in tree order, leaving out each one inside another +/// listed one (that one's asset holds it). +pub(crate) fn selected_3d_objects(app: &VectorcraftApp) -> Vec { + let Some(st) = app.session.active() else { return vec![] }; + let found = st.selection.objects.iter().copied().filter(|id| st.doc.node(*id).is_some_and(has_three_d)); + let mut paths: Vec<(Vec, NodeId)> = st.doc.index_paths(found).into_iter().map(|(id, path)| (path, id)).collect(); + paths.sort_by(|a, b| a.0.cmp(&b.0)); + let mut kept: Vec<(Vec, NodeId)> = Vec::with_capacity(paths.len()); + for (path, id) in paths { + if !kept.last().is_some_and(|(outer, _)| path.starts_with(outer)) { + kept.push((path, id)); + } + } + kept.into_iter().map(|(_, id)| id.0).collect() +} + +/// Export 3D Object: adds the selected objects that have a 3D effect to Asset Export as 3D assets +/// (`assets.add3D`, one undo step, none when each is an asset already), selects their assets there +/// and shows the Asset Export panel. Objects without a 3D effect in the selection are left out. +pub(crate) fn export_3d_object(app: &mut VectorcraftApp, ctx: &egui::Context) -> Result<(), String> { + use super::asset_export; + let ids = selected_3d_objects(app); + // Without one, `assets.add3D` on the selection says why nothing was added. + asset_export::add_3d(app, ctx, (!ids.is_empty()).then_some(ids.as_slice()))?; + if !crate::panel_docking::visible(&app.ui, asset_export::ID) { + app.run("window.panel", json!({"panel": asset_export::ID}))?; + } + Ok(()) } /// Does 3D effect `id` take render settings (`render`)? Extrude & Bevel, Revolve, Inflate and Rotate diff --git a/docs/effects-parity.md b/docs/effects-parity.md index 290148b89d..41ad38cfeb 100644 --- a/docs/effects-parity.md +++ b/docs/effects-parity.md @@ -183,7 +183,7 @@ VectorCraft choices; an original approximation, never compared with another appl | 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; hard-edged shadows behind or below the object from the first light ([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, soft shadows 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 or no Shading Color, 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)); Map Art: none | | Turntable (30.0 beta) | none | -| Export 3D objects (OBJ, USDA, glTF) | initial: Asset Export's Export 3D Object collects 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`); no textures, map art or shading ([3D export help](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/export-3d-vector-artwork.html)) | +| 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`); no textures, map art or shading ([3D export help](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/export-3d-vector-artwork.html)) | The `three-d` crate (depends on `geom` and `pathops`, with no UI or GPU dependencies) builds, rotates, projects, shades and depth-sorts the surfaces; the effects crate turns them into art. What's left (materials and shadows, ray-traced rendering, diff --git a/docs/mcp.md b/docs/mcp.md index c38d6fc7a2..22f1a8d49e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -8548,7 +8548,9 @@ becomes an asset (or one asset with `multiple: false`). ### 3D assets -Asset Export's menu item Export 3D Object (`assets.add3D {ids?, format?}`) collects each selected object (or `ids`) +Asset Export's menu item Export 3D Object and the 3D and Materials panel's Export 3D Object button +(`assets.add3D {ids?, format?}`; the button passes the ids of the selected objects that have a 3D effect and then shows +the Asset Export panel, [three-d.md](three-d.md#3d-and-materials-panel)) collect each selected object (or `ids`) that carries Extrude & Bevel, Revolve, Inflate or Rotate as a 3D asset, named after the object; an object already collected as a 3D asset keeps it, and an object without such an effect is refused. A 3D asset's Format is `usda` (the default), `usdz`, `gltf` or `obj`; the panel shows a Format row for the 3D assets it would export, and diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 4c8b2d43f8..d719e7dc9f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -596,6 +596,7 @@ since 2026-10-01. - Window › 3D and Materials panel: `crates/ui-egui/src/panels/three_d.rs` applies a 3D effect by object type (Plane, Extrude, Revolve, Inflate), changes an applied one in place (`effect.setParams` `threeDType`) and edits it with the options dialog's Object, Rotation and Lighting controls, one undo step per change; `crates/engine/src/cmd/effectcmd/three_d_type_tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` cover it. No Materials tab. - 3D and Materials › Quick Actions › Expand as Wireframes (#6354): `effect.expandAsWireframes` replaces each selected 3D object with a group of 0.5 pt black stroked paths, the edges of the faces its effect draws, each edge once and joined end to end, curves kept, in one undo step ([three-d.md](three-d.md#3d-and-materials-panel)); `crates/effects/src/solids/wireframe/tests.rs`, `crates/engine/src/cmd/wireframe/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` cover it. Scores and hours unchanged. - 3D and Materials › Render Settings › Wireframe: `render: {mode: "wireframe"}` on Extrude & Bevel, Revolve, Inflate and Rotate draws the live effect as the edges of its faces, 0.5 pt black strokes with no shadow, in every output and in Expand Appearance ([three-d.md](three-d.md#3d-and-materials-panel)); `crates/effects/src/solids/wireframe/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` cover it. Scores and hours unchanged. +- 3D and Materials › Export 3D Object: the panel's button adds the selected objects that have a 3D effect to Asset Export as 3D assets (`assets.add3D`), one undo step and none when each is an asset already, selects their assets and shows the Asset Export panel ([three-d.md](three-d.md#3d-and-materials-panel)); `panels::three_d::tests::{export_3d_object_adds_the_selected_3d_objects_to_asset_export, export_3d_object_leaves_out_a_3d_object_inside_another}` cover it. Scores and hours unchanged. - 3D effects on clipping groups, blends and symbol instances (#6140, #5725): every 3D type builds from the art the object shows (the art inside the clipping path, the blend's keys and steps, the symbol's art where the instance places it), alone or in a group, on the canvas, in exports, Object › Rasterize and `assets.add3D`; an image is refused with a pointer to Object › Image Trace › Make. `crates/effects/src/solids/tests_sources.rs`, `crates/engine/src/cmd/effectcmd/three_d_source_tests.rs` and `fx::tests::a_symbol_instance_a_blend_and_a_clipping_group_draw_their_solids` cover it. Scores and estimates unchanged. - 3D effects, images a clip hides: an image in a clipping group is left out of the solid when its transformed frame lies wholly outside the area every clipping path around it fills together, holes included, instead of when only the boxes miss; an image the clips show part of is still refused ([the help page](https://helpx.adobe.com/illustrator/using/clipping-masks.html) on clipping paths hiding everything outside their shape; the omission rule is VectorCraft's own). `solids::tests_sources::an_image_inside_a_clips_box_but_outside_its_shape_is_left_out` covers it. Scores and estimates unchanged. diff --git a/docs/three-d.md b/docs/three-d.md index 2861bee0b7..171f97d360 100644 --- a/docs/three-d.md +++ b/docs/three-d.md @@ -79,6 +79,16 @@ pages describe it. own choice. The group keeps the object's place, id, name, opacity, blending mode, opacity mask, attributes and text wrap and is selected; objects without a visible 3D effect do not change. It is one undo step, and an error changes nothing when no selected object has a visible 3D effect. +- **Export 3D Object** is a button in the panel, as the public + [Export 3D vector artwork](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/export-3d-vector-artwork.html) + page describes; VectorCraft places it at the bottom of the panel. It adds each selected object that has a visible + 3D effect to Asset Export as a 3D asset, the same as + Asset Export's own Export 3D Object (`assets.add3D` with those objects' ids), selects their assets in the Asset + Export panel and shows that panel, where the Format row and Export write the mesh files + ([3D assets in mcp.md](mcp.md#3d-assets)). Selected objects without a visible 3D effect are left out, and so is + a 3D object inside another selected 3D object, whose asset holds it. The button is unavailable while no selected + object has a visible 3D effect. Adding the assets is one undo step; when every one of the objects is an asset already, nothing is + recorded and their assets are selected again. - The Lighting tab also holds the Shadows switch and its settings ([Shadows](#shadows)). The Materials tab holds the Graphics ([Graphics](#graphics)); base materials and ray-traced rendering are not built (see below). The rotation and light rings on the artboard are part of the options dialog only. The panel's Lighting tab has the From f021c29b6f933086104f4eb7131b5fdd80780fc3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 06:44:48 -0800 Subject: [PATCH 14/31] Live Paint: test that a Shift-triple-click keeps joined faces of the same fill A Shift-triple-click on a face whose double-click already reached a joined face of the same fill selects every face with that fill. The new test pins that the joined face the double-click toggled on is not toggled off again by the triple-click. --- crates/tools/src/builder/tests.rs | 52 +++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/crates/tools/src/builder/tests.rs b/crates/tools/src/builder/tests.rs index 75e15da82d..41f39135c9 100644 --- a/crates/tools/src/builder/tests.rs +++ b/crates/tools/src/builder/tests.rs @@ -2736,6 +2736,58 @@ fn live_paint_selection_triple_click_series_ends_with_the_same_paint_parts() { assert_eq!(sel, vec![c.0]); } +/// A Shift-triple-click on a face whose double-click already reaches a joined face of the same +/// fill selects every face with that fill: the joined face the double-click toggled on is not +/// toggled off again. +#[test] +fn live_paint_selection_shift_triple_click_keeps_joined_faces_of_the_same_fill() { + let mut d = Document::new(500.0, 500.0); + let (_, [a, b, c], _) = live_strip(&mut d); + let red = Paint::solid(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0)); + // A and B are joined across the unstroked edge AB; C is parted from them by the stroked edge BC. + for id in [a, b, c] { + d.node_mut(id).unwrap().appearance.set_fill(red.clone()); + } + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let shift = Mods { shift: true, ..Default::default() }; + let mut t = LivePaintSelectionTool::default(); + let mut sel: Vec = vec![]; + for kind in [ + PointerKind::Down, + PointerKind::Up, + PointerKind::Down, + PointerKind::Up, + PointerKind::DoubleClick, + PointerKind::Down, + PointerKind::Up, + PointerKind::TripleClick, + ] { + for act in t.pointer(&cx, &ev(kind, 25.0, 25.0).with_mods(shift)) { + let Action::Exec(cmd, args) = act else { panic!("{act:?}") }; + assert_eq!(cmd, "select.toggle"); + let ids: Vec = match (args.get("ids"), args.get("id")) { + (Some(v), _) => v.as_array().unwrap().iter().map(|i| i.as_u64().unwrap()).collect(), + (None, Some(i)) => vec![i.as_u64().unwrap()], + (None, None) => vec![], + }; + for i in ids { + match sel.iter().position(|x| *x == i) { + Some(k) => { + sel.remove(k); + } + None => sel.push(i), + } + } + } + } + sel.sort_unstable(); + let mut want = vec![a.0, b.0, c.0]; + want.sort_unstable(); + assert_eq!(sel, want); +} + #[test] fn live_paint_selection_double_click_skips_locked_groups_and_art_outside_isolation() { let mut d = Document::new(500.0, 500.0); From 9d9b69a5445cdd80b967e8d82ecaff0faee2db03 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 06:45:05 -0800 Subject: [PATCH 15/31] PDF import: an isolated group with overprinting art inside stays isolated The importer kept a group's isolation only when something inside it blended, so an isolated group or knockout group whose objects only overprint read back without isolation. Written out again, it lost its /I true and its overprinting objects then kept the inks of the art below the group that they had covered. Isolation is now also kept when a visible fill or stroke inside, or characters' fill or stroke, overprints, directly or through children that do not isolate. --- crates/pdf/src/import/builder.rs | 18 +++++++++++++-- crates/pdf/src/tests/blend.rs | 39 +++++++++++++++++++++++++++++++- docs/target-app-parity.md | 1 + 3 files changed, 55 insertions(+), 3 deletions(-) diff --git a/crates/pdf/src/import/builder.rs b/crates/pdf/src/import/builder.rs index 0d50c58f31..c2650138b9 100644 --- a/crates/pdf/src/import/builder.rs +++ b/crates/pdf/src/import/builder.rs @@ -361,8 +361,9 @@ impl<'p> Builder<'p> { Some(MaskSpec::Mask(m)) => (opacity, Some(m.clone())), None => (opacity, None), }; - // Isolation only shows with blending inside; knockout with several objects. - let isolate = isolate && Node::children_blend(&children, &mut |c| c.blends_through()); + // Isolation only shows with blending or overprinting inside; knockout with several + // objects. + let isolate = isolate && (Node::children_blend(&children, &mut |c| c.blends_through()) || children_overprint(&children)); let knockout = knockout && children.len() > 1; let plain = opacity >= 0.999 && blend == BlendMode::Normal && mask.is_none() && !isolate && !knockout; if children.is_empty() { @@ -1183,3 +1184,16 @@ fn visual_glyph_text(text: String) -> String { let chars: Vec = text.chars().collect(); order.iter().filter_map(|&i| chars.get(i)).collect() } + +/// Whether a visible fill or stroke among `children` overprints, characters' too, directly or +/// through children that don't isolate. In an isolated group an overprinting object is drawn on +/// the group's empty backdrop, so it covers the inks of the art below the group that it does not +/// paint; without isolation it leaves them. +fn children_overprint(children: &[Arc]) -> bool { + children.iter().any(|c| { + c.visible + && (c.appearance.items.iter().any(|i| i.visible() && i.overprint()) + || matches!(&c.kind, NodeKind::Text(t) if t.runs.iter().any(|r| r.style.overprint_fill || r.style.overprint_stroke)) + || (!c.isolate && c.children().is_some_and(|ch| children_overprint(ch)))) + }) +} diff --git a/crates/pdf/src/tests/blend.rs b/crates/pdf/src/tests/blend.rs index 1cd5c949e0..25948763d8 100644 --- a/crates/pdf/src/tests/blend.rs +++ b/crates/pdf/src/tests/blend.rs @@ -195,7 +195,8 @@ fn a_knockout_group_without_blending_inside_is_isolated_only_when_it_isolates() /// An overprinting element of a knockout group that does not isolate is drawn in a `/K` group /// without `/I true`, so it overprints the art below the group, and its graphics state still -/// overprints (`/OP`, `/op`, `/OPM 1`). An isolated group keeps `/I true`. +/// overprints (`/OP`, `/op`, `/OPM 1`). An isolated group keeps `/I true`, reads back isolated +/// and is written with `/I true` again. #[test] fn an_overprinting_element_of_a_knockout_group_that_does_not_isolate_overprints_the_art_below() { for isolate in [false, true] { @@ -219,6 +220,42 @@ fn an_overprinting_element_of_a_knockout_group_that_does_not_isolate_overprints_ }); assert_eq!(overprints, [false, false, false, true], "isolate {isolate}"); assert_eq!(knockout_groups(&back), [3], "isolate {isolate}"); + let mut found = vec![]; + back.walk(|n| { + if n.knockout == vectorcraft_doc::Knockout::On { + found.push(n.isolate); + } + }); + assert_eq!(found, [isolate], "isolate {isolate}"); + assert_eq!(text(&back).matches("/Itrue").count(), usize::from(isolate), "isolate {isolate}"); + } +} + +/// An isolated group with nothing blending inside but an overprinting fill reads back as an +/// isolated group and is written with `/I true` again; a group that does not isolate reads back +/// as its objects. +#[test] +fn an_isolated_group_with_an_overprinting_object_reads_back_isolated() { + for isolate in [false, true] { + let mut d = Document::new(200.0, 200.0); + add(&mut d, rect(Rect::new(0.0, 0.0, 200.0, 200.0), (0.9, 0.8, 0.2))); + let mut top = rect(Rect::new(60.0, 60.0, 160.0, 160.0), (0.0, 0.0, 1.0)); + top.appearance.fill_mut().unwrap().overprint = true; + let mut below = rect(Rect::new(20.0, 20.0, 120.0, 120.0), (1.0, 0.0, 0.0)); + (below.id, top.id) = (d.alloc_id(), d.alloc_id()); + let mut g = Node::group(NodeId(0), vec![std::sync::Arc::new(below), std::sync::Arc::new(top)]); + g.isolate = isolate; + add(&mut d, g); + assert_eq!(text(&d).matches("/Itrue").count(), usize::from(isolate), "isolate {isolate}"); + let back = import(&export(&d, &PdfOptions::default()).unwrap()).unwrap_or_else(|e| panic!("isolate {isolate}: {e}")); + let mut groups = vec![]; + back.walk(|n| { + if matches!(n.kind, vectorcraft_doc::NodeKind::Group { .. }) { + groups.push(n.isolate); + } + }); + assert_eq!(groups, if isolate { vec![true] } else { vec![] }, "isolate {isolate}"); + assert_eq!(text(&back).matches("/Itrue").count(), usize::from(isolate), "isolate {isolate}"); } } diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 4c8b2d43f8..0e1a7fbe3d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1704,6 +1704,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Type inside a group, layer, symbol instance, blend or repeat keeps its opacity, blend mode, opacity mask, Opacity & Mask Define Knockout Shape, own effects, perspective and visibility when the effects on the container outline it. Hidden type with a geometry effect of its own is left out of exports. PDF export writes a knockout group as one PDF knockout group (`/K true`, with `/I true` when the group isolates; ISO 32000-1, 11.4.6.3), so a knockout group of any size opens again in VectorCraft as a knockout group, and the form nesting of the file does not grow with the number of elements. When an element's opacity or mask defines its knockout shape, or it paints translucently, each element is drawn through one soft mask of the overlapping elements above it instead; past 65,536 objects in a group's masks (or 2,048 elements) the group is a PDF knockout group, with a warning that its translucent elements knock out fully. SVG export draws each element of a knockout group through one mask of the overlapping elements above it, and the masks refer to one copy of each element's shape, so the elements stay siblings and the file nests no deeper with more elements; past 65,536 shapes in a group's masks (or 2,048 elements) the group is written as a plain group, with a warning. Evidence: `pdf/src/tests/blend.rs`, `svg/tests/it/blend_export.rs`, `pdf/tests/gradient_forms.rs` (a gradient in a knockout group reads back in place). A knockout group in Normal mode at full opacity that does not isolate, with nothing blending inside, is written without an isolated group around its elements, clipped or not, so the art below the group is its initial backdrop in the PDF as on the canvas (ISO 32000-1, 11.4.5): neither its `/K` group nor a form around a clipped group carries `/I true`, and an overprinting element in it overprints the art below the group. Evidence: `pdf/src/tests/blend.rs` (`a_knockout_group_without_blending_inside_is_isolated_only_when_it_isolates`, `an_overprinting_element_of_a_knockout_group_that_does_not_isolate_overprints_the_art_below`). + PDF import keeps a group's isolation when something inside it overprints as well as when something blends, so an isolated group or knockout group whose objects only overprint opens as an isolated group and is written with `/I true` again, and its overprinting objects still cover the inks of the art below the group. Evidence: `pdf/src/tests/blend.rs` (`an_isolated_group_with_an_overprinting_object_reads_back_isolated`, `an_overprinting_element_of_a_knockout_group_that_does_not_isolate_overprints_the_art_below`). - **Graphic styles:** styles keep opacity and blend mode, capture groups and type, apply on top with Alt, and link to the objects using them; Redefine, Break Link, Graphic Style Options, Select All Unused, Sort by Name, and Select > Same Graphic Style / Appearance Attribute. The panel has list and thumbnail views with rendered previews, merge, reorder and drag and drop, plus a Control bar Style picker; eleven generated style libraries (including Game HUD, Status Effects, Neon & Glow, Painted and Sketched, whose seven styles each repaint a solid fill with one watercolor, dry brush, pastel, charcoal or ink effect, and Textures) save and load as `.vcstyles`. The built-in Textures graphic style library (`graphicStyle.addFromLibrary {library: "textures"}`) has eight styles that paint their fills and strokes with the texture effects: Fine Grain (Grain), Canvas Weave and Burlap Sack (Texturizer), Cracked Glaze (Craquelure), Mosaic Floor (Mosaic Tiles), Quilted Squares (Patchwork), Leaded Glass (Stained Glass) and Damp Paper (Water Paper). The help page names new graphic styles for textures ([What's new](https://helpx.adobe.com/illustrator/desktop/new-features/whats-new.html)) without naming them, so the styles, their names and their settings are VectorCraft's own (`tests::stylelib::textures_styles_apply_their_texture_effects_and_keep_their_params_through_save_and_open`). In the Graphic Styles panel, Shift-click selects a range of styles and Ctrl/Cmd-click adds or removes one. From 1957fdda0f299f50f8619708540eb3ed5033a3ef Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 06:51:02 -0800 Subject: [PATCH 16/31] Control bar: symbol instance controls keep the Transform link's room The gap after the symbol instance controls was added whenever 4 pt remained, without the room the Transform link needs after the group. When a narrow bar left out the symbol controls, the gap could take the last points the link needed, and the bar hid the link. The gap is now added only when the reserve remains after it. --- crates/ui-egui/src/panels/symbols.rs | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/panels/symbols.rs b/crates/ui-egui/src/panels/symbols.rs index 741b080635..fd77707fcd 100644 --- a/crates/ui-egui/src/panels/symbols.rs +++ b/crates/ui-egui/src/panels/symbols.rs @@ -287,7 +287,7 @@ pub(crate) fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui, reserve: f32) { { app.status(e); } - if ui.available_width() >= 4.0 { + if ui.available_width() >= reserve + 4.0 { ui.add_space(4.0); } } @@ -1789,4 +1789,29 @@ mod tests { h.get_by_label(" Select All Instances").click(); h.run_steps(2); } + + /// The Control bar's symbol instance controls leave the room `reserve` asks for after them, the + /// gap after the controls included, when the row has no room for any of them. + #[test] + fn control_bar_symbol_controls_leave_the_reserve_when_none_fits() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let art = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap()["id"].clone(); + let instance = app.run("symbol.new", json!({"name": "Mark", "ids": [art]})).unwrap()["id"].clone(); + app.run("select.set", json!({ "ids": [instance] })).unwrap(); + let ctx = egui::Context::default(); + let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(600.0, 100.0))), ..Default::default() }; + let mut room = None; + let mut out = ctx.run_ui(raw, |ui| { + ui.horizontal(|ui| { + // Two points more than the reserve: too little for Edit Symbol or Replace. + let reserve = ui.available_width() - 2.0; + control_bar(&mut app, ui, reserve); + room = Some((ui.available_width(), reserve)); + }); + }); + out.textures_delta.clear(); + let (left, reserve) = room.expect("the row was drawn"); + assert!(left >= reserve, "{left} pt left after the symbol controls, {reserve} pt reserved"); + } } From c4754df6df215feeda9dd3983f70f432cda93fac Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 06:52:18 -0800 Subject: [PATCH 17/31] Window: panels shown from the edge hide only after the pointer moves away or a hold ends The hide timer started on every frame with no pointer over the window, so panels shown by window.panels.peek hid 0.3 s later while the pointer had not moved. It now starts when the pointer moves, is released or leaves the window, and a pointer entering the window counts as a move on its first frame. When a press, a dialog, a popup or a flyout stops holding the panels open with the pointer away from them, the timer starts as well, so closing a flyout with Escape hides them without the pointer moving. --- crates/ui-egui/src/panel_docking/peek.rs | 22 +++++++++---- crates/ui-egui/src/panel_docking/tests.rs | 39 +++++++++++++++++++++++ 2 files changed, 54 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/panel_docking/peek.rs b/crates/ui-egui/src/panel_docking/peek.rs index baf147f4fd..ed43b80e3d 100644 --- a/crates/ui-egui/src/panel_docking/peek.rs +++ b/crates/ui-egui/src/panel_docking/peek.rs @@ -41,6 +41,8 @@ struct Shown { edge: Edge, /// When the pointer left them; `None` while it is over them or has not moved since they showed. left_at: Option, + /// Whether a press, a modal dialog, a popup or a flyout held them open last frame. + held: bool, } /// The session's state of the panels shown from the edges. @@ -102,9 +104,11 @@ pub(super) fn update(app: &mut VectorcraftApp, ctx: &egui::Context, area: egui:: return None; } let (now, pointer, down, moved) = ctx.input(|i| { - // A release counts as moving away: a press may have held the panels while it left them. - let moved = - i.pointer.delta() != egui::Vec2::ZERO || i.pointer.any_released() || i.events.iter().any(|e| matches!(e, egui::Event::PointerGone)); + // A release counts as moving away: a press may have held the panels while it left them. A + // pointer entering the window has no delta on its first frame, so the move event counts too. + let moved = i.pointer.delta() != egui::Vec2::ZERO + || i.pointer.any_released() + || i.events.iter().any(|e| matches!(e, egui::Event::PointerMoved(_) | egui::Event::PointerGone)); (i.time, i.pointer.hover_pos(), i.pointer.any_down(), moved) }); // A workspace switched to while panels show may dock none on that side. @@ -123,11 +127,15 @@ pub(super) fn update(app: &mut VectorcraftApp, ctx: &egui::Context, area: egui:: Edge::Right => p.x > uncovered.right(), } }); - if over || down || blocked || flyout { + let held = down || blocked || flyout; + if over || held { shown.left_at = None; - } else if moved || pointer.is_none() { + } else if moved || shown.held { + // A hold that ends with the pointer away from them counts as moving away, as closing a + // popup or flyout with Escape does not move the pointer. shown.left_at.get_or_insert(now); } + shown.held = held; match shown.left_at { Some(left) if now - left >= GRACE => { st.shown = None; @@ -160,7 +168,7 @@ pub(super) fn update(app: &mut VectorcraftApp, ctx: &egui::Context, area: egui:: }; if now - since >= DELAY { st.resting = None; - st.shown = Some(Shown { edge, left_at: None }); + st.shown = Some(Shown { edge, left_at: None, held: false }); return Some(edge); } st.resting = Some((edge, since)); @@ -233,7 +241,7 @@ pub(super) fn command(app: &mut VectorcraftApp, params: &Value) -> Result { diff --git a/crates/ui-egui/src/panel_docking/tests.rs b/crates/ui-egui/src/panel_docking/tests.rs index 2c95ff0e16..c78622458f 100644 --- a/crates/ui-egui/src/panel_docking/tests.rs +++ b/crates/ui-egui/src/panel_docking/tests.rs @@ -642,6 +642,45 @@ fn window_panels_peek_rejects_what_it_cannot_show_and_changes_nothing() { h.app.ui.screen_mode = 0; } +#[test] +fn panels_shown_by_window_panels_peek_stay_until_the_pointer_moves_or_leaves_the_window() { + let mut h = Harness::new(); + let wide = hide_with_tab(&mut h); + assert_eq!(h.app.run("window.panels.peek", json!({"side": "right"})).unwrap(), json!("right")); + wait(&mut h, peek::GRACE * 2.0); + assert!(h.tab("properties").is_some(), "with no pointer movement, the panels stay"); + assert_eq!(inspect(&h.app, &h.ctx)["peek"], json!("right")); + h.frame(vec![Event::PointerMoved(wide.center())]); + wait(&mut h, peek::GRACE * 2.0); + assert!(h.tab("properties").is_none(), "the pointer moved away from them, so they hide"); + // The pointer leaving the window counts as moving away. + h.app.run("window.panels.peek", json!({"side": "right"})).unwrap(); + wait(&mut h, peek::GRACE * 2.0); + assert!(h.tab("properties").is_some()); + h.frame(vec![Event::PointerGone]); + wait(&mut h, peek::GRACE * 2.0); + assert!(h.tab("properties").is_none(), "the pointer left the window, so they hide"); + assert_eq!(inspect(&h.app, &h.ctx)["peek"], Value::Null); +} + +#[test] +fn panels_held_by_a_flyout_hide_after_it_closes_with_the_pointer_still_away_from_them() { + let mut h = Harness::new(); + let wide = hide_with_tab(&mut h); + // The pointer rests on the canvas, then outside the window, while a flyout holds the panels. + for away in [vec![Event::PointerMoved(wide.center())], vec![Event::PointerGone]] { + h.app.run("window.panels.peek", json!({"side": "right"})).unwrap(); + h.app.ui.open_panel = Some("swatches".into()); + h.frame(away); + wait(&mut h, peek::GRACE * 2.0); + assert!(h.tab("properties").is_some(), "an open flyout keeps them"); + h.app.ui.open_panel = None; + wait(&mut h, peek::GRACE * 2.0); + assert!(h.tab("properties").is_none(), "the flyout closed with the pointer away from them, so they hide"); + assert_eq!(inspect(&h.app, &h.ctx)["peek"], Value::Null); + } +} + #[test] fn edge_panels_are_the_docked_panels_on_each_side_of_the_canvas() { let layout = default_from(DockTab::ALL[0], &[], false, None, None); From bb6a8076f3b20e8869264c3a19e16a6ba0c80a41 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 06:55:16 -0800 Subject: [PATCH 18/31] Brushes: a one-point brush.freehand continuation follows keepSelected A brush.freehand call that continued a path by one point changed the path's brush and left the selection as it was. With keepSelected off the path stayed selected, and with it on the path was not selected, unlike a longer continuation and unlike what path.freehand's params text says. The brush edit now selects the path, or deselects it while the rest of the selection stays, as a longer continuation does. A call that leaves the brush as it is still changes nothing. --- crates/engine/src/cmd/draw2/freehand.rs | 10 ++++++-- crates/engine/src/tests/brushsym.rs | 34 +++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/draw2/freehand.rs b/crates/engine/src/cmd/draw2/freehand.rs index 977f3f921a..55f5fe267b 100644 --- a/crates/engine/src/cmd/draw2/freehand.rs +++ b/crates/engine/src/cmd/draw2/freehand.rs @@ -227,12 +227,18 @@ 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. + // 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, _| { + s.edit("Paintbrush", |d, sel| { set_brush(d, target, name); + if keep_selected { + sel.set([id]); + } else { + sel.remove(id); + } Ok(()) })?; } diff --git a/crates/engine/src/tests/brushsym.rs b/crates/engine/src/tests/brushsym.rs index a2e9eb3012..706bf2a508 100644 --- a/crates/engine/src/tests/brushsym.rs +++ b/crates/engine/src/tests/brushsym.rs @@ -1037,6 +1037,40 @@ fn brush_freehand_direct_call_has_one_undo_step() { assert_eq!(s.doc().unwrap().history.undo.last().map(|e| e.label.as_str()), Some("Paintbrush"), "a stroke with a brush is a Paintbrush step"); } +/// A `brush.freehand` call that continues a path by one point changes only the path's brush, and +/// applies `keepSelected` as a longer continuation does: off, the path is deselected while the +/// rest of the selection stays; on, the path is selected. A call that leaves the brush as it is +/// changes neither the selection nor the undo history. +#[test] +fn brush_freehand_continued_by_one_point_follows_keep_selected() { + let mut s = session(); + let r = s.execute("brush.freehand", &json!({"points": [[10, 10], [60, 40], [120, 10]], "style": "brush", "brush": "Charcoal"})).unwrap(); + let p = NodeId(r["id"].as_u64().unwrap()); + let a = rect(&mut s, 200.0, 200.0, 10.0, 10.0); + let extend = json!({"id": p.0, "end": "end"}); + + select(&mut s, &[p, a]); + let off = json!({"points": [[120, 10]], "extend": extend, "brush": "Dots", "keepSelected": false}); + assert_eq!(s.execute("brush.freehand", &off).unwrap()["id"], json!(p.0)); + assert_eq!(brush_of(&s, p).as_deref(), Some("Dots")); + assert_eq!(selected(&s), [a], "Keep selected off: the path is deselected and the rest stays"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(brush_of(&s, p).as_deref(), Some("Charcoal"), "one Undo takes back the brush"); + assert_eq!(selected(&s), [p, a], "Undo gives back the earlier selection"); + + select(&mut s, &[a]); + let on = json!({"points": [[120, 10]], "extend": extend, "brush": "Dots"}); + s.execute("brush.freehand", &on).unwrap(); + assert_eq!(brush_of(&s, p).as_deref(), Some("Dots")); + assert_eq!(selected(&s), [p], "Keep selected on: the continued path is selected"); + + select(&mut s, &[a]); + let undo = s.doc().unwrap().history.undo.len(); + s.execute("brush.freehand", &on).unwrap(); + assert_eq!(selected(&s), [a], "the same brush again: the selection stays"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "the same brush again: no undo step"); +} + /// `brush.freehand` refuses a brush for a path with no stroke (a continued path, a redrawn one /// and a new filled pencil path while the stroke is None) instead of reporting it painted: the /// document, the selection and the undo history stay as they were. Without a brush the path is From 216e14a6a72f0572f2975b93830261142190b967 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 07:06:15 -0800 Subject: [PATCH 19/31] Recolor Artwork: Find keeps the plain tint when only an exact key shares its hex The tint Find gives a row that isn't selected was skipped when its hex matched the hex of a selected row's exact key, though `recolor.apply` matches an exact key only by its key. The lighter tint was taken, and when every candidate collided the color was left undimmed. Only a "#rrggbb" entry is now compared by hex. --- crates/ui-egui/src/dialogs/recolor.rs | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index a11bbd0aeb..13ca97d1aa 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -645,7 +645,7 @@ fn find_params(d: &Dialog) -> Option { let dimmed = |c: Color| { (0..FIND_TRIES) .map(|n| c.tinted(FIND_DIM - n as f32 * 0.01)) - .find(|t| !found_keys.contains(&ColorKey::of(t)) && !found_hex.contains(&t.to_hex())) + .find(|t| !found_keys.contains(&ColorKey::of(t)) && !found_hex_entries.contains(&t.to_hex())) .map(|t| key(&t)) }; // The current colors of the rows that aren't selected, and the preserved colors. @@ -2275,11 +2275,22 @@ mod tests { assert!(p["commands"][0]["params"]["map"].get("rgb 255 0 0").is_none(), "{p}"); // A dimmed color that a selected row lists would be recolored with it: a lighter tint is taken. let mut rs = rows(); - rs[0]["from"] = json!(["rgb 255 0 0", "rgb 191 191 255"]); + rs[0]["from"] = json!(["rgb 255 0 0", "rgb 191.25 191.25 255"]); d.fields.insert("rows".into(), json!(rs)); let p = find_params(&d).unwrap(); let to = color_value(&p["commands"][0]["params"]["map"]["rgb 0 0 255"]).unwrap(); assert_eq!(to.to_hex(), "#c2c2ff", "{p}"); + // So is one that a selected "#rrggbb" entry matches by its hex. + rs[0]["from"] = json!(["rgb 255 0 0", "#bfbfff"]); + d.fields.insert("rows".into(), json!(rs)); + let p = find_params(&d).unwrap(); + let to = color_value(&p["commands"][0]["params"]["map"]["rgb 0 0 255"]).unwrap(); + assert_eq!(to.to_hex(), "#c2c2ff", "{p}"); + // Another key of the same hex matches only itself, so the tint is kept. + rs[0]["from"] = json!(["rgb 255 0 0", "rgb 191 191 255"]); + d.fields.insert("rows".into(), json!(rs)); + let p = find_params(&d).unwrap(); + assert_eq!(p["commands"][0]["params"]["map"]["rgb 0 0 255"], dim("rgb 0 0 255"), "{p}"); // Every row selected with Preview off: nothing to show. d.fields.insert("__sel".into(), json!([0, 1, 2])); assert_eq!(find_params(&d), None); From 8e602cb980999801c13844d6bb1afff66c50e97a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 07:21:00 -0800 Subject: [PATCH 20/31] Recolor Artwork: Find dims a row color given as a value, not a string A row of the rows that aren't selected whose current color was given as a color value (`[r,g,b]` or a CMYK, gray or Lab object) was left undimmed, because only string entries went into the dimming map. Such a color now dims under its color key, the form `recolor.apply` matches it by. --- crates/ui-egui/src/dialogs/recolor.rs | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index 13ca97d1aa..e15256b693 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -660,8 +660,13 @@ fn find_params(d: &Dialog) -> Option { None => false, }; for k in others.filter(|k| !listed(k)) { - if let (Some(to), Some(name)) = (color_value(&k).and_then(dimmed), k.as_str()) { - dim.insert(name.to_string(), to); + // A string entry keeps its own form ("#rrggbb" matches by hex); a color value goes by its key. + let name = match k.as_str() { + Some(s) => Some(s.to_string()), + None => color_value(&k).map(|c| ColorKey::of(&c).to_string()), + }; + if let (Some(to), Some(name)) = (color_value(&k).and_then(dimmed), name) { + dim.insert(name, to); } } let mut commands = vec![]; @@ -2265,6 +2270,14 @@ mod tests { let mut e = d.clone(); e.fields.insert(PRESERVED.into(), json!(["rgb 0 0 0"])); assert_eq!(find_params(&e).unwrap()["commands"][0]["params"]["map"]["rgb 0 0 0"], dim("rgb 0 0 0")); + // A color given as a value instead of a string dims under its key, as `recolor.apply` reads it. + let mut e = d.clone(); + let mut rs = rows(); + rs[1]["from"] = json!([[0.0, 0.0, 1.0], {"c": 0, "m": 100, "y": 100, "k": 0}]); + e.fields.insert("rows".into(), json!(rs)); + let map = find_params(&e).unwrap()["commands"][0]["params"]["map"].clone(); + assert_eq!(map["rgb 0 0 255"], dim("rgb 0 0 255"), "{map}"); + assert_eq!(map["cmyk 0 100 100 0"], dim("cmyk 0 100 100 0"), "{map}"); // A color a selected row lists is not dimmed; with Preview off only the dimming runs. let mut rs = rows(); rs[2]["from"] = json!(["rgb 0 255 0", "rgb 255 0 0"]); From ec4a1ac25dfd570bd7336fc01667dafb2f3e380a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 07:27:08 -0800 Subject: [PATCH 21/31] PDF export: a set Don't Include Profiles removes image color profiles When Profile inclusion is set to Don't Include Profiles (`profiles: "none"`), gray, RGB and CMYK images are written in device color spaces without their ICC profiles, and a JPEG that is kept as is loses its APP2 ICC_PROFILE segments. PDF/A-2b, PDF/X-3 and PDF/X-4 keep tagging their images. Leaving the setting out keeps the earlier output. `profiles` now serializes as null when not set, `"default"` clears a preset's value, and Save PDF > Output lists Default first. Presets and stored settings saved earlier hold `"profiles": "none"`, so exports from them now drop image profiles. --- crates/doc/src/cmyk.rs | 20 ++++- crates/engine/src/cmd/fileio/pdf.rs | 2 +- .../engine/src/cmd/fileio/tests_pdfoutput.rs | 16 ++++ crates/pdf/src/export/images.rs | 48 ++++++---- crates/pdf/src/export/text.rs | 2 +- crates/pdf/src/images.rs | 90 +++++++++++++++---- crates/pdf/src/output.rs | 50 +++++++++-- crates/pdf/src/settings.rs | 20 ++++- crates/pdf/src/tests/cmykimages.rs | 29 ++++++ crates/pdf/src/tests/compression.rs | 81 ++++++++++++++++- crates/pdf/src/tests/settings.rs | 18 ++++ crates/ui-egui/src/dialogs/save_pdf.rs | 18 +++- docs/mcp.md | 6 +- docs/target-app-parity.md | 1 + 14 files changed, 348 insertions(+), 53 deletions(-) diff --git a/crates/doc/src/cmyk.rs b/crates/doc/src/cmyk.rs index 6339f0a4ca..60a6db4074 100644 --- a/crates/doc/src/cmyk.rs +++ b/crates/doc/src/cmyk.rs @@ -664,9 +664,6 @@ pub fn jpeg_with_icc(bytes: &[u8], icc: &[u8]) -> Option> { const CHUNK: usize = 0xFFFF - 2 - ICC_SEGMENT.len() - 2; let chunks: Vec<&[u8]> = icc.chunks(CHUNK).collect(); let count = u8::try_from(chunks.len()).ok().filter(|n| *n > 0)?; - if !bytes.starts_with(&[0xFF, 0xD8]) { - return None; - } let mut segments = Vec::with_capacity(icc.len() + 18 * chunks.len()); for (i, chunk) in chunks.iter().enumerate() { let len = u16::try_from(chunk.len() + 2 + ICC_SEGMENT.len() + 2).ok()?; @@ -676,6 +673,23 @@ pub fn jpeg_with_icc(bytes: &[u8], icc: &[u8]) -> Option> { segments.extend_from_slice(&[u8::try_from(i + 1).ok()?, count]); segments.extend_from_slice(chunk); } + with_icc_segments(bytes, segments) +} + +/// JPEG `bytes` without the ICC profile they carry: every `ICC_PROFILE` APP2 segment before the +/// scan taken out, and the other segments and the scan as they are. `None` for bytes whose +/// segments before the scan can't be read. +pub fn jpeg_without_icc(bytes: &[u8]) -> Option> { + with_icc_segments(bytes, vec![]) +} + +/// JPEG `bytes` with every `ICC_PROFILE` APP2 segment before the scan taken out and `segments` +/// written after the leading application segments; `None` when the bytes don't start a JPEG or +/// their segments before the scan can't be read. +fn with_icc_segments(bytes: &[u8], segments: Vec) -> Option> { + if !bytes.starts_with(&[0xFF, 0xD8]) { + return None; + } let mut out = Vec::with_capacity(bytes.len() + segments.len()); out.extend_from_slice(&[0xFF, 0xD8]); let mut icc_segments = Some(segments); diff --git a/crates/engine/src/cmd/fileio/pdf.rs b/crates/engine/src/cmd/fileio/pdf.rs index 77902b4a15..6738f0727c 100644 --- a/crates/engine/src/cmd/fileio/pdf.rs +++ b/crates/engine/src/cmd/fileio/pdf.rs @@ -128,7 +128,7 @@ pub fn specs() -> 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; printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, 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", + "{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; 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", has_doc, export_pdf ), diff --git a/crates/engine/src/cmd/fileio/tests_pdfoutput.rs b/crates/engine/src/cmd/fileio/tests_pdfoutput.rs index 04726fee46..c98a121ded 100644 --- a/crates/engine/src/cmd/fileio/tests_pdfoutput.rs +++ b/crates/engine/src/cmd/fileio/tests_pdfoutput.rs @@ -38,3 +38,19 @@ fn export_pdf_converts_colours_writes_the_output_intent_and_real_text() { let bad = s.execute("document.exportPdf", &json!({"output": {"conversion": "destination", "destination": "Missing"}})); assert!(matches!(bad, Err(crate::EngineError::BadParams { .. })), "{bad:?}"); } + +/// Over a saved preset whose Profiles setting is `none`, `"default"` leaves the setting unset, +/// while `null` keeps the preset's value; an unknown value is a bad parameter. +#[test] +fn profiles_default_unsets_a_presets_profiles_setting() { + use vectorcraft_pdf::{PdfPreset, PdfSettings, ProfileInclusion}; + let mut settings = PdfSettings::default(); + settings.output.profiles = Some(ProfileInclusion::None); + let saved = [PdfPreset { name: "No profiles".into(), description: String::new(), settings }]; + let resolve = |output: Value| pdf::resolve("document.exportPdf", &json!({"preset": "No profiles", "output": output}), &saved); + assert_eq!(resolve(json!({"profiles": "default"})).unwrap().output.profiles, None); + assert_eq!(resolve(json!({"profiles": null})).unwrap().output.profiles, Some(ProfileInclusion::None)); + assert_eq!(resolve(json!({"profiles": "all"})).unwrap().output.profiles, Some(ProfileInclusion::All)); + let bad = resolve(json!({"profiles": "sometimes"})); + assert!(matches!(bad, Err(crate::EngineError::BadParams { .. })), "{bad:?}"); +} diff --git a/crates/pdf/src/export/images.rs b/crates/pdf/src/export/images.rs index 04a3a811f3..32878eb2bc 100644 --- a/crates/pdf/src/export/images.rs +++ b/crates/pdf/src/export/images.rs @@ -3,6 +3,8 @@ use super::{Arc, BlendMode, Color, Exporter, Image, Node, NodeKind, Paint, Rect, use krilla::color::device_n::{Colorant, DeviceNSpace, Process}; use krilla::image::{BitsPerComponent, CustomImage, ImageColorspace}; +use crate::images::SourceProfiles; + /// The byte count of a repeated color channel, within [`vectorcraft_doc::MAX_RASTER_ALLOC`]. fn tinted_color_len(samples: usize, pixels: usize) -> Option { let bytes = samples.checked_mul(pixels)?; @@ -138,7 +140,7 @@ impl Exporter<'_> { } let doc = self.doc; let out = self.out.clone(); - let profiles = !out.standard.cmyk_only(); + let profiles = out.source_profiles(); let to_srgb = out.image_srgb_intent().map(|intent| crate::images::ToSrgb { intent, sixteen_bit: self.sixteen_bit }); let img = doc.image_blob(im).filter(|_| !self.left_out.contains(key)).and_then(|blob| { let cmyk_image = blob.is_cmyk(); @@ -147,7 +149,7 @@ impl Exporter<'_> { } let r = if cmyk_image { let icc = out.cmyk_image_icc(blob); - crate::images::recode_cmyk(blob, size, c, interpolate, out.cmyk_pixels(), None, icc.as_deref()) + crate::images::recode_cmyk(blob, size, c, interpolate, out.cmyk_pixels(), None, out.cmyk_tag(icc.as_deref())) } else { crate::images::recode(&blob.bytes, size, c, interpolate, out.pixels(), profiles, to_srgb) }; @@ -197,7 +199,8 @@ impl Exporter<'_> { let img = doc.image_blob(im).filter(|b| b.is_cmyk()).and_then(|blob| { let alpha = crate::images::mask_alpha(doc.image_blob(mi)?, im.width, im.height, m.clip)?; let icc = self.out.cmyk_image_icc(blob); - let r = crate::images::recode_cmyk(blob, size, self.compression, interpolate, self.out.cmyk_pixels(), Some(alpha), icc.as_deref()); + let tag = self.out.cmyk_tag(icc.as_deref()); + let r = crate::images::recode_cmyk(blob, size, self.compression, interpolate, self.out.cmyk_pixels(), Some(alpha), tag); if let (Some(w), Some(_)) = (r.warning, &r.image) { self.warn(w); } @@ -320,13 +323,15 @@ pub(super) fn png_8_bit(bytes: &[u8]) -> Option> { } /// Image `blob` as it is: PNG, JPEG, GIF and WebP through the PDF writer (JPEG data unchanged), -/// other formats (a TIFF) decoded with their 16-bit samples and, when `profiles` allows it (not in -/// PDF/X-1a), the ICC profile they carry ([`crate::images::decoded_image`]). Without `profiles`, an -/// image that carries a gray or RGB profile is written without it, and so is one whose gray or RGB -/// profile is malformed ([`crate::images::valid_icc`]): a JPEG with its data unchanged, an image of -/// another format decoded. Without `sixteen_bit` (a file before PDF 1.5), a PNG or another image of -/// 16 bits a sample is written at 8 bits ([`png_8_bit`]). -pub(super) fn embed(blob: &vectorcraft_doc::ImageBlob, interpolate: bool, sixteen_bit: bool, profiles: bool) -> Option { +/// other formats (a TIFF) decoded with their 16-bit samples and, when `profiles` keeps it (not in +/// PDF/X-1a), the ICC profile they carry ([`crate::images::decoded_image`]). When `profiles` +/// doesn't keep it, an image that carries a gray or RGB profile is written without it, and so is +/// one whose gray or RGB profile is malformed ([`crate::images::valid_icc`]): a JPEG with its data +/// unchanged, an image of another format decoded. With [`SourceProfiles::Remove`], an image that +/// carries any profile is written without it, a JPEG without its `ICC_PROFILE` segments (decoded +/// when those can't be taken out). Without `sixteen_bit` (a file before PDF 1.5), a PNG or another +/// image of 16 bits a sample is written at 8 bits ([`png_8_bit`]). +pub(super) fn embed(blob: &vectorcraft_doc::ImageBlob, interpolate: bool, sixteen_bit: bool, profiles: SourceProfiles) -> Option { // The header's size first: the writer's decoders allocate what it declares, and the encoded // bytes of an image that is far larger than any the app reads may be a few kilobytes. let size = image::ImageReader::new(std::io::Cursor::new(blob.bytes.as_slice())).with_guessed_format().ok()?.into_dimensions(); @@ -334,16 +339,25 @@ pub(super) fn embed(blob: &vectorcraft_doc::ImageBlob, interpolate: bool, sixtee return None; } let bytes = blob.bytes.as_ref().clone(); - // The PDF writer keeps a gray or RGB image's ICC profile: without `profiles`, or when the - // profile is malformed, such a JPEG is written without its profile, and an image of another + // The PDF writer keeps a gray or RGB image's ICC profile: unless `profiles` keeps it, or when + // the profile is malformed, such a JPEG is written without its profile, and an image of another // format is decoded and written without it. The color space is read from the header's bytes - // 16..20 even in a profile cut short, as the PDF writer reads it. - let strip = crate::images::source_icc(&bytes).is_some_and(|icc| match icc.get(16..20) { - Some(space @ (b"GRAY" | b"RGB ")) => !profiles || <[u8; 4]>::try_from(space).is_ok_and(|s| !crate::images::valid_icc(&icc, s)), + // 16..20 even in a profile cut short, as the PDF writer reads it. With `Remove`, a JPEG's + // `ICC_PROFILE` segments are taken out also when they don't make up a profile the decoder reads. + let remove = profiles == SourceProfiles::Remove; + let jpeg = matches!(blob.mime.as_str(), "image/jpeg" | "image/jpg"); + let unkept = crate::images::source_icc(&bytes).is_some_and(|icc| match icc.get(16..20) { + _ if remove => true, + Some(space @ (b"GRAY" | b"RGB ")) => { + profiles != SourceProfiles::Keep || <[u8; 4]>::try_from(space).is_ok_and(|s| !crate::images::valid_icc(&icc, s)) + } _ => false, }); + let strip = (remove && jpeg) || unkept; let direct = match blob.mime.as_str() { - "image/jpeg" | "image/jpg" if strip => Image::from_jpeg_with_icc(bytes.clone().into(), None, interpolate).ok(), + "image/jpeg" | "image/jpg" if strip => { + crate::images::jpeg_data(&bytes, remove).and_then(|data| Image::from_jpeg_with_icc(data.into(), None, interpolate).ok()) + } _ if strip => None, "image/png" if !sixteen_bit && png_16_bit(&bytes) => png_8_bit(&bytes).and_then(|png| Image::from_png(png.into(), interpolate).ok()), "image/png" => Image::from_png(bytes.clone().into(), interpolate).ok(), @@ -371,7 +385,7 @@ mod tests { let crc = !png[12..29].iter().fold(!0u32, |c, b| (0..8).fold(c ^ u32::from(*b), |c, _| if c & 1 == 1 { 0xEDB8_8320 ^ (c >> 1) } else { c >> 1 })); png[29..33].copy_from_slice(&crc.to_be_bytes()); - assert!(super::embed(&ImageBlob::png(png), false, true, true).is_none()); + assert!(super::embed(&ImageBlob::png(png), false, true, super::SourceProfiles::Keep).is_none()); } #[test] diff --git a/crates/pdf/src/export/text.rs b/crates/pdf/src/export/text.rs index c6946f5416..ea29167f1b 100644 --- a/crates/pdf/src/export/text.rs +++ b/crates/pdf/src/export/text.rs @@ -326,7 +326,7 @@ impl Exporter<'_> { let img = match self.images.get(&cache) { Some(img) => img.clone(), None => { - let img = embed(&image.blob, self.interpolate, self.sixteen_bit, !self.out.standard.cmyk_only()); + let img = embed(&image.blob, self.interpolate, self.sixteen_bit, self.out.source_profiles()); self.images.insert(cache, img.clone()); img } diff --git a/crates/pdf/src/images.rs b/crates/pdf/src/images.rs index ac1d77f372..0b7024e731 100644 --- a/crates/pdf/src/images.rs +++ b/crates/pdf/src/images.rs @@ -20,6 +20,9 @@ //! inverted samples, which the PDF writer's Decode array undoes. A CMYK image whose numbers are //! kept carries the CMYK profile it is given ([`cmyk_icc`]), whether it is embedded as it is or //! written again; without one it is untagged, a JPEG's own `ICC_PROFILE` segments included. +//! With Don't Include Profiles set ([`SourceProfiles::Remove`], [`CmykTag::Removed`]), a JPEG +//! embedded as it is loses its `ICC_PROFILE` segments, its other segments and compressed samples +//! unchanged. use std::io::Cursor; use std::sync::Arc; @@ -152,10 +155,10 @@ pub(crate) fn from_decoded(img: DynamicImage, icc: Option>, interpolate: } /// Image `bytes` decoded within [`limits`], with the ICC profile it carries ([`source_icc`]) when -/// `profiles` allows it (not in PDF/X-1a, which allows no ICC-based color spaces), as -/// [`from_decoded`] writes it. `None` when it can't be decoded. -pub(crate) fn decoded_image(bytes: &[u8], interpolate: bool, sixteen_bit: bool, profiles: bool) -> Option { - from_decoded(decoded(bytes)?, profiles.then(|| source_icc(bytes)).flatten(), interpolate, sixteen_bit) +/// `profiles` keeps it ([`SourceProfiles::Keep`]), as [`from_decoded`] writes it. `None` when it +/// can't be decoded. +pub(crate) fn decoded_image(bytes: &[u8], interpolate: bool, sixteen_bit: bool, profiles: SourceProfiles) -> Option { + from_decoded(decoded(bytes)?, (profiles == SourceProfiles::Keep).then(|| source_icc(bytes)).flatten(), interpolate, sixteen_bit) } /// Are all of the RGBA pixels `rgba` grey? @@ -330,6 +333,47 @@ pub(crate) struct ToSrgb { pub sixteen_bit: bool, } +/// What happens to the ICC profile a gray or RGB image carries +/// ([`crate::output::ColorOut::source_profiles`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum SourceProfiles { + /// The image keeps a well-formed gray or RGB profile ([`valid_icc`]). + Keep, + /// The image is untagged; a JPEG embedded as it is keeps its data unchanged (PDF/X-1a). + Untag, + /// The image is untagged and a JPEG embedded as it is loses its `ICC_PROFILE` segments, its + /// other segments and compressed samples unchanged (Don't Include Profiles). + Remove, +} + +/// The CMYK profile [`recode_cmyk`] tags a CMYK image that keeps its numbers with. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum CmykTag<'a> { + /// This profile ([`cmyk_icc`]). + Profile(&'a [u8]), + /// None; a JPEG embedded as it is keeps its data unchanged. + Untagged, + /// None, and a JPEG embedded as it is loses its `ICC_PROFILE` segments, its other segments + /// and compressed samples unchanged (Don't Include Profiles). + Removed, +} + +impl<'a> CmykTag<'a> { + /// The profile the image is tagged with. + fn icc(self) -> Option<&'a [u8]> { + match self { + Self::Profile(icc) => Some(icc), + Self::Untagged | Self::Removed => None, + } + } +} + +/// JPEG `bytes` as they are embedded: without their `ICC_PROFILE` segments with `remove` +/// ([`vectorcraft_doc::cmyk::jpeg_without_icc`]). `None` when those can't be taken out. +pub(crate) fn jpeg_data(bytes: &[u8], remove: bool) -> Option> { + if remove { vectorcraft_doc::cmyk::jpeg_without_icc(bytes) } else { Some(bytes.to_vec()) } +} + /// The ICC profile image `bytes` carries ([`source_icc`]), when it is a well-formed profile of /// colour space `space` (`GRAY` or `RGB `, [`valid_icc`]): `None` without one, `Some(None)` when /// the CMS can't read it. @@ -474,8 +518,7 @@ fn resample_channels(img: DynamicImage, r: &Rule, (w, h): (u32, u32)) -> Dynamic /// Encoded image `bytes` placed `size` points wide and high, as the Compression settings `c` ask: /// resampled when its resolution is above the threshold, compressed with ZIP or JPEG, its colours /// converted by `convert` (colour images). Pixels that keep their colours keep the ICC profile -/// they carry when `profiles` allows it (not in PDF/X-1a, which allows no ICC-based color spaces); -/// with `to_srgb`, pixels in a gray or RGB profile other than sRGB are converted from it to sRGB +/// they carry when `profiles` keeps it ([`SourceProfiles::Keep`]); with `to_srgb`, pixels in a gray or RGB profile other than sRGB are converted from it to sRGB /// instead ([`ToSrgb`]), and colour ones then by `convert`; grey ones that `convert` leaves as /// they are keep their profile. `interpolate` lets viewers smooth it. An image that can't be /// decoded is kept as it is, with a warning when its pixels were to be converted to sRGB. @@ -485,7 +528,7 @@ pub(crate) fn recode( c: &CompressionSettings, interpolate: bool, convert: Option<&Pixels>, - profiles: bool, + profiles: SourceProfiles, to_srgb: Option, ) -> Recoded { let keep = Recoded { image: None, warning: None, note: None }; @@ -553,9 +596,14 @@ pub(crate) fn recode( // Written as it is only when nothing converts it further. let as_is = kept(&rule, dims, size, jpeg) && convert.is_none(); // A JPEG kept as JPEG whose samples the conversion leaves unchanged (an sRGB - // profile): its JPEG data, without the profile. - if !changed && as_is && jpeg { - let image = Image::from_jpeg_with_icc(bytes.to_vec().into(), None, interpolate).ok(); + // profile): its JPEG data, without the profile (and, with `Remove`, without its + // segments: encoded again when those can't be taken out). + if !changed + && as_is + && jpeg + && let Some(data) = jpeg_data(bytes, profiles == SourceProfiles::Remove) + { + let image = Image::from_jpeg_with_icc(data.into(), None, interpolate).ok(); return Recoded { image, warning: rule.instead, note: None }; } // Not resampled and lossless: written at its own depth. @@ -573,7 +621,8 @@ pub(crate) fn recode( // Pixels that keep their colours keep the profile they are in; converted ones are in the // destination's. let want = if kind == Kind::Color { *b"RGB " } else { *b"GRAY" }; - let icc = (profiles && convert.is_none() && source.is_none()).then(|| source_icc(bytes)).flatten().filter(|icc| valid_icc(icc, want)); + let keeps = profiles == SourceProfiles::Keep && convert.is_none() && source.is_none(); + let icc = keeps.then(|| source_icc(bytes)).flatten().filter(|icc| valid_icc(icc, want)); let rgb_icc = icc.is_some() && kind == Kind::Color; let mut rgba = resample(img, &rule, sized(&rule, dims, size)).into_rgba8(); if kind == Kind::Mono { @@ -630,8 +679,8 @@ pub(crate) fn coverage_sized(w: u32, h: u32, cover: Vec, size: (f64, f64), c /// is when its numbers are (`convert` is `None`); otherwise its ink amounts are resampled, /// converted by `convert` and compressed again. With `alpha` (one sample a pixel, see /// [`mask_alpha`]) the image is lossless and carries it as its soft mask; `None` then when its -/// inks can't be read. When its numbers are kept, the image is tagged with CMYK profile `icc` -/// (see [`cmyk_icc`]), and is untagged without one; converted pixels are never tagged with it. +/// inks can't be read. When its numbers are kept, the image is tagged as `tag` says, and is +/// untagged without a profile; converted pixels are never tagged with it. pub(crate) fn recode_cmyk( blob: &ImageBlob, size: (f64, f64), @@ -639,18 +688,21 @@ pub(crate) fn recode_cmyk( interpolate: bool, convert: Option<&CmykPixels>, alpha: Option>, - icc: Option<&[u8]>, + tag: CmykTag<'_>, ) -> Recoded { let rule = rule(c, Kind::Color); let jpeg = jpeg_components(&blob.bytes).is_some(); - let icc = icc.filter(|_| convert.is_none()); + let icc = tag.icc().filter(|_| convert.is_none()); if jpeg && convert.is_none() && alpha.is_none() { let dims = ImageReader::new(Cursor::new(blob.bytes.as_slice())).with_guessed_format().ok().and_then(|r| r.into_dimensions().ok()); - if let Some((w, h)) = dims.filter(|d| kept(&rule, *d, size, true)) { - // The JPEG data as it is, tagged with `icc` rather than with its own segments; one - // larger than [`MAX_EMBED_PIXELS`] is not written. + // The JPEG data as it is (without its `ICC_PROFILE` segments with `CmykTag::Removed`: its + // inks are encoded again when those can't be taken out), tagged with `icc` rather than + // with its own segments; one larger than [`MAX_EMBED_PIXELS`] is not written. + if let Some((w, h)) = dims.filter(|d| kept(&rule, *d, size, true)) + && let Some(data) = jpeg_data(&blob.bytes, tag == CmykTag::Removed) + { let image = (u64::from(w) * u64::from(h) <= MAX_EMBED_PIXELS) - .then(|| Image::from_jpeg_with_icc(blob.bytes.as_ref().clone().into(), icc.map(|i| i.to_vec().into()), interpolate).ok()) + .then(|| Image::from_jpeg_with_icc(data.into(), icc.map(|i| i.to_vec().into()), interpolate).ok()) .flatten(); return Recoded { image, warning: rule.instead, note: None }; } diff --git a/crates/pdf/src/output.rs b/crates/pdf/src/output.rs index 92381e1628..454e41c5ac 100644 --- a/crates/pdf/src/output.rs +++ b/crates/pdf/src/output.rs @@ -24,7 +24,11 @@ //! 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`]). +//! and PDF/X-4 unless `profiles` is `destination` ([`ColorOut::cmyk_image_icc`]). 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 +//! ([`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 //! information (`/False` when an output intent is written untrapped). PDF/A files carry their @@ -70,6 +74,9 @@ pub(crate) struct ColorOut { /// CMYK images that keep their numbers are tagged with the CMYK profile they carry /// ([`Self::cmyk_image_icc`]). image_icc: bool, + /// Don't Include Profiles was set, in a file that doesn't tag every color: no image keeps its + /// own ICC profile, a JPEG's `ICC_PROFILE` segments included ([`Self::source_profiles`]). + no_profiles: bool, /// The CMYK profile that tags CMYK colours. cmyk_profile: String, /// Tagged RGB colours are written as their sRGB equivalents: why (a warning), when their RGB @@ -117,6 +124,7 @@ impl Default for ColorOut { dest: None, tagged: false, image_icc: false, + no_profiles: false, cmyk_profile, srgb_note: None, pixels: OnceLock::new(), @@ -246,9 +254,11 @@ impl ColorOut { } out.dest = Some(Dest { srgb: name == cms::SRGB, cms, model, keep, destination }); } - out.tagged = matches!(set.standard, Standard::PdfA2b | Standard::PdfX3 | Standard::PdfX4) + let profiles = set.output.profiles.unwrap_or_default(); + let tags_all = matches!(set.standard, Standard::PdfA2b | Standard::PdfX3 | Standard::PdfX4); + out.tagged = tags_all || (!set.standard.cmyk_only() - && match set.output.profiles { + && match profiles { ProfileInclusion::None => false, ProfileInclusion::All | ProfileInclusion::Destination => true, ProfileInclusion::TaggedSource => !doc.color_profiles.is_empty(), @@ -256,11 +266,14 @@ impl ColorOut { // Source profiles: with `all` and `taggedSource`, and in the files that tag every colour // unless only the destination profile is asked for; never in PDF/X-1a. out.image_icc = !set.standard.cmyk_only() - && match set.output.profiles { + && match profiles { ProfileInclusion::All | ProfileInclusion::TaggedSource => true, - ProfileInclusion::None => matches!(set.standard, Standard::PdfA2b | Standard::PdfX3 | Standard::PdfX4), + ProfileInclusion::None => tags_all, ProfileInclusion::Destination => false, }; + // A set Don't Include Profiles leaves out every image's own profile, outside the files + // that tag every color. + out.no_profiles = set.output.profiles == Some(ProfileInclusion::None) && !tags_all; let rgb = match &out.dest { Some(d) if d.model == Model::Rgb => (d.srgb, d.cms.settings().rgb.clone()), _ => (source.rgb_is_srgb(), st.rgb.clone()), @@ -367,6 +380,33 @@ impl ColorOut { crate::images::cmyk_icc(blob) } + /// 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. + 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 => CmykTag::Untagged, + } + } + + /// What happens to the ICC profile a gray or RGB image carries ([`crate::images::recode`]): + /// left out with its JPEG segments when Don't Include Profiles was set (not in PDF/A, PDF/X-3 + /// and PDF/X-4), left out of the color space in PDF/X-1a, which allows no ICC-based color + /// spaces, and kept otherwise, also when the Profiles setting isn't set. + pub(crate) fn source_profiles(&self) -> crate::images::SourceProfiles { + use crate::images::SourceProfiles; + if self.no_profiles { + SourceProfiles::Remove + } else if self.standard.cmyk_only() { + SourceProfiles::Untag + } else { + SourceProfiles::Keep + } + } + /// How CMYK images' ink amounts are converted; `None` when they keep their numbers (no /// conversion, or to a CMYK destination that keeps them). pub(crate) fn cmyk_pixels(&self) -> Option<&CmykPixels> { diff --git a/crates/pdf/src/settings.rs b/crates/pdf/src/settings.rs index adaaa30c9c..c2f5487cbb 100644 --- a/crates/pdf/src/settings.rs +++ b/crates/pdf/src/settings.rs @@ -387,7 +387,12 @@ pub struct OutputSettings { /// Destination profile name (empty: the document's profile; [`DOCUMENT_CMYK`]: the CMYK /// profile in effect, whatever the document's colour mode). pub destination: String, - pub profiles: ProfileInclusion, + /// The Profile Inclusion setting; `None` (left out, `null` or `"default"`) when it isn't set: + /// colors are then written as with [`ProfileInclusion::None`], while gray and RGB images keep + /// the ICC profiles they carry. A set [`ProfileInclusion::None`] also leaves those out (see + /// [`crate::output`]). + #[serde(deserialize_with = "unset_or_choice")] + pub profiles: Option, /// PDF/X output intent profile name. pub output_intent: String, pub output_condition: String, @@ -397,6 +402,19 @@ pub struct OutputSettings { pub trapped: bool, } +/// The JSON id of a setting that isn't set ([`OutputSettings::profiles`]), as `null` is. +pub const UNSET_CHOICE: &str = "default"; + +/// A choice that may be left unset: `null` and [`UNSET_CHOICE`] are `None`, a choice's id is that +/// choice. +fn unset_or_choice<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>(d: D) -> Result, D::Error> { + match Option::::deserialize(d)? { + None => Ok(None), + Some(id) if id == UNSET_CHOICE => Ok(None), + Some(id) => T::deserialize(serde::de::value::StringDeserializer::::new(id)).map(Some), + } +} + /// The Advanced section. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] diff --git a/crates/pdf/src/tests/cmykimages.rs b/crates/pdf/src/tests/cmykimages.rs index 590afa3df9..c9746d0fc4 100644 --- a/crates/pdf/src/tests/cmykimages.rs +++ b/crates/pdf/src/tests/cmykimages.rs @@ -573,6 +573,35 @@ 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"); } +/// 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. +#[test] +fn a_set_dont_include_profiles_takes_a_cmyk_jpegs_profile_out() { + let ink = [0u8, 102, 255, 0]; + let icc = cmyk_profile(|_| {}); + let jpg = cmyk_jpeg_with(&flat(ink, 64 * 64), 64, 64, &icc); + let d = image_doc(ImageBlob::new("image/jpeg", jpg.clone()), 64, 64); + let export = |s: serde_json::Value| { + 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:?}"); + (w.into_iter().next().unwrap(), out.bytes) + }; + let segment = |data: &[u8]| data.windows(12).any(|w| w == b"ICC_PROFILE\0"); + let (w, _) = export(json!({})); + assert!(w.data == jpg && segment(&w.data), "unset: the JPEG data unchanged"); + let s = json!({"output": {"profiles": "none"}}); + let (w, bytes) = export(s.clone()); + assert_eq!((w.space.as_str(), w.filter.as_deref()), ("DeviceCMYK", Some("DCTDecode")), "{s}"); + assert!(!segment(&w.data) && w.data.len() < jpg.len(), "{s}: no ICC_PROFILE segment is left"); + assert!(w.data == vectorcraft_doc::cmyk::jpeg_without_icc(&jpg).unwrap(), "{s}: the other segments and the scan unchanged"); + assert_eq!(blobs(&import(&bytes).unwrap())[0].cmyk().unwrap().data, ImageBlob::new("image/jpeg", jpg.clone()).cmyk().unwrap().data); + 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 CMYK JPEG kept as it is whose header declares far more pixels than the app reads is left out /// with a warning, as other images that large are. #[test] diff --git a/crates/pdf/src/tests/compression.rs b/crates/pdf/src/tests/compression.rs index f36cb88e4b..26c6826723 100644 --- a/crates/pdf/src/tests/compression.rs +++ b/crates/pdf/src/tests/compression.rs @@ -266,7 +266,7 @@ fn images_declaring_more_than_the_allowance_are_not_decoded() { assert_eq!(crate::images::mask_alpha(&blob, 60_000, 60_000, false), None); assert_eq!(crate::images::mask_alpha(&blob, 2, 2, false), None, "another size is not decoded at all"); let c: CompressionSettings = serde_json::from_value(json!({"gray": {"downsample": "bicubic", "ppi": 72, "abovePpi": 100}})).unwrap(); - let r = crate::images::recode(&png, (10.0, 10.0), &c, false, None, true, None); + let r = crate::images::recode(&png, (10.0, 10.0), &c, false, None, crate::images::SourceProfiles::Keep, None); assert!(r.image.is_none(), "kept as it is"); } @@ -425,6 +425,80 @@ fn pdf_x1a_keeps_a_tagged_gray_jpeg_as_jpeg() { } } +/// With Don't Include Profiles set, a gray or RGB image is written without the ICC profile it +/// carries: a PNG, JPEG or TIFF embedded as it is, resampled or compressed with JPEG, with alpha and +/// at 16 bits. A JPEG kept as it is loses its `ICC_PROFILE` segments, its compressed samples +/// unchanged. Left unset, or `null`, the setting keeps the profiles. PDF/X-4 files keep them +/// whatever the setting says. +#[test] +fn a_set_dont_include_profiles_removes_image_profiles() { + let (rgb, gray) = (icc_profile(b"RGB ", 600), icc_profile(b"GRAY", 300)); + let mut clear = colour().to_rgba8(); + clear.put_pixel(0, 0, image::Rgba([10, 20, 30, 0])); + let deep = DynamicImage::ImageRgb16(colour().to_rgb16()); + let export = |d: &Document, settings: Value| { + let mut settings: PdfSettings = serde_json::from_value(settings).unwrap(); + settings.compression.compress_text = false; + export_with_report(d, &PdfOptions { settings, ..Default::default() }).unwrap() + }; + let resampled = + json!({"color": {"downsample": "bicubic", "ppi": 150, "abovePpi": 225}, "gray": {"downsample": "bicubic", "ppi": 150, "abovePpi": 225}}); + let jpeg = json!({"color": {"compression": "jpeg"}, "gray": {"compression": "jpeg"}}); + let cases = [ + ("RGB PNG", tagged(&colour(), &rgb, ImageFormat::Png), "image/png", json!({}), "DeviceRGB"), + ("gray PNG", tagged(&colour().grayscale(), &gray, ImageFormat::Png), "image/png", json!({}), "DeviceGray"), + ("RGB JPEG", tagged(&colour(), &rgb, ImageFormat::Jpeg), "image/jpeg", json!({}), "DeviceRGB"), + ("gray JPEG", tagged(&colour().grayscale(), &gray, ImageFormat::Jpeg), "image/jpeg", json!({}), "DeviceGray"), + ("RGB TIFF", tagged(&colour(), &rgb, ImageFormat::Tiff), "image/tiff", json!({}), "DeviceRGB"), + ("gray TIFF", tagged(&colour().grayscale(), &gray, ImageFormat::Tiff), "image/tiff", json!({}), "DeviceGray"), + ("RGBA TIFF", tagged(&clear.into(), &rgb, ImageFormat::Tiff), "image/tiff", json!({}), "DeviceRGB"), + ("16-bit TIFF", tagged(&deep, &rgb, ImageFormat::Tiff), "image/tiff", json!({}), "DeviceRGB"), + ("RGB PNG, resampled", tagged(&colour(), &rgb, ImageFormat::Png), "image/png", resampled.clone(), "DeviceRGB"), + ("gray JPEG, resampled", tagged(&colour().grayscale(), &gray, ImageFormat::Jpeg), "image/jpeg", resampled, "DeviceGray"), + ("RGB TIFF as JPEG", tagged(&colour(), &rgb, ImageFormat::Tiff), "image/tiff", jpeg.clone(), "DeviceRGB"), + ("gray TIFF as JPEG", tagged(&colour().grayscale(), &gray, ImageFormat::Tiff), "image/tiff", jpeg, "DeviceGray"), + ]; + for (what, bytes, mime, compression, device) in cases { + let d = doc(bytes.clone(), mime); + // Left unset, or null, the image keeps its profile. + for profiles in [json!({}), json!({"profiles": null})] { + let r = export(&d, json!({"compression": compression.clone(), "output": profiles})); + let spaces = image_spaces(&r.bytes); + assert!(spaces.len() == 1 && spaces[0].space == "ICCBased" && spaces[0].icc.is_some(), "{what}, {profiles}: {spaces:?}"); + } + let none = export(&d, json!({"compression": compression.clone(), "output": {"profiles": "none"}})); + assert!(none.warnings.is_empty(), "{what}: {:?}", none.warnings); + let spaces = image_spaces(&none.bytes); + assert!(spaces.len() == 1 && spaces[0].space == device && spaces[0].icc.is_none(), "{what}: {spaces:?}"); + let data = image_data(&none.bytes); + assert!(data.iter().all(|d| !d.windows(12).any(|w| w == b"ICC_PROFILE\0")), "{what}: no ICC_PROFILE segment is left"); + if mime == "image/jpeg" && compression == json!({}) { + // The JPEG data without its profile segments: the image decoder reads the same pixels + // from it, and no profile. + assert!(data.len() == 1 && data[0].len() < bytes.len(), "{what}: the JPEG data kept"); + let decode = |b: &[u8]| image::load_from_memory_with_format(b, ImageFormat::Jpeg).unwrap(); + assert!(decode(&data[0]) == decode(&bytes), "{what}: the same pixels"); + assert!(crate::images::source_icc(&data[0]).is_none() && crate::images::source_icc(&bytes).is_some(), "{what}"); + } + // PDF/X-4 tags every colour: the image keeps its profile. + let x4 = export(&d, json!({"standard": "pdfX4", "compatibility": "1.6", "compression": compression, "output": {"profiles": "none"}})); + let spaces = image_spaces(&x4.bytes); + assert!(spaces.len() == 1 && spaces[0].space == "ICCBased", "{what}, PDF/X-4: {spaces:?}"); + } + // A JPEG whose `ICC_PROFILE` segments don't make up a profile (the first of two, the second + // missing) loses them too. + let plain = encoded(colour(), ImageFormat::Jpeg); + let mut part = vec![0xFF, 0xD8, 0xFF, 0xE2, 0, 30]; + part.extend_from_slice(b"ICC_PROFILE\0"); + part.extend_from_slice(&[1, 2]); + part.extend_from_slice(&rgb[..14]); + part.extend_from_slice(&plain[2..]); + assert!(crate::images::source_icc(&part).is_none(), "the decoder reads no profile"); + let none = export(&doc(part, "image/jpeg"), json!({"output": {"profiles": "none"}})); + let data = image_data(&none.bytes); + assert!(data == [plain], "an unreadable profile: the JPEG data without its segments"); +} + /// A gray or RGB TIFF that carries an ICC profile of its colour space is written in an ICC-based /// colour space holding the same profile, at 16 bits a sample from PDF 1.5 on, with its alpha as /// a soft mask; and so is a tagged TIFF or PNG that is resampled or compressed with JPEG. Pixels @@ -778,9 +852,10 @@ fn convert_to_srgb_converts_tagged_images_from_their_profile() { let c: CompressionSettings = serde_json::from_value(json!({})).unwrap(); let srgb_out = Some(crate::images::ToSrgb { intent: Intent::RelativeColorimetric, sixteen_bit: true }); for (what, png) in [("RGB", declared(&colour(), &p3)), ("gray", declared(&colour().grayscale(), &gray))] { - let r = crate::images::recode(&png, (100.0, 100.0), &c, false, None, true, srgb_out); + let keep = crate::images::SourceProfiles::Keep; + let r = crate::images::recode(&png, (100.0, 100.0), &c, false, None, keep, srgb_out); assert!(r.image.is_none() && r.warning.is_some_and(|w| w.contains("not converted to sRGB")), "{what}: {:?}", r.warning); - let r = crate::images::recode(&png, (100.0, 100.0), &c, false, None, true, None); + let r = crate::images::recode(&png, (100.0, 100.0), &c, false, None, keep, None); assert!(r.image.is_none() && r.warning.is_none(), "{what}, no conversion: {:?}", r.warning); // Too large to embed as it is too: the export leaves it out, and says only that. let mut settings: PdfSettings = serde_json::from_value(to_srgb(json!({}))).unwrap(); diff --git a/crates/pdf/src/tests/settings.rs b/crates/pdf/src/tests/settings.rs index e159b7b162..d4dd5a63ce 100644 --- a/crates/pdf/src/tests/settings.rs +++ b/crates/pdf/src/tests/settings.rs @@ -41,6 +41,24 @@ fn json_is_camel_case_and_partial_objects_keep_defaults() { } } +/// The Profiles setting is unset when left out, `null` or `"default"` (written as `null`), and set +/// by a choice's id; another value is refused. +#[test] +fn the_profiles_setting_can_be_left_unset() { + assert_eq!(serde_json::to_value(PdfSettings::default()).unwrap()["output"]["profiles"], serde_json::Value::Null); + for unset in [json!({}), json!({"profiles": null}), json!({"profiles": "default"})] { + assert_eq!(settings(json!({"output": unset.clone()})).output.profiles, None, "{unset}"); + } + for (id, want) in [("none", ProfileInclusion::None), ("all", ProfileInclusion::All), ("taggedSource", ProfileInclusion::TaggedSource)] { + let s = settings(json!({"output": {"profiles": id}})); + assert_eq!(s.output.profiles, Some(want), "{id}"); + assert_eq!(serde_json::from_value::(serde_json::to_value(&s).unwrap()).unwrap(), s, "{id} round-trips"); + } + for bad in [json!("Default"), json!("never"), json!(1)] { + assert!(serde_json::from_value::(json!({"output": {"profiles": bad.clone()}})).is_err(), "{bad}"); + } +} + #[test] fn passwords_are_never_serialized() { let s = settings(json!({"security": {"openPassword": "secret", "permissionsPassword": "owner"}})); diff --git a/crates/ui-egui/src/dialogs/save_pdf.rs b/crates/ui-egui/src/dialogs/save_pdf.rs index 225c2cee52..4f8bdf7667 100644 --- a/crates/ui-egui/src/dialogs/save_pdf.rs +++ b/crates/ui-egui/src/dialogs/save_pdf.rs @@ -325,6 +325,19 @@ pub(super) fn pick(ui: &mut egui::Ui, d: &mut Dialog, path: &str, wid true } +/// [`pick`] with a first entry, `unset`, for a setting that isn't set: shown while the value at +/// `path` isn't one of the choices, and stored as [`vectorcraft_pdf::UNSET_CHOICE`] when chosen. +fn pick_or_unset(ui: &mut egui::Ui, d: &mut Dialog, path: &str, width: f32, unset: &str) -> bool { + let current = choice_index::(d, path).map_or(0, |i| i + 1); + let lang = crate::i18n::current(); + let labels: Vec<&str> = std::iter::once(unset).chain(T::LABELS.iter().map(|label| choice_label(lang, path, label))).collect(); + let label = labels.get(current).copied().unwrap_or(unset); + let Some(i) = widgets::dropdown_with(ui, path, label, &labels, width, |_| true) else { return false }; + let id = i.checked_sub(1).and_then(|i| T::IDS.get(i)).copied().unwrap_or(vectorcraft_pdf::UNSET_CHOICE); + set(d, path, json!(id)); + true +} + /// Printer mark styles use adjectives, separately from interface language names. pub(super) fn choice_label<'a>(lang: crate::i18n::Lang, path: &str, label: &'a str) -> &'a str { if path == "marks.kind" { crate::i18n::tr_ctx(lang, "mark-style", label) } else { crate::i18n::tr(lang, label) } @@ -663,8 +676,9 @@ fn output(ui: &mut egui::Ui, d: &mut Dialog) { .collect(); row(ui, tl!("Destination:"), |ui| profile_pick(ui, d, "output.destination", &destinations, 2, converting)); row(ui, tl!("Profile inclusion:"), |ui| { - // A standard decides whether colours are tagged. - ui.add_enabled_ui(standard == Standard::None, |ui| pick::(ui, d, "output.profiles", 300.0, |_| true)); + // A standard decides whether colours are tagged. Not set, colors are untagged and gray and + // RGB images keep their profiles (shown as Default). + ui.add_enabled_ui(standard == Standard::None, |ui| pick_or_unset::(ui, d, "output.profiles", 300.0, tl!("Default"))); }); 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.")); diff --git a/docs/mcp.md b/docs/mcp.md index c38d6fc7a2..f805e6a40d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5917,7 +5917,11 @@ for its colour mode). `profiles` (`all`, `destination`, or `taggedSource` for a 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 -images are always untagged CMYK. `outputIntent` embeds a profile as the file's +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 `/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: diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 4c8b2d43f8..0b6bb3ac08 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1930,6 +1930,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - 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 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`). - An image that Open and Place store again keeps the ICC profile its file embeds and its 16-bit samples. A turned PNG, JPEG, WebP or TIFF stored as PNG, and a TIFF the image decoder reads, keep their gray or RGB samples at 8 or 16 bits with their gray or RGB profile in the PNG's `iCCP` chunk ([PNG specification, iCCP](https://www.w3.org/TR/png-3/#11iCCP)). A CMYK TIFF stored with one plane per ink and a turned CMYK JPEG or TIFF keep their CMYK profile as TIFF tag 34675, a JPEG's put together from all its APP2 segments ([ICC image-format guide](https://github.com/InternationalColorConsortium/iccDEV/blob/master/iccdev-mcp/docs/icc-format-guide.md)). A profile whose color space differs from the stored samples' is left out. The profile is kept in the stored image; how CMYK inks are drawn and exported to PDF does not change (`crates/engine/src/cmd/fileio/tests.rs`). - PDF export writes a stored gray or RGB TIFF in an `ICCBased` color space that holds the gray or RGB profile of its tag 34675, at 16 bits a sample from PDF 1.5 on and 8 before, with its alpha as a soft mask only when some pixel is not opaque ([ISO 32000-1, §8.6.5.5](https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf#page=157)). A gray or RGB image, a PNG included, that the Compression settings resample or compress with JPEG keeps its profile too, and gray pixels in an RGB profile stay RGB. Pixels the Output settings convert, a profile whose color space differs from the samples', and a malformed profile, a PNG's or JPEG's kept as it is included, are written without it; such a JPEG keeps its JPEG data. PDF/X-1a allows no ICC-based color spaces, so there a gray image with a gray profile, kept as it is, resampled or compressed with JPEG, is written in DeviceGray without the profile, a JPEG kept as JPEG with its JPEG data unchanged, and RGB images are converted to CMYK as before. CMYK images are unchanged (`crates/pdf/src/tests/compression.rs`). From 104a844da1c4da5ecc57a696b419f4812ddeaf9d Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Sun, 15 Nov 2026 16:35:15 +0530 Subject: [PATCH 22/31] feat(ui): implement Check Spelling modal dialog (#4936) # Conflicts: # docs/roadmap.md --- crates/mcp/src/ui_catalog.rs | 6 + crates/ui-egui/src/dialogs.rs | 2 + crates/ui-egui/src/dialogs/check_spelling.rs | 1101 ++++++++++++++++++ crates/ui-egui/src/menus/invoke.rs | 7 + crates/ui-egui/src/menus/run.rs | 1 + crates/ui-egui/src/menus/state.rs | 2 +- crates/ui-egui/src/menus/tree.rs | 2 +- crates/ui-egui/src/menus/ui_commands.rs | 6 + docs/gaps.md | 9 +- docs/roadmap.md | 5 +- docs/target-app-parity.md | 17 +- docs/type-parity.md | 5 +- 12 files changed, 1146 insertions(+), 17 deletions(-) create mode 100644 crates/ui-egui/src/dialogs/check_spelling.rs diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index ecbdf780fb..8e651622af 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -167,6 +167,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} toggle a red underline under the words of the document's type its dictionaries don't know (text.spelling.check lists them), kept up to date as the type changes; type with effects isn't underlined → whether Auto Spell Check is on", ), + ( + "ui.checkSpelling", + "Check Spelling…", + "Cmd+I", + "{} open the Check Spelling dialog to walk through unrecognized words with suggestions, ignore, change and dictionary options", + ), ("shortcuts.set", "Set Keyboard Shortcut", "", "{id: command id or tool:, shortcut: \"Cmd+Shift+K\" | \"\" (none) | null (default), force?}"), ("shortcuts.list", "List Keyboard Shortcuts", "", "{query?} → [{id, label, group, shortcut, default, overridden}]"), ("shortcuts.conflicts", "Keyboard Shortcut Conflicts", "", "{} → [{shortcut, ids}]"), diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 875e8025a1..fe48f28952 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -22,6 +22,7 @@ pub mod brush_options; pub mod brush_replace_art; pub mod bullets_numbering; pub mod char_style_options; +pub mod check_spelling; pub mod color_balance; pub mod color_guide_options; mod color_picker; @@ -460,6 +461,7 @@ registry! { EditSelection: [edit_selection::KIND] => edit_selection::SPEC, EditViews: [edit_views::KIND] => edit_views::SPEC, EditCustomDictionary: [custom_dictionary::KIND] => custom_dictionary::SPEC, + CheckSpelling: [check_spelling::KIND] => check_spelling::SPEC, PerspectivePlane: [perspective_plane::KIND] => perspective_plane::SPEC, LayerOptions: [layer_options::KIND] => layer_options::SPEC, LayersPanelOptions: [layers_panel_options::KIND] => layers_panel_options::SPEC, diff --git a/crates/ui-egui/src/dialogs/check_spelling.rs b/crates/ui-egui/src/dialogs/check_spelling.rs new file mode 100644 index 0000000000..5f0bb8693e --- /dev/null +++ b/crates/ui-egui/src/dialogs/check_spelling.rs @@ -0,0 +1,1101 @@ +//! Edit › Spelling › Check Spelling…: walk through unknown words in the selection or the whole +//! document, displaying the unrecognized word in its sentence context, with suggestions, and +//! Ignore, Ignore All, Change, Change All, Add to Dictionary, and Done / Cancel. +//! +//! Fields: +//! - `not_in_dictionary`: the current unrecognized word +//! - `context`: sentence context containing the unrecognized word +//! - `context_before`, `context_word`, `context_after`: parts of the sentence context +//! - `suggestions`: alternative words suggested by the dictionary +//! - `selected_suggestion`: the suggestion currently selected +//! - `change_to`: the replacement word (from suggestions or typed) +//! - `node_id`, `start`, `end`, `lang`: location of the current misspelling +//! - `ids`: object IDs checked (None: entire document) +//! - `skipped`: list of `[node_id, start]` skipped by Ignore +//! - `done`: whether spell checking has finished (or no unrecognized words found) + +use std::collections::BTreeMap; +use std::ops::Range; + +use serde_json::{Value, json}; + +use super::{DialogAction, DialogResult, DialogSpec}; +use crate::state::Dialog; +use crate::theme::Tokens; +use crate::{VectorcraftApp, widgets}; + +/// The dialog kind of Check Spelling. +pub const KIND: &str = "checkSpelling"; + +/// The command its menu item runs. +pub const COMMAND: &str = "ui.checkSpelling"; + +pub(super) const SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("Check Spelling").into(), + body_with_actions: Some(body), + confirm, + ok: None, + min_width: 480.0, + max_width: Some(560.0), + ..DialogSpec::FORM +}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Action { + Ignore, + IgnoreAll, + Change, + ChangeAll, + AddToDictionary, + Done, + Cancel, +} + +/// Open Check Spelling on the active document's type. +pub fn open(app: &mut VectorcraftApp) -> Result { + if app.session.active().is_none() { + return Err("no document".into()); + } + let doc_uid = app.session.doc().map_err(|e| e.to_string())?.uid; + let (ids, remaining_ids): (Option>, Vec) = { + let st = app.session.doc().map_err(|e| e.to_string())?; + let selected = &st.selection.objects; + if !selected.is_empty() { + let selected_ids: Vec = selected.iter().map(|n| n.0).collect(); + (Some(selected_ids.clone()), selected_ids) + } else { + let mut all_ordered = Vec::new(); + st.doc.walk(|n| { + if matches!(n.kind, vectorcraft_doc::NodeKind::Text(_)) && st.doc.is_editable(n.id) { + all_ordered.push(n.id.0); + } + }); + (None, all_ordered) + } + }; + let mut d = Dialog::new( + KIND, + json!({ + "doc_uid": doc_uid, + "ids": ids, + "remaining_ids": remaining_ids, + "skipped": [], + "not_in_dictionary": "", + "context": "", + "context_before": "", + "context_word": "", + "context_after": "", + "change_to": "", + "suggestions": [], + "selected_suggestion": null, + "node_id": null, + "start": null, + "end": null, + "lang": null, + "done": false, + }), + ); + advance(app, &mut d)?; + app.ui.dialog = Some(d); + Ok(Value::Null) +} + +fn get_skipped(d: &Dialog) -> Vec<(u64, u64)> { + d.fields + .get("skipped") + .and_then(Value::as_array) + .map(|arr| { + arr.iter() + .filter_map(|pair| { + let a = pair.as_array()?; + if a.len() == 2 { Some((a[0].as_u64()?, a[1].as_u64()?)) } else { None } + }) + .collect() + }) + .unwrap_or_default() +} + +fn set_skipped(d: &mut Dialog, skipped: &[(u64, u64)]) { + let arr: Vec = skipped.iter().map(|&(id, start)| json!([id, start])).collect(); + d.fields.insert("skipped".into(), json!(arr)); +} + +/// Extracts the sentence containing `range` within `text`, returning (before, word, after). +pub fn extract_sentence_context(text: &str, range: Range) -> (String, String, String) { + let empty = (String::new(), String::new(), String::new()); + if range.start > range.end { + return empty; + } + let Some(word_slice) = text.get(range.clone()) else { + return empty; + }; + let word = word_slice.to_string(); + + let Some(before_slice) = text.get(..range.start) else { + return empty; + }; + let nl_start = before_slice.rfind('\n').map(|idx| idx + 1); + let mut punct_start = None; + for (idx, ch) in before_slice.char_indices() { + if (ch == '.' || ch == '!' || ch == '?') && before_slice.get(idx + ch.len_utf8()..).is_some_and(|s| s.starts_with(char::is_whitespace)) { + punct_start = Some(idx + ch.len_utf8()); + } + } + let start_idx = match (nl_start, punct_start) { + (Some(nl), Some(p)) => nl.max(p), + (Some(nl), None) => nl, + (None, Some(p)) => p, + (None, None) => 0, + }; + + let Some(after_slice) = text.get(range.end..) else { + return empty; + }; + let nl_end = after_slice.find('\n'); + let mut punct_end = None; + for (idx, ch) in after_slice.char_indices() { + if ch == '.' || ch == '!' || ch == '?' { + let next_idx = idx + ch.len_utf8(); + if next_idx >= after_slice.len() || after_slice.get(next_idx..).is_some_and(|s| s.starts_with(char::is_whitespace)) { + punct_end = Some(next_idx); + break; + } + } + } + let end_offset = match (nl_end, punct_end) { + (Some(nl), Some(p)) => nl.min(p), + (Some(nl), None) => nl, + (None, Some(p)) => p, + (None, None) => after_slice.len(), + }; + + let mut before = text.get(start_idx..range.start).unwrap_or("").trim_start().to_string(); + let mut after = after_slice.get(..end_offset).unwrap_or("").trim_end().to_string(); + + const MAX_SIDE: usize = 120; + if before.len() > MAX_SIDE { + let target = before.len() - MAX_SIDE; + let split_idx = before.char_indices().map(|(idx, _)| idx).find(|&idx| idx >= target).unwrap_or(before.len()); + let suffix = before.get(split_idx..).unwrap_or(""); + before = match suffix.find(' ') { + Some(space) => format!("…{}", suffix.get(space..).unwrap_or("")), + None => format!("…{suffix}"), + }; + } + if after.len() > MAX_SIDE { + let split_idx = after.char_indices().map(|(idx, _)| idx).take_while(|&idx| idx <= MAX_SIDE).last().unwrap_or(0); + let prefix = after.get(..split_idx).unwrap_or(""); + after = match prefix.rfind(' ') { + Some(space) => format!("{}…", prefix.get(..space).unwrap_or("")), + None => format!("{prefix}…"), + }; + } + + (before, word, after) +} + +fn set_done(d: &mut Dialog) { + d.fields.insert("done".into(), json!(true)); + d.fields.insert("not_in_dictionary".into(), json!("")); + d.fields.insert("context".into(), json!(tl!("The spell check is complete."))); + d.fields.insert("context_before".into(), json!("")); + d.fields.insert("context_word".into(), json!("")); + d.fields.insert("context_after".into(), json!("")); + d.fields.insert("suggestions".into(), json!([])); + d.fields.insert("selected_suggestion".into(), Value::Null); + d.fields.insert("change_to".into(), json!("")); + d.fields.insert("node_id".into(), Value::Null); + d.fields.insert("start".into(), Value::Null); + d.fields.insert("end".into(), Value::Null); + d.fields.insert("lang".into(), Value::Null); +} + +/// Advance to the next unrecognized word or complete the spell check. +pub fn advance(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { + let mut remaining_ids: Vec = + d.fields.get("remaining_ids").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_u64).collect()).unwrap_or_default(); + + if remaining_ids.is_empty() && d.fields.get("ids").is_none_or(Value::is_null) { + let st = app.session.doc().map_err(|e| e.to_string())?; + st.doc.walk(|n| { + if matches!(n.kind, vectorcraft_doc::NodeKind::Text(_)) && st.doc.is_editable(n.id) { + remaining_ids.push(n.id.0); + } + }); + d.fields.insert("remaining_ids".into(), json!(remaining_ids)); + } + + let skipped = get_skipped(d); + + loop { + if remaining_ids.is_empty() { + set_done(d); + return Ok(()); + } + + let check_res = app.run("text.spelling.check", json!({ "ids": remaining_ids })).map_err(|e| e.to_string())?; + let words = check_res.get("words").and_then(Value::as_array).cloned().unwrap_or_default(); + let more = check_res.get("more").and_then(Value::as_bool).unwrap_or(false); + + let next_word = words + .iter() + .find(|w| { + let id = w.get("id").and_then(Value::as_u64).unwrap_or(0); + let start = w.get("start").and_then(Value::as_u64).unwrap_or(0); + !skipped.contains(&(id, start)) + }) + .cloned(); + + if let Some(w) = next_word { + let id = w["id"].as_u64().unwrap_or(0); + let start = w["start"].as_u64().unwrap_or(0) as usize; + let end = w["end"].as_u64().unwrap_or(0) as usize; + let word = w["word"].as_str().unwrap_or("").to_string(); + let lang = w["lang"].as_str().unwrap_or("en").to_string(); + + let (before, target, after) = { + let st = app.session.doc().map_err(|e| e.to_string())?; + if let Some(vectorcraft_doc::NodeKind::Text(t)) = st.doc.node(vectorcraft_doc::NodeId(id)).map(|n| &n.kind) { + extract_sentence_context(&t.plain_text(), start..end) + } else { + (String::new(), word.clone(), String::new()) + } + }; + + let sugg_res = app.run("text.spelling.suggest", json!({ "word": word, "lang": lang, "max": 10 })).map_err(|e| e.to_string())?; + let suggestions: Vec = sugg_res + .get("suggestions") + .and_then(Value::as_array) + .map(|a| a.iter().filter_map(Value::as_str).map(String::from).collect()) + .unwrap_or_default(); + + let change_to = suggestions.first().cloned().unwrap_or_else(|| word.clone()); + let full_context = format!("{before}{target}{after}"); + + d.fields.insert("not_in_dictionary".into(), json!(word)); + d.fields.insert("context".into(), json!(full_context)); + d.fields.insert("context_before".into(), json!(before)); + d.fields.insert("context_word".into(), json!(target)); + d.fields.insert("context_after".into(), json!(after)); + d.fields.insert("suggestions".into(), json!(suggestions)); + d.fields.insert("selected_suggestion".into(), json!(suggestions.first().cloned())); + d.fields.insert("change_to".into(), json!(change_to)); + d.fields.insert("node_id".into(), json!(id)); + d.fields.insert("start".into(), json!(start)); + d.fields.insert("end".into(), json!(end)); + d.fields.insert("lang".into(), json!(lang)); + d.fields.insert("done".into(), json!(false)); + return Ok(()); + } + + if more && !words.is_empty() { + let last_id = words.last().and_then(|w| w.get("id")).and_then(Value::as_u64).unwrap_or(0); + if let Some(pos) = remaining_ids.iter().position(|&id| id == last_id) + && pos > 0 + { + remaining_ids.drain(0..pos); + d.fields.insert("remaining_ids".into(), json!(remaining_ids)); + continue; + } + if remaining_ids.len() > 1 { + remaining_ids.remove(0); + d.fields.insert("remaining_ids".into(), json!(remaining_ids)); + continue; + } + } + + set_done(d); + return Ok(()); + } +} + +fn check_doc_uid(app: &VectorcraftApp, d: &Dialog) -> Result<(), String> { + let doc_uid = d.fields.get("doc_uid").and_then(Value::as_u64); + let active_uid = app.session.active().map(|st| st.uid); + if doc_uid.is_some() && doc_uid != active_uid { + return Err("the document was switched".into()); + } + Ok(()) +} + +fn ignore(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { + check_doc_uid(app, d)?; + if d.bool("done") { + return Ok(()); + } + let id = d.fields.get("node_id").and_then(Value::as_u64).unwrap_or(0); + let start = d.fields.get("start").and_then(Value::as_u64).unwrap_or(0); + let mut skipped = get_skipped(d); + skipped.push((id, start)); + set_skipped(d, &skipped); + advance(app, d) +} + +fn ignore_all(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { + check_doc_uid(app, d)?; + if d.bool("done") { + return Ok(()); + } + let word = d.str("not_in_dictionary"); + if !word.is_empty() { + app.run("text.spelling.ignoreAll", json!({ "word": word })).map_err(|e| e.to_string())?; + } + advance(app, d) +} + +fn change(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { + check_doc_uid(app, d)?; + if d.bool("done") { + return Ok(()); + } + let id = d.fields.get("node_id").and_then(Value::as_u64).unwrap_or(0); + let start = d.fields.get("start").and_then(Value::as_u64).unwrap_or(0) as usize; + let end = d.fields.get("end").and_then(Value::as_u64).unwrap_or(0) as usize; + let expected_word = d.str("not_in_dictionary"); + let change_to = d.str("change_to"); + if !change_to.trim().is_empty() && id > 0 { + let text_matches = { + let st = app.session.doc().map_err(|e| e.to_string())?; + if let Some(vectorcraft_doc::NodeKind::Text(t)) = st.doc.node(vectorcraft_doc::NodeId(id)).map(|n| &n.kind) { + let plain = t.plain_text(); + plain.get(start..end).map(|s| s == expected_word).unwrap_or(false) + } else { + false + } + }; + + if text_matches { + app.run("text.editRange", json!({ "id": id, "start": start, "end": end, "insert": change_to })).map_err(|e| e.to_string())?; + } else { + return advance(app, d); + } + } + advance(app, d) +} + +fn change_all(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { + check_doc_uid(app, d)?; + if d.bool("done") { + return Ok(()); + } + let word = d.str("not_in_dictionary"); + let change_to = d.str("change_to"); + if word.is_empty() || change_to.trim().is_empty() { + return advance(app, d); + } + let initial_ids = d.fields.get("ids").cloned().unwrap_or(Value::Null); + let skipped = get_skipped(d); + + let mut undo_group_started = false; + let mut execute_changes = || -> Result<(), String> { + let mut replaced_spans: Vec<(u64, usize, usize)> = Vec::new(); + let mut all_commands = Vec::new(); + loop { + let check_res = app.run("text.spelling.check", json!({ "ids": initial_ids })).map_err(|e| e.to_string())?; + let words = check_res.get("words").and_then(Value::as_array).cloned().unwrap_or_default(); + let more = check_res.get("more").and_then(Value::as_bool).unwrap_or(false); + + let mut by_node: BTreeMap> = BTreeMap::new(); + let mut new_edits = 0; + for w in &words { + let id = w.get("id").and_then(Value::as_u64).unwrap_or(0); + let start = w.get("start").and_then(Value::as_u64).unwrap_or(0) as usize; + let end = w.get("end").and_then(Value::as_u64).unwrap_or(0) as usize; + let w_str = w.get("word").and_then(Value::as_str).unwrap_or(""); + if skipped.contains(&(id, start as u64)) { + continue; + } + if replaced_spans.iter().any(|&(r_id, r_start, r_end)| r_id == id && start >= r_start && start < r_end) { + continue; + } + if w_str.eq_ignore_ascii_case(&word) { + by_node.entry(id).or_default().push((start, end)); + new_edits += 1; + } + } + + if new_edits == 0 { + break; + } + + let new_len = change_to.len() as isize; + for (r_id, r_start, r_end) in &mut replaced_spans { + if let Some(ranges) = by_node.get(r_id) { + let delta: isize = ranges.iter().filter(|(_, end)| *end <= *r_start).map(|(start, end)| new_len - (*end - *start) as isize).sum(); + *r_start = (*r_start as isize + delta).max(0) as usize; + *r_end = (*r_end as isize + delta).max(0) as usize; + } + } + for (&id, ranges) in &by_node { + for &(start, _) in ranges { + let delta: isize = ranges + .iter() + .filter(|(_, other_end)| *other_end <= start) + .map(|(other_start, other_end)| new_len - (*other_end - *other_start) as isize) + .sum(); + let post_start = (start as isize + delta).max(0) as usize; + let post_end = post_start + change_to.len(); + replaced_spans.push((id, post_start, post_end)); + } + } + + let mut batch_commands = Vec::new(); + for (id, mut ranges) in by_node { + ranges.sort_by_key(|a| std::cmp::Reverse(a.0)); + for (start, end) in ranges { + batch_commands.push(json!({ + "command": "text.editRange", + "params": { + "id": id, + "start": start, + "end": end, + "insert": change_to, + } + })); + } + } + + if !batch_commands.is_empty() { + if batch_commands.len() == 1 && !more && all_commands.is_empty() && !undo_group_started { + let cmd = &batch_commands[0]; + app.run(cmd["command"].as_str().unwrap_or("text.editRange"), cmd["params"].clone()).map_err(|e| e.to_string())?; + break; + } else if more { + if !undo_group_started { + app.run("edit.undoGroup.begin", json!({ "label": "Change All" })).map_err(|e| e.to_string())?; + undo_group_started = true; + } + app.run("command.batch", json!({ "label": "Change All", "commands": batch_commands })).map_err(|e| e.to_string())?; + continue; + } else { + all_commands.extend(batch_commands); + break; + } + } + + break; + } + + if !all_commands.is_empty() { + if all_commands.len() == 1 && !undo_group_started { + let cmd = &all_commands[0]; + app.run(cmd["command"].as_str().unwrap_or("text.editRange"), cmd["params"].clone()).map_err(|e| e.to_string())?; + } else { + app.run("command.batch", json!({ "label": "Change All", "commands": all_commands })).map_err(|e| e.to_string())?; + } + } + Ok(()) + }; + + let res = execute_changes(); + if undo_group_started { + let cancel = res.is_err(); + let _ = app.run("edit.undoGroup.end", json!({ "cancel": cancel })); + } + res?; + advance(app, d) +} + +fn add_to_dictionary(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { + check_doc_uid(app, d)?; + if d.bool("done") { + return Ok(()); + } + let word = d.str("not_in_dictionary"); + if !word.is_empty() { + app.run("text.spelling.addWord", json!({ "word": word })).map_err(|e| e.to_string())?; + } + advance(app, d) +} + +fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAction { + let doc_uid = d.fields.get("doc_uid").and_then(Value::as_u64); + let active_uid = app.session.active().map(|st| st.uid); + if doc_uid.is_some() && doc_uid != active_uid { + return DialogAction::Cancel; + } + + if let Some(act) = d.fields.remove("action").and_then(|v| v.as_str().map(String::from)) { + let res = match act.as_str() { + "ignore" => ignore(app, d), + "ignoreAll" => ignore_all(app, d), + "change" => change(app, d), + "changeAll" => change_all(app, d), + "addToDictionary" => add_to_dictionary(app, d), + "done" | "cancel" => return DialogAction::Cancel, + _ => Ok(()), + }; + if let Err(e) = res { + app.status(&e); + d.fields.insert("error".into(), json!(e)); + } else { + d.fields.remove("error"); + } + } + + let mut action_to_run = None; + let done = d.bool("done"); + let before = d.str("context_before"); + let target = d.str("context_word"); + let after = d.str("context_after"); + let mut change_to = d.str("change_to"); + let suggestions: Vec = d + .fields + .get("suggestions") + .and_then(Value::as_array) + .map(|a| a.iter().filter_map(Value::as_str).map(String::from).collect()) + .unwrap_or_default(); + + let can_change = !done && !change_to.trim().is_empty(); + + if crate::shortcuts::pressed_anew(ui.ctx(), egui::Key::Enter) + || ui.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Key { key: egui::Key::Enter, pressed: true, repeat: false, .. }))) + { + if can_change { + action_to_run = Some(Action::Change); + } else if done { + return DialogAction::Cancel; + } + } + if ui.input(|i| i.key_pressed(egui::Key::Escape)) { + return DialogAction::Cancel; + } + + let action_col_width = 110.0; + let col_spacing = 16.0; + let text_col_width = (ui.available_width() - action_col_width - col_spacing).clamp(200.0, 320.0); + + ui.horizontal_top(|ui| { + ui.vertical(|ui| { + ui.set_width(text_col_width); + if done { + ui.add_space(20.0); + widgets::dim_label(ui, tl!("The spell check is complete.")); + ui.add_space(80.0); + } else { + widgets::dim_label(ui, tl!("Not in Dictionary:")); + ui.group(|ui| { + ui.set_width(text_col_width); + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing.x = 0.0; + if !before.is_empty() { + ui.label(&before); + } + let t = Tokens::get(ui.ctx()); + ui.add(egui::Label::new(egui::RichText::new(&target).color(t.accent).strong().underline())); + if !after.is_empty() { + ui.label(&after); + } + }); + }); + + ui.add_space(8.0); + widgets::dim_label(ui, tl!("Change to:")); + let field_id = ui.scope_id().with(("dlg-text", "change_to")); + widgets::take_dialog_focus(ui, field_id, &change_to); + if ui.add(egui::TextEdit::singleline(&mut change_to).id(field_id).desired_width(text_col_width)).changed() { + d.fields.insert("change_to".into(), json!(change_to)); + } + + ui.add_space(8.0); + widgets::dim_label(ui, tl!("Suggestions:")); + widgets::list_box(ui, |ui| { + ui.set_width(text_col_width); + let row = ui.spacing().interact_size.y; + egui::ScrollArea::vertical().id_salt("check-spelling-suggestions").min_scrolled_height(140.0).max_height(140.0).show_rows( + ui, + row, + suggestions.len(), + |ui, range| { + ui.set_width(ui.available_width()); + for s in suggestions.get(range).unwrap_or_default() { + let is_selected = change_to == *s; + if ui.selectable_label(is_selected, s.as_str()).clicked() { + d.fields.insert("change_to".into(), json!(s)); + d.fields.insert("selected_suggestion".into(), json!(s)); + } + } + }, + ); + }); + } + }); + + ui.add_space(col_spacing); + + ui.vertical(|ui| { + let w = action_col_width; + if ui.add_enabled_ui(!done, |ui| widgets::flat_button_fit(ui, tl!("Ignore"), w).clicked()).inner { + action_to_run = Some(Action::Ignore); + } + ui.add_space(6.0); + if ui.add_enabled_ui(!done, |ui| widgets::flat_button_fit(ui, tl!("Ignore All"), w).clicked()).inner { + action_to_run = Some(Action::IgnoreAll); + } + ui.add_space(6.0); + if ui.add_enabled_ui(can_change, |ui| widgets::flat_button_fit(ui, tl!("Change"), w).clicked()).inner { + action_to_run = Some(Action::Change); + } + ui.add_space(6.0); + if ui.add_enabled_ui(can_change, |ui| widgets::flat_button_fit(ui, tl!("Change All"), w).clicked()).inner { + action_to_run = Some(Action::ChangeAll); + } + ui.add_space(6.0); + if ui.add_enabled_ui(!done, |ui| widgets::flat_button_fit(ui, tl!("Add to Dictionary"), w).clicked()).inner { + action_to_run = Some(Action::AddToDictionary); + } + ui.add_space(16.0); + if widgets::flat_button_fit(ui, tl!("Done"), w).clicked() { + action_to_run = Some(Action::Done); + } + ui.add_space(6.0); + if widgets::flat_button_fit(ui, tl!("Cancel"), w).clicked() { + action_to_run = Some(Action::Cancel); + } + }); + }); + + if let Some(act) = action_to_run { + let res = match act { + Action::Ignore => ignore(app, d), + Action::IgnoreAll => ignore_all(app, d), + Action::Change => change(app, d), + Action::ChangeAll => change_all(app, d), + Action::AddToDictionary => add_to_dictionary(app, d), + Action::Done | Action::Cancel => return DialogAction::Cancel, + }; + if let Err(e) = res { + app.status(&e); + d.fields.insert("error".into(), json!(e)); + } else { + d.fields.remove("error"); + } + } + + DialogAction::None +} + +fn confirm(app: &mut VectorcraftApp, _: &Dialog) -> DialogResult { + app.ui.dialog = None; + Ok(Value::Null) +} + +#[cfg(test)] +mod tests { + use egui::{Event, PointerButton, Pos2, Rect, vec2}; + use serde_json::json; + + use crate::VectorcraftApp; + + const WORD_A: &str = "zqvspella"; + const WORD_B: &str = "zqvspellb"; + const WORD_C: &str = "zqvspellc"; + + fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + app + } + + fn text(app: &mut VectorcraftApp, y: f64, text: &str) -> u64 { + app.run("text.create", json!({"x": 10, "y": y, "text": text})).unwrap()["id"].as_u64().unwrap() + } + + fn forget(app: &mut VectorcraftApp, words: &[&str]) { + for w in words { + let _ = app.run("text.spelling.removeWord", json!({ "word": w })); + } + } + + fn context() -> egui::Context { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + ctx + } + + fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> Vec<(String, Rect)> { + let time = ctx.input(|i| i.time) + 0.25; + let screen_rect = Some(Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))); + let raw = egui::RawInput { screen_rect, events, time: Some(time), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| crate::dialogs::show(app, ui.ctx())); + out.textures_delta.clear(); + fn walk(s: &egui::Shape, v: &mut Vec<(String, Rect)>) { + match s { + egui::Shape::Text(t) => v.push((t.galley.text().to_string(), 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 + } + + fn click(app: &mut VectorcraftApp, ctx: &egui::Context, label: &str) -> Vec<(String, Rect)> { + frame(app, ctx, vec![]); + let texts = frame(app, ctx, vec![]); + let at = texts.iter().find(|(t, _)| t == label).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("no `{label}` in {texts:?}")); + let press = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(app, ctx, vec![Event::PointerMoved(at)]); + frame(app, ctx, vec![press(true)]); + frame(app, ctx, vec![press(false)]); + frame(app, ctx, vec![]) + } + + fn key_press(app: &mut VectorcraftApp, ctx: &egui::Context, key: egui::Key) { + let down = Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + frame(app, ctx, vec![down]); + let up = Event::Key { key, physical_key: None, pressed: false, repeat: false, modifiers: egui::Modifiers::NONE }; + frame(app, ctx, vec![up]); + } + + #[test] + fn test_extract_sentence_context() { + let text = "First sentence. Here is teh sample typo! Third sentence."; + let (before, word, after) = super::extract_sentence_context(text, 24..27); + assert_eq!(word, "teh"); + assert_eq!(before, "Here is "); + assert_eq!(after, " sample typo!"); + + let single = "Hello world"; + let (b, w, a) = super::extract_sentence_context(single, 6..11); + assert_eq!(w, "world"); + assert_eq!(b, "Hello "); + assert_eq!(a, ""); + + #[allow(clippy::reversed_empty_ranges)] + let (b_inv, w_inv, a_inv) = super::extract_sentence_context(single, 10..5); + assert!(w_inv.is_empty() && b_inv.is_empty() && a_inv.is_empty()); + + // Multibyte UTF-8 regression test (e.g. 61 copies of 'é', which is 122 bytes) + let after_multibyte = format!("word {}", "é".repeat(70)); + let (b_mb, w_mb, a_mb) = super::extract_sentence_context(&after_multibyte, 0..4); + assert_eq!(w_mb, "word"); + assert_eq!(b_mb, ""); + assert!(a_mb.ends_with('…')); + + let before_multibyte = format!("{} typo end.", "é".repeat(70)); + let typo_start = "é".repeat(70).len() + 1; + let typo_end = typo_start + 4; + let (b_mb2, w_mb2, a_mb2) = super::extract_sentence_context(&before_multibyte, typo_start..typo_end); + assert_eq!(w_mb2, "typo"); + assert!(b_mb2.starts_with('…')); + assert_eq!(a_mb2, " end."); + + // Stale / out-of-bounds or non-char boundary offsets never panic + let (b_oob, w_oob, a_oob) = super::extract_sentence_context(single, 5..50); + assert!(w_oob.is_empty() && b_oob.is_empty() && a_oob.is_empty()); + + let utf8_sample = "Héllo world"; + let (b_mid, w_mid, a_mid) = super::extract_sentence_context(utf8_sample, 2..4); + assert!(w_mid.is_empty() && b_mid.is_empty() && a_mid.is_empty()); + } + + #[test] + fn menu_opens_check_spelling_dialog() { + let mut app = app(); + text(&mut app, 50.0, &format!("Hello {WORD_A} world")); + + let e = crate::menus::menu_entries(&app).into_iter().find(|e| e.label == "Check Spelling…").expect("in Edit menu"); + assert_eq!(e.command.as_deref(), Some(super::COMMAND)); + assert!(e.enabled); + + crate::menus::invoke(&mut app, super::COMMAND, json!({})); + let d = app.ui.dialog.as_ref().expect("Check Spelling dialog opens"); + assert_eq!(d.kind, super::KIND); + assert_eq!(d.str("not_in_dictionary"), WORD_A); + assert!(d.str("context").contains(WORD_A)); + assert!(!d.bool("done")); + } + + #[test] + fn check_spelling_word_replacement_and_undo_redo() { + let mut app = app(); + let id = text(&mut app, 50.0, &format!("Prefix {WORD_A} suffix")); + + super::open(&mut app).unwrap(); + let ctx = context(); + + // Change replacement word + app.ui.dialog.as_mut().unwrap().fields.insert("change_to".into(), json!("replacement")); + click(&mut app, &ctx, "Change"); + + // Verify word replacement in the document + let plain = { + let st = app.session.doc().unwrap(); + match &st.doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind { + vectorcraft_doc::NodeKind::Text(t) => t.plain_text(), + _ => panic!("not text"), + } + }; + assert_eq!(plain, "Prefix replacement suffix"); + + // Verify one-step undo brings the original word back + app.run("edit.undo", json!({})).unwrap(); + let plain_undone = { + let st = app.session.doc().unwrap(); + match &st.doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind { + vectorcraft_doc::NodeKind::Text(t) => t.plain_text(), + _ => panic!("not text"), + } + }; + assert_eq!(plain_undone, format!("Prefix {WORD_A} suffix")); + + // Verify redo re-applies the replacement + app.run("edit.redo", json!({})).unwrap(); + let plain_redone = { + let st = app.session.doc().unwrap(); + match &st.doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind { + vectorcraft_doc::NodeKind::Text(t) => t.plain_text(), + _ => panic!("not text"), + } + }; + assert_eq!(plain_redone, "Prefix replacement suffix"); + } + + #[test] + fn check_spelling_change_all_in_one_undo_step() { + let mut app = app(); + let a = text(&mut app, 50.0, &format!("First {WORD_B} here and {WORD_B} again")); + let b = text(&mut app, 100.0, &format!("Second {WORD_B} line")); + app.run("select.none", json!({})).unwrap(); + + super::open(&mut app).unwrap(); + let ctx = context(); + + app.ui.dialog.as_mut().unwrap().fields.insert("change_to".into(), json!("replaced")); + click(&mut app, &ctx, "Change All"); + + let plain_a = { + let st = app.session.doc().unwrap(); + match &st.doc.node(vectorcraft_doc::NodeId(a)).unwrap().kind { + vectorcraft_doc::NodeKind::Text(t) => t.plain_text(), + _ => panic!("not text"), + } + }; + let plain_b = { + let st = app.session.doc().unwrap(); + match &st.doc.node(vectorcraft_doc::NodeId(b)).unwrap().kind { + vectorcraft_doc::NodeKind::Text(t) => t.plain_text(), + _ => panic!("not text"), + } + }; + assert_eq!(plain_a, "First replaced here and replaced again"); + assert_eq!(plain_b, "Second replaced line"); + + // Single undo reverts all changes made by Change All + app.run("edit.undo", json!({})).unwrap(); + let plain_a_undone = { + let st = app.session.doc().unwrap(); + match &st.doc.node(vectorcraft_doc::NodeId(a)).unwrap().kind { + vectorcraft_doc::NodeKind::Text(t) => t.plain_text(), + _ => panic!("not text"), + } + }; + let plain_b_undone = { + let st = app.session.doc().unwrap(); + match &st.doc.node(vectorcraft_doc::NodeId(b)).unwrap().kind { + vectorcraft_doc::NodeKind::Text(t) => t.plain_text(), + _ => panic!("not text"), + } + }; + assert_eq!(plain_a_undone, format!("First {WORD_B} here and {WORD_B} again")); + assert_eq!(plain_b_undone, format!("Second {WORD_B} line")); + } + + #[test] + fn check_spelling_dictionary_addition() { + let mut app = app(); + forget(&mut app, &[WORD_C]); + text(&mut app, 50.0, &format!("Look at {WORD_C} here")); + + super::open(&mut app).unwrap(); + let ctx = context(); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("not_in_dictionary"), WORD_C); + + click(&mut app, &ctx, "Add to Dictionary"); + + // Verify WORD_C was added to user dictionary + let dict = app.run("text.spelling.dictionary", json!({})).unwrap(); + let words = dict["words"].as_array().unwrap(); + assert!(words.contains(&json!(WORD_C))); + + // Dialog should now have completed because no other unknown words exist + assert!(app.ui.dialog.as_ref().unwrap().bool("done")); + + forget(&mut app, &[WORD_C]); + } + + #[test] + fn check_spelling_ignore_and_ignore_all() { + let mut app = app(); + text(&mut app, 50.0, &format!("{WORD_A} then {WORD_B}")); + + super::open(&mut app).unwrap(); + let ctx = context(); + + // First word is WORD_A + assert_eq!(app.ui.dialog.as_ref().unwrap().str("not_in_dictionary"), WORD_A); + + // Clicking Ignore moves to WORD_B without modifying the document or ignore list + click(&mut app, &ctx, "Ignore"); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("not_in_dictionary"), WORD_B); + assert!(!app.session.doc().unwrap().spelling_ignored.contains(WORD_A)); + + // Clicking Ignore All adds WORD_B to the document's spelling_ignored list + click(&mut app, &ctx, "Ignore All"); + assert!(app.session.doc().unwrap().spelling_ignored.contains(WORD_B)); + assert!(app.ui.dialog.as_ref().unwrap().bool("done")); + } + + #[test] + fn check_spelling_keyboard_navigation() { + let mut app = app(); + let id = text(&mut app, 50.0, &format!("Item {WORD_A} text")); + + super::open(&mut app).unwrap(); + let ctx = context(); + + app.ui.dialog.as_mut().unwrap().fields.insert("change_to".into(), json!("fixed")); + + // Enter triggers Change + key_press(&mut app, &ctx, egui::Key::Enter); + + let plain = { + let st = app.session.doc().unwrap(); + match &st.doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind { + vectorcraft_doc::NodeKind::Text(t) => t.plain_text(), + _ => panic!("not text"), + } + }; + assert_eq!(plain, "Item fixed text"); + assert!(app.ui.dialog.as_ref().unwrap().bool("done")); + + // When done, Enter closes the dialog + key_press(&mut app, &ctx, egui::Key::Enter); + assert!(app.ui.dialog.is_none(), "Enter on done closes dialog"); + + // Enter when change_to is empty and review is unfinished leaves dialog open + text(&mut app, 100.0, &format!("More {WORD_A}")); + super::open(&mut app).unwrap(); + assert!(!app.ui.dialog.as_ref().unwrap().bool("done")); + app.ui.dialog.as_mut().unwrap().fields.insert("change_to".into(), json!("")); + key_press(&mut app, &ctx, egui::Key::Enter); + assert!(app.ui.dialog.is_some(), "Enter with empty change_to leaves dialog open"); + + // Test Escape closes dialog + key_press(&mut app, &ctx, egui::Key::Escape); + assert!(app.ui.dialog.is_none(), "Escape closes dialog"); + } + + #[test] + fn check_spelling_selected_group_finds_nested_text() { + let mut app = app(); + let t = text(&mut app, 50.0, &format!("Grouped {WORD_A} item")); + app.run("select.set", json!({ "ids": [t] })).unwrap(); + let g = app.run("object.group", json!({})).unwrap(); + let group_id = g["id"].as_u64().unwrap(); + app.run("select.set", json!({ "ids": [group_id] })).unwrap(); + + super::open(&mut app).unwrap(); + let d = app.ui.dialog.as_ref().expect("dialog opens"); + assert_eq!(d.str("not_in_dictionary"), WORD_A); + } + + #[test] + fn check_spelling_when_no_misspellings() { + let mut app = app(); + text(&mut app, 50.0, "All correctly spelled English words here"); + + super::open(&mut app).unwrap(); + let d = app.ui.dialog.as_ref().expect("dialog opens"); + assert!(d.bool("done")); + assert!(d.str("context").contains("The spell check is complete.")); + + let ctx = context(); + click(&mut app, &ctx, "Done"); + assert!(app.ui.dialog.is_none()); + } + + #[test] + fn check_spelling_refused_on_document_switch() { + let mut app = app(); + text(&mut app, 50.0, &format!("Text {WORD_A} here")); + + super::open(&mut app).unwrap(); + assert!(app.ui.dialog.is_some()); + + // Create a new document, switching active document UID + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + + let ctx = context(); + frame(&mut app, &ctx, vec![]); + assert!(app.ui.dialog.is_none(), "switching documents closes spelling dialog"); + } + + #[test] + fn test_extract_sentence_context_multiline() { + let text = "First sentence.\nSecond line with teh typo.\nThird line ends."; + let range = text.find("teh").map(|idx| idx..idx + 3).unwrap(); + let (before, word, after) = super::extract_sentence_context(text, range); + assert_eq!(word, "teh"); + assert_eq!(before, "Second line with "); + assert_eq!(after, " typo."); + assert!(!before.contains("First")); + assert!(!after.contains("Third")); + + let text2 = "Far before. Near before.\nLine with teh typo. Near after.\nFar after."; + let range2 = text2.find("teh").map(|idx| idx..idx + 3).unwrap(); + let (b2, w2, a2) = super::extract_sentence_context(text2, range2); + assert_eq!(w2, "teh"); + assert_eq!(b2, "Line with "); + assert_eq!(a2, " typo."); + assert!(!b2.contains("Near before")); + assert!(!a2.contains("Near after")); + } + + #[test] + fn check_spelling_ignores_uneditable_text() { + let mut app = app(); + let editable_id = text(&mut app, 50.0, &format!("Prefix {WORD_A} suffix")); + let locked_id = text(&mut app, 100.0, &format!("Prefix {WORD_B} suffix")); + + // Lock the second text object + app.run("select.set", json!({ "ids": [locked_id] })).unwrap(); + app.run("object.lock", json!({})).unwrap(); + app.run("select.set", json!({ "ids": [] })).unwrap(); + + super::open(&mut app).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(d.str("not_in_dictionary"), WORD_A); + + let rem = d.fields.get("remaining_ids").and_then(serde_json::Value::as_array).unwrap(); + assert!(rem.iter().any(|v| v.as_u64() == Some(editable_id))); + assert!(!rem.iter().any(|v| v.as_u64() == Some(locked_id))); + } + + #[test] + fn check_spelling_change_all_containing_target_word_terminates() { + let mut app = app(); + let t1 = text(&mut app, 50.0, &format!("Prefix {WORD_A} suffix")); + + super::open(&mut app).unwrap(); + assert!(app.ui.dialog.is_some()); + + // Replace WORD_A with something containing WORD_A + let ctx = context(); + let replacement = format!("{WORD_A}abc"); + app.ui.dialog.as_mut().unwrap().fields.insert("change_to".into(), json!(replacement)); + + click(&mut app, &ctx, "Change All"); + // Change All successfully replaced WORD_A; advance moves to the new word + assert_eq!(app.ui.dialog.as_ref().unwrap().str("not_in_dictionary"), format!("{WORD_A}abc")); + + let st = app.session.doc().unwrap(); + let t1_text = match &st.doc.node(vectorcraft_doc::NodeId(t1)).unwrap().kind { + vectorcraft_doc::NodeKind::Text(t) => t.plain_text(), + _ => panic!("not text"), + }; + assert!(t1_text.contains(&format!("{WORD_A}abc"))); + } +} diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index ab11dc5a10..32db24c1c7 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -298,6 +298,13 @@ fn open_view_dialog(app: &mut VectorcraftApp, id: &str, p: &Value) -> bool { } return true; } + // Check Spelling…: dialog to walk through unknown words. + if id == crate::dialogs::check_spelling::COMMAND && p.as_object().is_none_or(|o| o.is_empty()) { + if let Err(e) = crate::dialogs::check_spelling::open(app) { + app.status(e); + } + return true; + } // Edit Views…: the saved views in a list, to rename or delete. if id == "view.saved.edit" && p.as_object().is_none_or(|o| o.is_empty()) { if let Err(e) = crate::dialogs::edit_views::open(app) { diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 994f3e571a..495e606d6c 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -1090,6 +1090,7 @@ fn run_ui_part13(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::dialogs::blend_options::open(app), "ui.livePaintGapOptions" => crate::dialogs::live_paint_gaps::open(app), "ui.perspectivePlane" => crate::dialogs::perspective_plane::open(app, p), + crate::dialogs::check_spelling::COMMAND => crate::dialogs::check_spelling::open(app), _ => return None, }; diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index f08bd87998..d4dda4698b 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -282,7 +282,7 @@ pub fn enabled(app: &VectorcraftApp, id: &str) -> bool { .dialog .as_ref() .is_some_and(|d| crate::dialogs::para_style_options::is_paragraph_dialog(d) && crate::dialogs::para_style_options::can_reset(d)), - "ui.newArtboard" | "artboard.selectAll" => app.session.active().is_some(), + "ui.newArtboard" | "artboard.selectAll" | crate::dialogs::check_spelling::COMMAND => app.session.active().is_some(), "ui.sampleScreenColor" => crate::screen_color::available(app), "ui.newBrush" => app.session.active().is_some(), "ui.brushOptions" => crate::dialogs::brush_options::available(app), diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index b718b24080..ec8ec99018 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -97,7 +97,7 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { Sep, cp("Find and Replace…", "edit.findReplace", json!({"find": "", "replace": "", "matchCase": false, "wholeWord": false})), cp("Find Next", "edit.findNext", json!({"find": ""})), - sub("Spelling", vec![c("Auto Spell Check", "edit.autoSpellCheck"), todos("Check Spelling…", "Cmd+I")]), + sub("Spelling", vec![c("Auto Spell Check", "edit.autoSpellCheck"), c("Check Spelling…", crate::dialogs::check_spelling::COMMAND)]), // Edit › Edit Custom Dictionary…, beside Spelling, on the public Check and correct // spelling page. c("Edit Custom Dictionary…", crate::dialogs::custom_dictionary::COMMAND), diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index c099422957..4c286f1da9 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -168,6 +168,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} toggle a red underline under the words of the document's type its dictionaries don't know (text.spelling.check lists them), kept up to date as the type changes; type with effects isn't underlined → whether Auto Spell Check is on", ), + ( + crate::dialogs::check_spelling::COMMAND, + "Check Spelling…", + "Cmd+I", + "{} open the Check Spelling dialog to walk through unrecognized words with suggestions, ignore, change and dictionary options", + ), ("shortcuts.set", "Set Keyboard Shortcut", "", "{id: command id or tool:, shortcut: \"Cmd+Shift+K\" | \"\" (none) | null (default), force?}"), ("shortcuts.list", "List Keyboard Shortcuts", "", "{query?} → [{id, label, group, shortcut, default, overridden}]"), ("shortcuts.conflicts", "Keyboard Shortcut Conflicts", "", "{} → [{shortcut, ids}]"), diff --git a/docs/gaps.md b/docs/gaps.md index 05483e81d4..1647b6331e 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,10 +1,10 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-15 · **Change:** minor (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-15 · **Change:** minor (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) ## Feature submission evidence -**Feature evidence last updated:** 2026-11-14. +**Feature evidence last updated:** 2026-11-15. Raster rendering fits and preflattens curved stroke outlines more tightly only below four times the raster tolerance, retaining thin-band coverage without changing stroke weight or vector export geometry. Current cached character/object outlines, cropped long strokes, gradient clips and effect rasters share the helper; cropped-region reuse and guarded flattening remain. The unchanged `fractional_curved_strokes_retain_coverage_between_notches` regression covers fractional weights, rotation, phase, opacity and f32-rounded endpoints. This is a quality/cost tradeoff, not a speed claim. Scores and estimates unchanged. @@ -34,6 +34,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 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). | | 2026-11-14 | minor | G12: 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-14 | minor | G5: Weather Icons joins Basic Shapes, UI Frames, Map Markers, Inventory Icons and Skill Icons as a sixth built-in symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow; original procedural vector symbols generated in code, no default 9-slice); estimate decremented (5–15 → 4–14 h). | @@ -457,10 +458,10 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Done:** COLR and SVG glyphs go with type that geometry effects reshape, into Expand Appearance and EMF/WMF export, where the type's outlines used to leave them out; bitmap glyphs (emoji) too, as images that hold their own pixels until a document takes them in; estimate unchanged. +- **Done:** spell check (#4936): engine (`text.spelling.check` and `text.spelling.suggest` on craft-proof); custom dictionary and Ignore All (`text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary`, `ignoreAll`); Auto Spell Check (`edit.autoSpellCheck`) with red wavy underlines and canvas context menu suggestions, Ignore All and Add to Dictionary; Edit › Edit Custom Dictionary…; and modal Check Spelling dialog (Edit › Spelling › Check Spelling…, `ui.checkSpelling`) with sentence context, suggestions list, "Change to" edit, Ignore, Ignore All, Change, Change All, Add to Dictionary, Done, Cancel, and keyboard navigation. Estimate unchanged. - **Missing:** CJK vertical composition (custom mojikumi sets and the Mojikumi Settings dialog, kinsoku settings #633, manual tate-chu-yoko), Middle Eastern - features beyond bidi, digit types, Character Direction and Kashidas (a split caret; the Middle Eastern & South Asian composers are done, #4935), spell check (its engine is done, #4936: `text.spelling.check` and - `text.spelling.suggest` on craft-proof; the custom dictionary and Ignore All commands; Auto Spell Check, `edit.autoSpellCheck`, with a right-click on an underlined word offering its suggestions, Ignore All and Add to Dictionary, and Spelling › Auto Spell Check in the context menu of type; the Edit Custom Dictionary dialog; the Check Spelling dialog remains), + features beyond bidi, digit types, Character Direction and Kashidas (a split caret; the Middle Eastern & South Asian composers are done, #4935), Touch Type, Retype, Snap to Glyph; optional preservation of font sizes during group scaling (#1034 enhancement). Itemized in [type-parity.md](type-parity.md). - **Impact:** professional typography and Japanese/Chinese publishing. diff --git a/docs/roadmap.md b/docs/roadmap.md index 742fef93ed..e1d6af64fd 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # Roadmap: milestones and what's next -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-15 · **Change:** minor (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-15 · **Change:** minor (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). > @@ -162,7 +162,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | 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) | | M5 | Performance | 🟡 background render + caches + MT done; `vectorcraft-cli bench` and `vectorcraft-cli perf` (budget suite); opaque solid-fill knockout paths draw once in hard-edge/supersampled raster export, with analytical-AA compositing unchanged; file format v2 opens 3× faster (50k paths: 722 → 244 ms); raster effects (glows, shadows, blur, feather) no longer force the whole frame single-threaded (filtered offscreen per effect, verified equal to the single-threaded reference); Craquelure/Mosaic Tiles/Stained Glass distance searches optimized with pixel-invariance checks and the `texture_drag_perf` probe (#1257); effect-heavy demos need a clean-machine benchmark; dirty-region rendering, GPU backend spike pending | 15–25 | | M6 | Path operations (Pathfinder, Shape Builder, offset…) | ✅ mostly done (live compound shapes: Make, Alt-click a Shape Mode, member modes, Release, Expand (#4522); single-result Pathfinder names and SVG IDs retained (#1293); Divide open-cutting-path geometry, appearance and history verified (#1307; existing segment cap remains); Simplify preview/counts and rewritten-path component selection verified (#1272; the slider opens at the Auto-Simplify level; a Direct Selection part of a path simplifies on its own); Compound appearance and member fill-rule edits verified (#1197); Boolean precision on almost-horizontal edges fixed and the property tests made deterministic; Shape Builder gap detection, large-offset bug open); 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 | 3–6 | -| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof and the custom dictionary and Ignore All commands and Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary, and Spelling › Auto Spell Check in the context menu of type, and the Edit Custom Dictionary dialog (#4936; the Check Spelling dialog remains); Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Hanging punctuation keeps its published amounts under Glyph Scaling, and Standard burasagari counts a hung line start as room; Fullwidth `!` / `?` keep an upright fallback in vertical type; Hyphenation… and Justification… per paragraph (#2310, #2755), Auto Leading also driving the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs (feature-valued alternates and unencoded glyphs applied in one Undo step while keeping Arabic joining, #5514), OpenType panel (including font-defined Stylistic Sets), Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders, spell check, vertical type pending | 45–60 | +| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, the custom dictionary and Ignore All commands, Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary, Spelling › Auto Spell Check in the context menu of type, the Edit Custom Dictionary dialog, and the modal Check Spelling dialog (Edit › Spelling › Check Spelling…, `Cmd+I`, `ui.checkSpelling`, #4936); Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Hanging punctuation keeps its published amounts under Glyph Scaling, and Standard burasagari counts a hung line start as room; Fullwidth `!` / `?` keep an upright fallback in vertical type; Hyphenation… and Justification… per paragraph (#2310, #2755), Auto Leading also driving the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs (feature-valued alternates and unencoded glyphs applied in one Undo step while keeping Arabic joining, #5514), OpenType panel (including font-defined Stylistic Sets), Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders, vertical type pending | 45–60 | | M8 | Transform & distort (Puppet Warp, Liquify tools, Envelopes, Blends, Perspective Grid) | ✅ done (M8.1–M8.20 on 2026-10-06, fidelity pass): Liquify Tool Options with one shared brush, pen pressure, hold-to-apply, a safe scope and incremental strokes; tool options that last; Puppet Warp rotation, multi-select, Control bar and a rest-shape session that follows Undo; Width tool on compound paths; Envelope dialogs with preview, Reset with Warp/Mesh, full Envelope Options, type/images/symbols/appearance/gradients/patterns distorted on canvas and in every export, warps that keep their frame, Edit Contents, mesh handles and Control bar; Blend Options, anchor-targeted Blend tool, editable spine, keys picked on the canvas, faithful interpolation and knockout; Anchor Point spine conversion/handle editing and selection priority (#2544), with #2425 Shift reshape preserved; Perspective Grid with Define Grid, presets, lock/snap/rulers, widgets, the 1–4 plane switch, movable planes, Perspective Selection scale/copy/perpendicular/Transform Again, and type and symbols truly projected with Edit Text. Left: Anti-Alias and Preserve Shape output, warp-envelope point editing, brush interpolation in blends, Free Transform/Scale/Reflect along a rotated box | 2–4 | | M9 | Live effects (+ 3D & Materials) | 🟡 2D effects done incl. Effect → Pathfinder, Color Adjustments and Document Raster Effects Settings; PDF export warns when the pixel cap lowers raster-effect resolution; Artistic › Colored Pencil, Cutout, Dry Brush, Film Grain, Fresco, Neon Glow, Paint Daubs, Palette Knife, Poster Edges, Rough Pastels, Smudge Stick, Sponge, Underpainting and Watercolor and Sketch › Halftone Pattern, Bas Relief, Charcoal, Conté Crayon, Photocopy, Stamp, Torn Edges and Water Paper done (57/57 Photoshop filters); Revolve with automatic smooth vector shading, default-on circular caps and continuous rims, Extrude & Bevel, Inflate and Rotate with one to ten colored directional lights and four original lighting presets; SVG Filters, remaining raster effects and 3D materials and shadows pending | 81–130 | | M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, six generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, Weather Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, ten generated libraries including Tech Circuit, Ink and Wash, Bristle Brushes and Dry Media, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | @@ -350,6 +350,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | 2026-10-13 | minor | G1: create width points through Width Point Edit with optional adjoining adjustment; command/pointer/history regressions and full CI passed; dialog layout reviewed; scores and hours unchanged | | 2026-10-13 | minor | Corner Radius: a link toggle behind the field in the Properties and Transform panels; off, a live rectangle shows a radius field for each corner (Top Left, Top Right, Bottom Right, Bottom Left), each setting its own corner (`singleCornerRadius` preference); split from #1594; score unchanged (estimated) | | 2026-10-13 | minor | Control transport deadlines (#1726): idle and partial clients and blocked replies release connection slots; parity scores and estimates unchanged. | +| 2026-11-15 | minor | M7: Check Spelling modal dialog (Edit › Spelling › Check Spelling…, `ui.checkSpelling`, #4936); spell check complete; scores and estimates unchanged. | | 2026-10-13 | minor | M12 row: Image Trace has 15 presets and the Ignore Color, Shapes, Auto Grouping and Gradients options (#1574, #1609, #1618, #1627); its speed figure, measured before these, is dropped for the measurements in `image-trace-quality.md` | | 2026-10-13 | minor | The interface is available in Polish (`pl`): menus, panels, dialogs and messages, with one/few/many plurals; AI-drafted, native review pending (#1498); Native documents with a lot of path data (traced or generated art, in layers, symbols or patterns) are saved as compact JSON, about a fifth of the size; small documents stay pretty-printed (#1492); Paste takes a PDF or EPS another app copied as editable vector art: from the macOS pasteboard (with SVG), EPS on Windows beside PDF, and `.eps` files copied in a file manager, with the new command `clipboard.importEps` (#1538, fixes #1499); Opening or placing a file with an image too large to decode says so, and the Links panel shows it on the row (#1540, part of #1479); a multi-artboard `.ai` with notes beside its artboards opens from its editing data, a page's art past its artboard no longer lying over the page before it (#1528); a `.ai` gradient whose stops are listed upwards keeps each midpoint on the stop that starts its part of the ramp (#1530); SVG text on a path follows basic shapes (circle, ellipse, rect, line, polyline, polygon) as their SVG 2 equivalent paths (#1531, fixes #1527); PDFs whose alpha soft masks are drawn as images import with the mask instead of empty art (#1551); EPS and PostScript type set in Type 42 (TrueType) fonts imports at its size instead of 1000 times too large (#1553); PDF and EPS import keep a clipping path whose bounding box covers the page but whose shape doesn't (#1544, fixes #1542); 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); a round corner next to a curved side curves smoothly instead of sticking out of the shape and the Smooth tool smooths only the stretch of path under the drag (#1547, fixes #1512); Join merges the selected anchor points that lie on one another, as after Average, into one anchor (#1582, fixes #1533); Lock Guides also locks the objects made into guides: they can't be selected, moved or deleted (#1543); they are drawn in the guide colour and style of Preferences, and a dragged selection snaps to ruler guides with Smart Guides on (#1583, fixes #1534); Edit › Keyboard Shortcuts lists Edit › Duplicate and the other commands that are in no menu but run without parameters (panel-menu commands such as Break Link to Symbol), so they can be given shortcuts (#1549, #1580, fixes #1539); Raster effects (blur, shadow, glow, grain) drawn after a pattern, radial or freeform gradient fill export at their place and size (#1541, fixes #1536); 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); estimates unchanged | | 2026-10-13 | minor | Direct Selection takes the selected object's anchor where anchors of overlapping objects coincide (#1508); commands and MCP `add_text` report area type that does not fit its frame (#1471), a tab stop in the Tabs panel drags from where the press landed (#1458); M9: 3D and Materials on outlined type and other shapes of many small curves (#1481), Twist 0° to 360° (#1524), twisted walls keep their faces (#1525); print-size images draw, export and crop (#1517), `vectorcraft-cli perf` reports load and memory on Windows (#1502); sliders in dialogs show their rail (#1483), a template layer stays in Preview in Outline view (#1486), French catalog complete again (#1511), a Hungarian message in the informal address (#1474); `graph.setData`'s CSV keeps each value exactly (#1485); estimates unchanged | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 4c8b2d43f8..eee8b9369b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -248,15 +248,15 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Appearance, transparency, graphic styles, masks | 5 | 97% | raster effect reach in preview bounds | 1–2 | estimated; Transform typing, sliders, preview, and undo are covered in `crates/ui-egui/src/panels/tests_appearance.rs` | | 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, painter visibility); materials, light presets, shadows, ray tracing, the rest of 3D Classic (Map Art), Turntable views, textures, map art and shading in 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12); every 3D seam has round joins (2026-11-12, [three-d.md](three-d.md#seams)), score, gaps and hours unchanged | | Type core | 9 | 80% | Auto-leading style resets are implemented; Hyphenation… and Justification… options are done (#2310, #2755), and a paragraph's Auto Leading also sets the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; remaining: Optical Margin Alignment, Middle Eastern features beyond bidi layout (the Middle Eastern & South Asian and Standard composers are done per paragraph, #4935; `.ai`/EPS/PDF files carry no composer), optional group font-size preservation; transformed character controls fixed (#1034), see [type-parity.md](type-parity.md) | 14–19 | estimated; eleven-language pattern hyphenation in both composers, with grapheme and shaping-cluster protection (#4947, `hyphen::tests` and `layout::wrapping_tests`); Sanskrit patterns pending an allowlisted source; recent-font groups in font pickers (#3515); full-name font matches regression-tested (#1258); mixed paragraph alignment indication implemented; headless regressions, full integration CI and visual review pass; localized legacy family-name fallback with loaded/catalog regressions (#2208); Fractional Widths per type object regression-tested; color emoji fonts with bitmap glyphs (`sbix`, `CBDT`) draw and export; threading ports: every selected area type and type on a path shows its in and out ports (empty, arrow, red "+"), and the Selection tool threads from either, the in port into a frame before it, and a double-click on a threaded port breaks the thread there (`threads::tests::break_splits_the_thread_and_the_story_flows_into_the_first_part`, `select::tests::a_double_click_on_a_threaded_port_breaks_the_thread`, `canvas::tests::a_double_click_on_a_threaded_out_port_breaks_the_thread`) (#2572; `select::tests::a_click_on_the_in_port_threads_into_a_frame_before_it`, `text::tests::selected_type_shows_its_ports_in_each_state`, `threads::tests::add_before_threads_the_story_from_the_new_frame_into_the_clicked_one`, live screenshot); the Glyphs panel highlights and scrolls to the character selected with the Type tool (#4908, `panels::glyphs` tests); the OpenType panel lists only `ss01`–`ss20` sets present in the selected font and uses its custom names when supplied; Type-range desktop Copy publishes styled art and keeps font family, size and color on canvas Paste after editing (#5636); paint-only Arabic harakat keep joining with conditional GDEF-mark ownership and Insert Kashidas base-letter paint (`tests::harakat`) | -| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), variable font axes, tab leaders, spell check (engine, custom dictionary and Auto Spell Check with its right-click suggestions and Spelling › Auto Spell Check, and the Edit Custom Dictionary dialog done, #4936; the Check Spelling dialog remains), Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | +| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), variable font axes, tab leaders, Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | | Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons and Weather Icons are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested | -| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), tab leaders, spell check (engine, custom dictionary and Auto Spell Check with its right-click suggestions and Spelling › Auto Spell Check, and the Edit Custom Dictionary dialog done, #4936; the Check Spelling dialog remains), Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | +| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), tab leaders, Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | | Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons and Weather Icons are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested | | Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; simpler contour walk, 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, so Paths is monotone on the code-drawn sweep) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them; Live trace result bounds and selection highlights exclude the retained bitmap except in source-image views (scores/hours unchanged) | | Live vector effects | 5 | 85% | Outline Object, SVG Filters | 4–8 | measured count 49/50 (Pathfinder 13/13 with Trap), depth estimated; Warp Options controls verified by focused checks and original-image review | | 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, original lighting presets, painter visibility), Revolve (Classic) with Angle, Cap, Offset and the Plastic, Diffuse, No Shading and Wireframe surfaces, the Quick Actions › Expand as Wireframes command (#6354), the Render Settings › Wireframe mode on Extrude & Bevel, Revolve, Inflate and Rotate; materials, shadows, ray tracing, the rest of 3D Classic (Map Art), Turntable views, textures, map art and shading in 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12); Revolve (Classic) is covered by the `revolve::classic` tests and `dialogs::revolve::tests::classic_revolve_shows_its_options_and_applies_as_one_step`; Expand as Wireframes is covered by `crates/effects/src/solids/wireframe/tests.rs` and `crates/engine/src/cmd/wireframe/tests.rs`, and Render Settings › Wireframe by `crates/effects/src/solids/wireframe/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` (score, gaps and hours unchanged); every 3D seam has round joins (2026-11-12, [three-d.md](three-d.md#seams)), score, gaps and hours unchanged | -| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (mojikumi), variable font axes, tab leaders, spell check (engine, custom dictionary and Auto Spell Check with its right-click suggestions and Spelling › Auto Spell Check, and the Edit Custom Dictionary dialog done, #4936; the Check Spelling dialog remains), Touch Type, Retype | 20–28 | estimated; No Break keeps marked characters on one line; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | -| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (mojikumi), tab leaders, spell check (engine, custom dictionary and Auto Spell Check with its right-click suggestions and Spelling › Auto Spell Check, and the Edit Custom Dictionary dialog done, #4936; the Check Spelling dialog remains), Touch Type, Retype | 20–28 | estimated; No Break keeps marked characters on one line; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | +| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (mojikumi), variable font axes, tab leaders, Touch Type, Retype | 20–28 | estimated; No Break keeps marked characters on one line; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | +| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (mojikumi), tab leaders, Touch Type, Retype | 20–28 | estimated; No Break keeps marked characters on one line; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | | Raster effects (Effect Gallery) | 4 | 55% | — | — | estimated (raised from 52%: the Effect Gallery's filter thumbnails and in-dialog preview, an original landscape drawing passed through each filter, [Filter Gallery overview](https://helpx.adobe.com/photoshop/desktop/effects-filters/get-started-with-filters/filter-gallery.html), `dialogs::effect_gallery::tests::gallery_shows_thumbnails_and_an_in_dialog_preview`; the gallery itself shipped in #2883, six categories, per-filter settings, ordered stack, live canvas preview, one undo step, `stack_ok_is_one_undo_step`, `stack_preview_is_one_interaction`); measured count 57/57 (Artistic complete with Colored Pencil, Fresco, Paint Daubs, Palette Knife, Rough Pastels and Underpainting; Sketch complete with Torn Edges and Conté Crayon, `pixel::tests_sketch::conte_crayon_*`); texture redraw distances optimized (#1257), pixels verified; the score stays under 100% because the filters are original approximations; depth estimated | | Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons and Weather Icons are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) and on-canvas 9-slice guides (#5280) are done | 4–7 | estimated | | Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; large images trace with a warning; Auto Color keeps rare distinct colours) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them | @@ -517,10 +517,10 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale) | Appearance, transparency, graphic styles, masks | 5 | 98% | Graphic Styles list fills a taller panel above its footer (#2992; scores and estimates unchanged); raster effect reach in preview bounds (flattener presets apply in PDF, EPS and print) | 1–2 | | Live vector effects | 5 | 85% | Outline Object, Pathfinder Hard/Soft Mix and Trap (since done: #3061, #3063, #3785), SVG Filters, Transform Patterns and Scale Strokes & Effects on a fill's or stroke's own Transform effect | 6–10 | | 3D and Materials | 4 | ~25% | Initial Revolve, Extrude & Bevel, Inflate and Rotate, with simple lighting; materials, light presets, shadows, ray tracing, Rotate (Classic), Map Art and more complete visibility remain | 25–45 | -| Type advanced | 4 | 50% | CJK composition for vertical type (ruby, mojikumi beyond Line-end Punctuation Half Width — the other sets (and their paragraph-start bracket and indent rules), custom kinsoku sets (beyond Hard, Soft and None) and the Mojikumi Settings dialog —, manual tate-chu-yoko), tab leaders, spell check (its engine, custom dictionary commands, the Edit Custom Dictionary dialog and Auto Spell Check are done, #4936: the Check Spelling dialog remains; a right-click on an underlined word offers its suggestions, Ignore All and Add to Dictionary, and a right-click on type has Spelling › Auto Spell Check), 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 advanced | 4 | 50% | CJK composition for vertical type (ruby, mojikumi beyond Line-end Punctuation Half Width — the other sets (and their paragraph-start bracket and indent rules), custom kinsoku sets (beyond Hard, Soft and None) and the Mojikumi Settings dialog —, manual tate-chu-yoko), 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 | | 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, spell check (its engine, custom dictionary commands, the Edit Custom Dictionary dialog and Auto Spell Check are done, #4936: the Check Spelling dialog remains; a right-click on an underlined word offers its suggestions, Ignore All and Add to Dictionary, and a right-click on type has Spelling › Auto Spell Check), 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 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 | | 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 | @@ -2519,7 +2519,9 @@ The right-click followed (2026-11-10), as the same page's "Correct spelling erro The page's other way to turn Auto Spell Check on followed (2026-11-10): right-click the text and choose Spelling › Auto Spell Check (#4936). A right-click on type (which selects it) has a Spelling submenu with Auto Spell Check, which runs `edit.autoSpellCheck` as Edit › Spelling does. The context menu draws no check marks, its toggles saying what they do (Show Rulers, Hide Guides), but a submenu that holds only toggles shows them, so Auto Spell Check is checked while it is on; other art has no Spelling submenu (`right_click_on_type_turns_auto_spell_check_on_and_off`). -Edit Custom Dictionary followed (2026-11-10), as the same page's "Edit the custom dictionary" describes it: Edit › Edit Custom Dictionary…, then enter a word in the Entry field and Add it, select a word and Delete it, or select a word, edit it in the Entry field and Change it, then Done (#4936). The dialog lists the custom dictionary's words (`text.spelling.dictionary`); picking one puts it in the Entry field. Add and Change take one word that isn't listed yet, kept in lower case as the dictionary keeps it, and Delete and Change need a word picked. Nothing changes until Done, which deletes and adds the words that differ (`text.spelling.removeWord`, `text.spelling.addWord`); Cancel leaves the dictionary as it was (`ui-egui/src/dialogs/custom_dictionary.rs`). The Check Spelling dialog remains. +Edit Custom Dictionary followed (2026-11-10), as the same page's "Edit the custom dictionary" describes it: Edit › Edit Custom Dictionary…, then enter a word in the Entry field and Add it, select a word and Delete it, or select a word, edit it in the Entry field and Change it, then Done (#4936). The dialog lists the custom dictionary's words (`text.spelling.dictionary`); picking one puts it in the Entry field. Add and Change take one word that isn't listed yet, kept in lower case as the dictionary keeps it, and Delete and Change need a word picked. Nothing changes until Done, which deletes and adds the words that differ (`text.spelling.removeWord`, `text.spelling.addWord`); Cancel leaves the dictionary as it was (`ui-egui/src/dialogs/custom_dictionary.rs`). + +Check Spelling followed (2026-11-15): Edit › Spelling › Check Spelling… (`Cmd+I`, `ui.checkSpelling`) opens a modal dialog displaying the unrecognized word in its sentence context ("Not in Dictionary"), a list of suggestions with selection or double-click to replace into the "Change to" field, and action buttons: "Ignore" (skips current word), "Ignore All" (skips word in active document, `text.spelling.ignoreAll`), "Change" (replaces word in 1-step undo, `text.editRange`), "Change All" (replaces all occurrences in a single undo step via `command.batch`), "Add to Dictionary" (`text.spelling.addWord`), and "Done" / "Cancel". Supports keyboard navigation (Tab between controls, Enter to Change or Done, Escape to close) (#4936; `crates/ui-egui/src/dialogs/check_spelling.rs`). Spell check is complete. ## Control bar: Paragraph section while type is selected (2026-11-06) @@ -2598,6 +2600,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | 2026-11-11 | minor | Bundled content: built-in Energy Beams brush library (Laser Bolt, Plasma Arc, Charge Wave, Spark Trail); brush libraries evidence updated; ~44% → ~46%; more built-in brush libraries remain. | | 2026-11-11 | minor | Bundled content: built-in Skill Icons symbol library (Attack, Defend, Heal, Buff, Ult); symbol libraries evidence updated; ~42% → ~44%; more built-in symbol libraries remain. | | 2026-11-11 | minor | Bundled content: built-in Status Effects graphic style library; style libraries evidence updated; ~40% → ~42%; MCP Symbol libraries list UI Frames and Map Markers; more built-in graphic-style libraries remain. | +| 2026-11-15 | minor | Type advanced: the Check Spelling dialog (Edit › Spelling › Check Spelling…, `Cmd+I`, `ui.checkSpelling`, #4936); evidence added; spell check complete; scores and hours unchanged. | | 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). | diff --git a/docs/type-parity.md b/docs/type-parity.md index 5b332efd5e..e6a74374f9 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -1,6 +1,6 @@ # Type parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-14 · **Change:** minor (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; `.ai` and EPS files do not carry the choice; scores and estimates unchanged; previously minor: kerning at the Type tool's caret at the start of a line sets the space before the character after it, #5111; previously minor: type's strokes in an envelope paint along its bent glyph outlines at their own weight, Distort Appearance on or off, as users' `.ai` files draw them, #6644; previously minor: a centred or right-aligned line of tracked type is aligned without the tracking after its last character, as the page of users' `.ai` files aligns it, #6610; previously minor: tracking and manual kerning in horizontally scaled type are thousandths of the em as the Horizontal Scale draws it, as the page of users' `.ai` files spaces such type; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: Direct Selection shows and drags the direction handles of type on a path's path, #3565; 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: Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas base-letter paint; scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: right-aligned area type sets the text after a line's last tab against the right edge; a soft return in justified type no longer keeps its line from being justified; 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) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-15 · **Change:** minor (modal Check Spelling dialog: Edit › Spelling › Check Spelling…, `ui.checkSpelling`, #4936; spell check complete; previously minor: 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; `.ai` and EPS files do not carry the choice; scores and estimates unchanged; previously minor: kerning at the Type tool's caret at the start of a line sets the space before the character after it, #5111; previously minor: type's strokes in an envelope paint along its bent glyph outlines at their own weight, Distort Appearance on or off, as users' `.ai` files draw them, #6644; previously minor: a centred or right-aligned line of tracked type is aligned without the tracking after its last character, as the page of users' `.ai` files aligns it, #6610; previously minor: tracking and manual kerning in horizontally scaled type are thousandths of the em as the Horizontal Scale draws it, as the page of users' `.ai` files spaces such type; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: Direct Selection shows and drags the direction handles of type on a path's path, #3565; 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: Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas base-letter paint; scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: right-aligned area type sets the text after a line's last tab against the right edge; a soft return in justified type no longer keeps its line from being justified; 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) · **Target:** Adobe Illustrator 2026 (30.x) Glyphs review (#6084): a positional variant no supported feature draws is accepted as a glyph choice. Entire Font respects the selection's variable axes and font version; the default cell can reset an unlisted choice without GSUB alternates. Contextual choices use the supplying face, including fallback. Feature-only boundaries preserve ligature clusters and Arabic mark attachment. Encoded characters insert unchanged except Arabic presentation forms with a joining base letter; normalization reports success only after insertion succeeds. Latest follow-up regressions await runtime verification. Scores and estimates unchanged. @@ -51,7 +51,7 @@ against Illustrator's public documentation; **estimated** unless noted. | 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; type on a path doesn't use them. 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` | -| Spell check (Check Spelling, Auto Spell Check, custom dictionary) | partial | 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 Check Spelling dialog remains. 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). | +| 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 | | Caret: the arrows and Delete step over whole clusters (Thai consonant with its marks, combining accents, emoji); Backspace removes one character | done | in text with right-to-left characters the arrows move in visual order and stop on both sides of a character drawn with no width, such as a zero width non-joiner | @@ -88,6 +88,7 @@ Character Styles menu New/Redefine and footer New capture the first selected cha | Date | Change | Summary | |---|---|---| +| 2026-11-15 | minor | Check Spelling dialog (#4936): Edit › Spelling › Check Spelling… (`Cmd+I`, `ui.checkSpelling`) modal dialog with 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-14 | minor | Paragraph composers (#4935): `text.setFormat {composer}` and paragraph styles take `singleLine` and `everyLine` (the Middle Eastern & South Asian composers, what all type used and the default) and `standardSingleLine` and `standardEveryLine`, which break lines the same way and set a complex script (Indic, Arabic, Hebrew) glyph by glyph as the font maps its characters, with no conjuncts, reordering, marks placed or joining forms. The choice is per paragraph, saved in the native file only when it is not Every-line, and not written to `.ai`, EPS or PDF files, whose composer setting this app has no recorded format for. Scores and estimates unchanged. Tests `tests::composers`. | | 2026-11-12 | minor | Glyphs review (#6084): validate contextual glyph choices against their supplying face, including fallback and overflow; keep feature-only boundaries inside ligatures and Arabic mark clusters while retaining drawing-attribute splits; preserve insertion failures instead of reporting normalization success. Deterministic engine, shaping and panel regression sources added; ligature range assertions use the fixture's unencoded glyph identity. Runtime proof pending. Scores and estimates unchanged. | | 2026-11-12 | minor | Glyphs review (#6084): Entire Font resolves the selected font's version and variable axes; the default cell remains available to reset an unlisted choice with no listed alternates. Character insertion normalizes only Arabic presentation forms, preserving ordinary characters whose glyphs share Arabic substitution provenance. Add deterministic panel apply/reset/Undo regressions without OS-font dependencies. Scores and estimates unchanged. | From d089df0ab51719ce5dd9f78702b1f03cb432394e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 08:28:08 -0800 Subject: [PATCH 23/31] Recolor Artwork: Find tries every lighter tint down to 1% When a selected row listed the twenty tints from 25% through 6% of a color of an unselected row, Find left that color undimmed although its 5% tint was free. The search now tries each tint a percent apart from 25% down to 1% before leaving a color as it is. --- crates/ui-egui/src/dialogs/recolor.rs | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index e15256b693..238205216e 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -599,8 +599,9 @@ fn apply_params(d: &Dialog) -> Value { /// aren't selected shows while it is on (VectorCraft's own amount: [`Color::tinted`]). const FIND: &str = "findColors"; const FIND_DIM: f32 = 0.25; -/// The lighter tints, a percent apart, tried when a dimmed color is one a selected row lists. -const FIND_TRIES: usize = 20; +/// The tints tried when a dimmed color is one a selected row lists: [`FIND_DIM`] and each lighter +/// one a percent apart, down to 1%. +const FIND_TRIES: usize = 25; /// The colors of the art that the rows leave out (Preserve White, Black and Grays), as /// `recolor.reduce` returned them. const PRESERVED: &str = "__preserved"; @@ -2299,6 +2300,15 @@ mod tests { let p = find_params(&d).unwrap(); let to = color_value(&p["commands"][0]["params"]["map"]["rgb 0 0 255"]).unwrap(); assert_eq!(to.to_hex(), "#c2c2ff", "{p}"); + // When the twenty tints from 25% through 6% are all listed, the 5% tint is taken. + let blue = color_value(&json!("rgb 0 0 255")).unwrap(); + let tint = |n: usize| key(&blue.tinted(FIND_DIM - n as f32 * 0.01)); + let mut from = vec![json!("rgb 255 0 0")]; + from.extend((0..20).map(tint)); + rs[0]["from"] = json!(from); + d.fields.insert("rows".into(), json!(rs)); + let p = find_params(&d).unwrap(); + assert_eq!(p["commands"][0]["params"]["map"]["rgb 0 0 255"], tint(20), "{p}"); // Another key of the same hex matches only itself, so the tint is kept. rs[0]["from"] = json!(["rgb 255 0 0", "rgb 191 191 255"]); d.fields.insert("rows".into(), json!(rs)); From e837dae7b3bbacf96d4ce72810012c45b09fb95d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 08:30:11 -0800 Subject: [PATCH 24/31] Export for Screens: artboard name fields close on a first-frame key and commit when another opens Escape or Enter pressed in the first frame that draws an artboard's name field was dropped: the field asked for focus and skipped its key checks, while the dialog kept itself open for the field. The field now ends the edit on either key in that frame too. A double-click on an earlier artboard's name, with both clicks in one frame, replaced the edit of a later artboard before that artboard's field was drawn, so the name typed there was lost. The typed name now goes to its artboard before the new field opens. Follows #7695. --- .../ui-egui/src/dialogs/export_for_screens.rs | 13 +++- crates/ui-egui/src/dialogs/tests_screens.rs | 75 +++++++++++++++++++ 2 files changed, 84 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dialogs/export_for_screens.rs b/crates/ui-egui/src/dialogs/export_for_screens.rs index 5b28affa2f..96b5f63c27 100644 --- a/crates/ui-egui/src/dialogs/export_for_screens.rs +++ b/crates/ui-egui/src/dialogs/export_for_screens.rs @@ -638,15 +638,16 @@ fn edit_artboard_name( widgets::reject_dialog_commit(ui.ctx()); } let response = ui.put(rect, egui::TextEdit::singleline(text).id(field).font(egui::FontId::proportional(11.0)).desired_width(rect.width())); - if *focus { - widgets::focus_field(ui, field, text); - *focus = false; - } else if cancel || enter || response.lost_focus() { + // Escape and Enter also end the edit in the first frame that draws the field. + if cancel || enter || (!*focus && response.lost_focus()) { if !cancel { *rename = Some((*b, std::mem::take(text))); } response.surrender_focus(); *editing = None; + } else if *focus { + widgets::focus_field(ui, field, text); + *focus = false; } (false, true) } else { @@ -654,6 +655,10 @@ fn edit_artboard_name( if let Some(board) = board && response.double_clicked() { + // A name still typed for an artboard whose field this frame has not drawn yet is kept. + if let Some((b, text, _)) = editing.take() { + *rename = Some((b, text)); + } *editing = Some((board, name.into(), true)); ui.ctx().request_repaint(); // If both releases arrived this frame, the first click did not toggle the row. diff --git a/crates/ui-egui/src/dialogs/tests_screens.rs b/crates/ui-egui/src/dialogs/tests_screens.rs index e26c82de60..b99405ecfe 100644 --- a/crates/ui-egui/src/dialogs/tests_screens.rs +++ b/crates/ui-egui/src/dialogs/tests_screens.rs @@ -1547,3 +1547,78 @@ fn an_artboard_name_stays_with_its_document() { assert_eq!(names(&app, 1), ["Artboard 1", "Artboard 2"]); assert!(log.borrow().is_empty(), "renaming must not export"); } + +/// Escape or Enter in the first frame that draws an artboard's name field closes the field, and +/// the dialog stays open. +#[test] +fn a_key_in_the_first_frame_of_an_artboard_name_closes_it() { + for view in ["grid", "list"] { + for key in [egui::Key::Escape, egui::Key::Enter] { + let (mut app, log) = app(2, true); + open(&mut app); + set(&mut app, "view", json!(view)); + let mut h = ScreensFrame::new(); + let out = h.settle(&mut app); + let at = screen_text_at(&out, "1 Artboard 1"); + h.frame(&mut app, vec![egui::Event::PointerMoved(at)]); + for pressed in [true, false, true, false] { + h.frame( + &mut app, + vec![egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }], + ); + } + // The double-click opened the field in the last frame; this frame draws it first. + h.time += 0.1; + let input = egui::RawInput { + events: vec![egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }], + time: Some(h.time), + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1100.0, 900.0))), + ..Default::default() + }; + let mut out = h.ctx.run_ui(input, |ui| { + crate::shortcuts::handle(&mut app, ui.ctx()); + super::show(&mut app, ui.ctx()); + }); + out.textures_delta.clear(); + h.settle(&mut app); + assert!(!h.ctx.egui_wants_keyboard_input(), "{view}, {key:?}: the field closes"); + assert_eq!(kind(&app), Some(export_for_screens::KIND), "{view}, {key:?}"); + assert_eq!(app.session.active().unwrap().doc.artboards[0].name, "Artboard 1", "{view}, {key:?}"); + assert!(log.borrow().is_empty(), "{view}, {key:?}: the key must not export"); + } + } +} + +/// A double-click on an earlier artboard's name, both clicks in one frame, renames the artboard +/// whose name was being typed before it opens the new field. +#[test] +fn double_clicking_another_artboard_name_keeps_the_typed_name() { + for view in ["grid", "list"] { + let (mut app, log) = app(2, true); + open(&mut app); + set(&mut app, "view", json!(view)); + let mut h = ScreensFrame::new(); + let before = field(&app, "boards"); + let double_click = |h: &mut ScreensFrame, app: &mut VectorcraftApp, at: egui::Pos2| { + h.frame(app, vec![egui::Event::PointerMoved(at)]); + let events = [true, false, true, false] + .into_iter() + .map(|pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }) + .collect(); + h.frame(app, events); + h.settle(app); + }; + let out = h.settle(&mut app); + let first = screen_text_at(&out, "1 Artboard 1"); + double_click(&mut h, &mut app, screen_text_at(&out, "2 Artboard 2")); + assert!(h.ctx.egui_wants_keyboard_input(), "{view}: the double-click opens the name"); + h.frame(&mut app, vec![egui::Event::Text("Typed".into())]); + h.time += 1.0; + double_click(&mut h, &mut app, first); + let names: Vec = app.session.active().unwrap().doc.artboards.iter().map(|a| a.name.clone()).collect(); + assert_eq!(names, ["Artboard 1", "Typed"], "{view}"); + assert!(h.ctx.egui_wants_keyboard_input(), "{view}: the second double-click opens its name"); + assert_eq!(field(&app, "boards"), before, "{view}"); + assert!(log.borrow().is_empty(), "{view}: renaming must not export"); + } +} From 9382b0ab0ac5ff3549ecb751e2a90e66d5cdbfa4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 08:30:35 -0800 Subject: [PATCH 25/31] Place: an import dialog a drop opened places in the document the file was dropped on A file dropped on a canvas that asks for import options (a layered PSD, a PDF with several pages, a DXF drawing, a text file) kept only its placement params in the dialog. The dialog's OK then placed the file in whichever document was active at that moment, and placed it even when the dropped-on document had been reverted since. The drop now carries its target document and revert count in the place params, as the place cursor's import options carry their token. Placing checks them on the drop and again on the dialog's OK: the file goes to the document it was dropped on, which becomes active again, and is not placed when that document has been closed or reverted. The dialog then stays open and shows the reason. The checks drop_files ran itself now run in that one place. --- crates/ui-egui/src/dialogs/psd_import.rs | 43 +++++++++++++++++++++++ crates/ui-egui/src/dialogs/text_import.rs | 21 +++++++++++ crates/ui-egui/src/place.rs | 41 +++++++++++++-------- 3 files changed, 91 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/dialogs/psd_import.rs b/crates/ui-egui/src/dialogs/psd_import.rs index 75fd0e0f11..950b15c763 100644 --- a/crates/ui-egui/src/dialogs/psd_import.rs +++ b/crates/ui-egui/src/dialogs/psd_import.rs @@ -322,6 +322,49 @@ mod tests { assert!(matches!(st.doc.node(id).unwrap().kind, NodeKind::Image(_))); } + /// The OK of the dialog a drop on a canvas opened places in the document the file was dropped + /// on, made active again, even when another document became active meanwhile; it doesn't + /// place when that document has been reverted or closed since. + #[test] + fn a_dropped_files_ok_places_in_the_document_it_was_dropped_on() { + use crate::place::{DropAt, DropTarget}; + let psd = layered(); + let mut app = app(); + for _ in 0..2 { + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + } + let drop_on_first = |app: &mut VectorcraftApp| { + app.session.set_active(0); + let st = app.session.doc().unwrap(); + let target = DropTarget::Place(DropAt { doc: st.uid, reverts: st.reverts, at: vectorcraft_geom::Point::new(50.0, 50.0), embed: true }); + crate::place::drop_files(app, vec![(target, ("poster.psd".into(), None, psd.clone()))]); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND)); + // Another document becomes active while the dialog is open. + app.session.set_active(1); + }; + let objects = + |app: &VectorcraftApp, i: usize| app.session.documents()[i].doc.layers.iter().map(|l| l.children().map_or(0, Vec::len)).sum::(); + drop_on_first(&mut app); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!((objects(&app, 0), objects(&app, 1)), (1, 0), "placed in the document it was dropped on"); + assert_eq!(app.session.active_index(), Some(0), "which is active again"); + // Reverted meanwhile: the dialog stays open with the reason, and nothing is placed. + drop_on_first(&mut app); + let first = app.session.documents()[0].uid; + app.session.document_mut(first).unwrap().reverts += 1; + let e = super::super::confirm(&mut app).unwrap_err(); + assert!(e.contains("was reverted"), "{e}"); + assert_eq!((objects(&app, 0), objects(&app, 1)), (1, 0)); + // Closed meanwhile. + app.ui.dialog = None; + drop_on_first(&mut app); + app.session.close_document(0); + let e = super::super::confirm(&mut app).unwrap_err(); + assert!(e.contains("was closed"), "{e}"); + assert_eq!(objects(&app, 0), 0); + } + #[test] fn several_files_placed_without_link_take_the_last_choices() { let dir = std::env::temp_dir().join(format!("vc-psd-import-queue-{}", std::process::id())); diff --git a/crates/ui-egui/src/dialogs/text_import.rs b/crates/ui-egui/src/dialogs/text_import.rs index a52e9f47fe..99128cc321 100644 --- a/crates/ui-egui/src/dialogs/text_import.rs +++ b/crates/ui-egui/src/dialogs/text_import.rs @@ -165,4 +165,25 @@ mod tests { assert_eq!(t.plain_text(), "one two\nthree", "one paragraph per block"); assert_eq!(st.history.undo.len(), 1); } + + /// 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] + fn a_dropped_text_files_ok_places_in_the_document_it_was_dropped_on() { + use crate::place::{DropAt, DropTarget}; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + for _ in 0..2 { + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + } + app.session.set_active(0); + let st = app.session.doc().unwrap(); + let target = DropTarget::Place(DropAt { doc: st.uid, reverts: st.reverts, at: vectorcraft_geom::Point::new(100.0, 100.0), embed: true }); + crate::place::drop_files(&mut app, vec![(target, ("notes.txt".into(), None, b"one".to_vec()))]); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND)); + app.session.set_active(1); + super::super::confirm(&mut app).unwrap(); + let objects = |i: usize| app.session.documents()[i].doc.layers.iter().map(|l| l.children().map_or(0, Vec::len)).sum::(); + assert_eq!((objects(0), objects(1)), (1, 0), "placed in the document it was dropped on"); + assert_eq!(app.session.active_index(), Some(0)); + } } diff --git a/crates/ui-egui/src/place.rs b/crates/ui-egui/src/place.rs index 80c2464f62..0ad9fbc3ed 100644 --- a/crates/ui-egui/src/place.rs +++ b/crates/ui-egui/src/place.rs @@ -88,6 +88,11 @@ pub struct PlaceState { /// file is placed. const ASKED: &str = "__placeCursorAsk"; +/// The `file.place` param that keeps where a file dropped on a canvas goes (`{doc, reverts}`, as +/// [`DropAt`]) through the import options dialog the drop opened, so its OK places the file in that +/// document; hidden from the dialog's fields and removed before the file is placed. +const DROPPED: &str = "__dropTarget"; + /// A place cursor thumbnail: decoded when the cursor is loaded, uploaded when first drawn (and /// again in a new graphics context). struct Thumb { @@ -149,7 +154,23 @@ enum Read { ForUser { dropped: bool }, } -fn place_file(app: &mut VectorcraftApp, p: &Value, read: Read) -> Result { +fn place_file(app: &mut VectorcraftApp, p: &Value, mut read: Read) -> Result { + // A file dropped on a canvas, and the OK of the import options its drop asked for, go to the + // document it was dropped on, which becomes active again; not when that document has closed or + // been reverted since. + if let Some(target) = p.get(DROPPED) { + let field = |k: &str| target.get(k).and_then(Value::as_u64); + let Some(i) = app.session.documents().iter().position(|st| Some(st.uid) == field("doc")) else { + return Err("the document it was dropped on was closed".into()); + }; + if app.session.documents().get(i).is_some_and(|st| Some(st.reverts) != field("reverts")) { + return Err("the document it was dropped on was reverted".into()); + } + app.session.set_active(i); + if let Read::ForUser { .. } = read { + read = Read::ForUser { dropped: true }; + } + } // The OK of import options a click of the place cursor asked for places within the roots the // cursor was loaded in. A caller with roots of its own places within those. let Some(token) = p.get(ASKED) else { return place_file_in(app, p, read) }; @@ -224,6 +245,7 @@ fn place_file_in(app: &mut VectorcraftApp, p: &Value, read: Read) -> Result { @@ -619,29 +641,20 @@ pub type DropFile = (String, Option, Vec); /// Files dropped on the window, each placed on a canvas or opened (and added to Open Recent /// Files) as its target says: the placed ones first, so the last document opened is the one /// shown. A file for a canvas goes to the document it was dropped on, which becomes active again; -/// it isn't placed when that document has closed or been reverted since. +/// it isn't placed when that document has closed or been reverted since, and neither is it by the +/// OK of an import options dialog the drop opened ([`DROPPED`]). pub fn drop_files(app: &mut VectorcraftApp, mut files: Vec<(DropTarget, DropFile)>) { files.sort_by_key(|(target, _)| *target == DropTarget::Open); for (target, (name, path, bytes)) in files { - if let DropTarget::Place(d) = target { - let Some(i) = app.session.documents().iter().position(|st| st.uid == d.doc) else { - app.status(format!("Couldn't place {name}: the document it was dropped on was closed")); - continue; - }; - if app.session.documents().get(i).is_some_and(|st| st.reverts != d.reverts) { - app.status(format!("Couldn't place {name}: the document it was dropped on was reverted")); - continue; - } - app.session.set_active(i); - } let r = match target { - DropTarget::Place(DropAt { at, embed, .. }) => { + DropTarget::Place(DropAt { doc, reverts, at, embed }) => { let mut p = match &path { Some(path) => json!({ "path": path }), None => json!({ "name": name, "dataBase64": vectorcraft_format::base64_encode(&bytes) }), }; p["at"] = json!([at.x, at.y]); p["link"] = json!(!embed); + p[DROPPED] = json!({ "doc": doc, "reverts": reverts }); place_file(app, &p, Read::ForUser { dropped: true }).map(|_| ()) } DropTarget::Open => match path.as_deref() { From 1df834568d3ddaf94abede201e4c391b4fca3863 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 08:31:19 -0800 Subject: [PATCH 26/31] Variables: Variable Options fills the field left unset after the Variable changes Setting the Variable field through ui.dialog.set clears Name and Kind until a frame fills them from the chosen variable. Setting Name or Kind alone before that frame marked the fields as filled, so the other field stayed null and the dialog showed "null" for Name or a blank Kind. OK already read a null field as the variable's own value, so only the displayed field was wrong. A frame now fills every field when the chosen variable changes, and after that fills only a field that is still null, keeping a field that was set. --- crates/ui-egui/src/dialogs/variables.rs | 64 +++++++++++++++++++++---- 1 file changed, 56 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/dialogs/variables.rs b/crates/ui-egui/src/dialogs/variables.rs index dad6e3f43b..8151df4e33 100644 --- a/crates/ui-egui/src/dialogs/variables.rs +++ b/crates/ui-egui/src/dialogs/variables.rs @@ -140,11 +140,18 @@ pub fn open(app: &mut VectorcraftApp, id: &str, preselect: Option<&str>) -> bool /// Variable Options' Name and Kind fields for the variable `name`: its name, and its kind as /// `variable.rename` takes it (empty for a variable of unknown kind, which OK leaves as it is). -/// [`FILLED`] records which variable they were filled for. +/// [`FILLED`] records which variable they were filled for. Once they were, only a field that is +/// still unset (null, as setting the Variable field leaves it) is filled. fn fill_variable_options(vars: &Variables, name: &str, fields: &mut serde_json::Map) { - let kind = vars.variable(name).map(|v| v.kind).filter(|k| *k != VariableKind::Unknown).map(VariableKind::label).unwrap_or_default(); - fields.insert("newName".into(), json!(name)); - fields.insert("kind".into(), json!(kind)); + let refill = fields.get(FILLED).and_then(Value::as_str) != Some(name); + let unset = |fields: &serde_json::Map, key: &str| matches!(fields.get(key), None | Some(Value::Null)); + if refill || unset(fields, "newName") { + fields.insert("newName".into(), json!(name)); + } + if refill || unset(fields, "kind") { + let kind = vars.variable(name).map(|v| v.kind).filter(|k| *k != VariableKind::Unknown).map(VariableKind::label).unwrap_or_default(); + fields.insert("kind".into(), json!(kind)); + } fields.insert(FILLED.into(), json!(name)); } @@ -212,9 +219,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { label(ui, tl!("Variable")); dropdown(ui, d, "variable", &variable_names, 220.0); let picked = d.str("variable"); - if picked != d.str(FILLED) { - fill_variable_options(vars, &picked, &mut d.fields); - } + fill_variable_options(vars, &picked, &mut d.fields); ui.end_row(); label(ui, tl!("Name")); text(ui, d, "newName", 220.0); @@ -305,7 +310,8 @@ fn set_text(d: &mut Dialog, key: &str, s: String) { /// /// In Variable Options, setting the Variable field clears Name and Kind, which OK reads as the /// variable's own name and kind, until a frame fills them from it; setting Name or Kind ties them -/// to the variable already named, so no frame fills them over. +/// to the variable already named, so no frame fills them over, and a frame fills only the one +/// still cleared. pub(super) fn note_set(d: &mut Dialog, field: &str) { d.fields.remove(&empty_marker(field)); if d.str("__command") == "variable.rename" { @@ -669,4 +675,46 @@ mod tests { let d = app.ui.dialog.as_ref().unwrap(); assert_eq!((d.str("newName"), d.str("kind")), ("Flag".to_string(), "visibility".to_string())); } + + #[test] + fn variable_options_fills_the_field_left_unset_after_the_variable_changes() { + let mut app = app_with_variables(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let frame = |app: &mut VectorcraftApp| { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| crate::dialogs::show(app, ui.ctx())); + out.textures_delta.clear(); + }; + + // Kind alone: Name shows the newly picked variable's name. + open(&mut app, "variable.rename", Some("Title")); + { + let d = app.ui.dialog.as_mut().unwrap(); + crate::dialogs::set_field(d, "variable".into(), json!("Badge")); + crate::dialogs::set_field(d, "kind".into(), json!("text")); + } + frame(&mut app); + { + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.str("newName"), d.str("kind")), ("Badge".to_string(), "text".to_string())); + } + + // Name alone: Kind shows the newly picked variable's kind. + open(&mut app, "variable.rename", Some("Title")); + { + let d = app.ui.dialog.as_mut().unwrap(); + crate::dialogs::set_field(d, "variable".into(), json!("Badge")); + crate::dialogs::set_field(d, "newName".into(), json!("Flag")); + } + frame(&mut app); + { + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.str("newName"), d.str("kind")), ("Flag".to_string(), "visibility".to_string())); + } + + // OK still renames Badge and keeps its kind. + crate::dialogs::confirm(&mut app).unwrap(); + let kind_of = |name: &str| app.session.active().and_then(|st| st.doc.variables.variable(name).map(|v| v.kind)); + assert_eq!((kind_of("Flag"), kind_of("Badge")), (Some(VariableKind::Visibility), None)); + } } From 133e54b970acebd849bb858fffacdde892921a0d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 08:34:35 -0800 Subject: [PATCH 27/31] Gradients: a gradient spanning the selection on a lower stroke fits the box that stroke paints With span: "selection", paint.setStroke placed the gradient on the union of each target's topmost stroke box, also when `item` named a lower stroke, including an aligned row of a graph design's art. With a 40 pt lower stroke under a 1 pt topmost one, the gradient reached 0.5 pt past the objects instead of 20 pt. Each target's box is now that of the row it edits. --- crates/engine/src/cmd/paint.rs | 25 ++++++++++++++++--------- crates/engine/src/tests/gradspan.rs | 22 ++++++++++++++++++++++ 2 files changed, 38 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 6370f8dbf9..61b734b4d4 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -555,9 +555,15 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool) let ids = super::graph::paint_targets(&s.doc()?.doc, &selected); let of = super::appearance::reference_of(s, p, item, cmd)?; let paint = if span { - // With a design's art, the gradient spans only the objects with a row equal to the art's, which take it. - let spanned: Vec = ids.iter().zip(item.per_target_of(s, of, &ids)).filter_map(|(id, it)| it.map(|_| *id)).collect(); - placed_across(&s.doc()?.doc, &spanned, paint, p, fill) + // With a design's art, the gradient spans only the objects with a row equal to the art's, which take it. Each + // object's box is that of the row it edits. + let d = &s.doc()?.doc; + let mut spanned = Vec::with_capacity(ids.len()); + for (id, it) in ids.iter().zip(item.per_target_of(s, of, &ids)) { + let (Some(it), Some(n)) = (it, d.node(*id)) else { continue }; + spanned.push((*id, it.resolve(&n.appearance, fill, cmd)?)); + } + placed_across(d, &spanned, paint, p, fill) } else { paint }; @@ -730,14 +736,15 @@ fn spans_targets(p: &Value, paint: &Paint) -> std::result::Result Ok(true) } -/// `paint` placed once on the union of the bounds of `ids` (each one's fill box, or the box its -/// stroke paints), at the gradient's angle and aspect: every target gets the same vector in -/// document coordinates, so the ramp runs on across them (#2127). -fn placed_across(d: &Document, ids: &[NodeId], paint: Paint, p: &Value, fill: bool) -> Paint { +/// `paint` placed once on the union of the bounds of `ids` (each one's fill box, or the box the +/// stroke it edits paints: the row given with it, `None` for the topmost), at the gradient's angle +/// and aspect: every target gets the same vector in document coordinates, so the ramp runs on +/// across them (#2127). +fn placed_across(d: &Document, ids: &[(NodeId, Option)], paint: Paint, p: &Value, fill: bool) -> Paint { let union = ids .iter() - .filter_map(|id| d.node(*id)) - .filter_map(|n| item_paint_bounds(n, None, fill).or_else(|| n.geometric_bounds())) + .filter_map(|(id, index)| Some((d.node(*id)?, *index))) + .filter_map(|(n, index)| item_paint_bounds(n, index, fill).or_else(|| n.geometric_bounds())) .filter(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite())) .reduce(|a, b| a.union(b)); let (Some(union), Paint::Gradient(g)) = (union, &paint) else { return paint }; diff --git a/crates/engine/src/tests/gradspan.rs b/crates/engine/src/tests/gradspan.rs index 9674204642..664afdbdb6 100644 --- a/crates/engine/src/tests/gradspan.rs +++ b/crates/engine/src/tests/gradspan.rs @@ -119,6 +119,28 @@ fn strokes_span_the_targets_too() { assert!(ga.start.x < 0.0 && ga.end.x > 400.0, "the stroke's box, half its weight out: {ga:?}"); } +#[test] +fn a_lower_stroke_row_spans_the_box_that_row_paints() { + let mut s = session(); + let a = rect(&mut s, 0.0, 50.0, 100.0, 100.0); + let b = rect(&mut s, 300.0, 50.0, 100.0, 100.0); + // [Fill, Stroke 40 pt, Stroke 1 pt] on both. + s.execute("appearance.addStroke", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("stroke.set", &json!({"ids": [a.0, b.0], "item": 1, "weight": 40})).unwrap(); + for aligned in [false, true] { + s.execute("paint.setStroke", &json!({"ids": [a.0, b.0], "item": 1, "aligned": aligned, "gradient": black_to_white(), "span": "selection"})) + .unwrap(); + for id in [a, b] { + let Paint::Gradient(g) = &s.doc().unwrap().doc.node(id).unwrap().appearance.stroke_at(Some(1)).unwrap().paint else { + panic!("expected a gradient on stroke row 1") + }; + // The 40 pt row reaches 20 pt past the union 0..400, not the 1 pt topmost stroke's 0.5 pt. + let geom = g.geom.expect("placed in document coordinates"); + assert!(near(geom.start, Point::new(-20.0, 100.0)) && near(geom.end, Point::new(420.0, 100.0)), "aligned {aligned}, {id:?}: {geom:?}"); + } + } +} + #[test] fn the_new_art_default_stays_unplaced() { let mut s = session(); From 527a2142d9e6a121223ca61a980177958efe5056 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 08:35:38 -0800 Subject: [PATCH 28/31] Effects: Radial Blur's dialog sends a saved Blur Center outside the bounds at the edge A Radial Blur whose saved centerX or centerY lies outside 0 to 1 draws at the nearest edge, and its dialog showed the center there. The dialog kept the saved value in its fields, though, so OK without moving the center sent that value, and effect.setParams refused it. The Blur Center box now writes the center it shows, kept within 0 to 1, into the dialog's fields on every frame, so OK stores the edge. --- crates/ui-egui/src/dialogs/effect.rs | 47 +++++++++++++++++++++++++--- 1 file changed, 42 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/dialogs/effect.rs b/crates/ui-egui/src/dialogs/effect.rs index cd089e04bd..5a4799d22d 100644 --- a/crates/ui-egui/src/dialogs/effect.rs +++ b/crates/ui-egui/src/dialogs/effect.rs @@ -321,12 +321,12 @@ fn center_round(x: f64) -> f64 { /// 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 /// Horizontal and Vertical fields beside it type the same position in percent of the bounds' width -/// and height. Changes go to `d.fields["centerX"]` and `["centerY"]`. +/// and height. The center the box shows, kept within 0 to 1, goes to `d.fields["centerX"]` and +/// `["centerY"]`. fn blur_center(ui: &mut egui::Ui, d: &mut Dialog) { use egui::{Key, Modifiers, Sense, Stroke}; let [kx, ky] = BLUR_CENTER; let mut c = [d.f64(kx, 0.5).clamp(0.0, 1.0), d.f64(ky, 0.5).clamp(0.0, 1.0)]; - let before = c; let t = Tokens::get(ui.ctx()); let zoom = d.str("method").eq_ignore_ascii_case("zoom"); form::caption(ui, "Blur Center"); @@ -404,9 +404,12 @@ fn blur_center(ui: &mut egui::Ui, d: &mut Dialog) { }); }); }); - if c != before { - d.fields.insert(kx.into(), json!(c[0])); - d.fields.insert(ky.into(), json!(c[1])); + // A saved center outside the bounds is drawn at the nearest edge, and the fields hold that + // edge too, so OK sends the center the box shows. + for (key, v) in [(kx, c[0]), (ky, c[1])] { + if d.fields.get(key).and_then(Value::as_f64) != Some(v) { + d.fields.insert(key.into(), json!(v)); + } } } @@ -1502,4 +1505,38 @@ mod tests { "OK applies it" ); } + + /// A Radial Blur whose saved Blur Center lies outside the object's bounds (a document written + /// by hand or by another build) opens with the center at the nearest edge, and OK stores that + /// edge instead of sending the saved value, which `effect.setParams` refuses. + #[test] + fn radial_blur_center_outside_the_bounds_opens_at_the_edge_and_ok_keeps_it() { + let mut app = VectorcraftApp::new(vectorcraft_engine::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": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); + app.run("select.all", json!({})).unwrap(); + app.run("effect.apply", json!({"effect": RADIAL_BLUR, "params": {"amount": 20}})).unwrap(); + { + let st = app.session.doc_mut().unwrap(); + let d = std::sync::Arc::make_mut(&mut st.doc); + let fx = &mut d.node_mut(vectorcraft_doc::NodeId(id)).unwrap().appearance.effects[0]; + fx.params["centerX"] = json!(1.5); + fx.params["centerY"] = json!(-0.25); + } + app.run("effect.dialog", json!({"effect": RADIAL_BLUR, "index": 0})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, Default::default()); + for k in 0..4 { + let input = egui::RawInput { time: Some(f64::from(k) * 0.05), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| super::super::show(&mut app, ui.ctx())); + out.textures_delta.clear(); + } + let field = |k: &str| app.ui.dialog.as_ref().unwrap().fields.get(k).and_then(Value::as_f64); + assert_eq!((field("centerX"), field("centerY")), (Some(1.0), Some(0.0)), "the fields hold the center the box shows"); + super::super::confirm(&mut app).unwrap(); + let st = app.session.doc().unwrap(); + let fx = &st.doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.effects[0]; + assert_eq!((fx.params["centerX"].as_f64(), fx.params["centerY"].as_f64()), (Some(1.0), Some(0.0)), "OK stores the edge"); + } } From 0cf2aa3f79464230074ec4942f57fe4bbaf5a411 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 08:36:31 -0800 Subject: [PATCH 29/31] Effects: removing or duplicating several aligned effects of a design's art refuses one that no object has With the art of a graph design in a series given first and aligned: true, effect.remove and effect.duplicate with `indices` skipped an effect of the art that no other object has, and edited the others. With art [shadow, roughen], a mark [shadow] and indices [0, 1], effect.remove took the mark's shadow off and succeeded. Such an edit is now an error that leaves the document and its undo history as they are, as the same index given alone already was. An object that lacks one of the effects while another object has it is still left out for that effect. --- crates/engine/src/cmd/effectcmd.rs | 10 ++++++-- crates/engine/src/cmd/graph/tests.rs | 36 ++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index 42113c9578..30b3dd6304 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -367,7 +367,8 @@ fn edit_effects( /// [`edit_effects`] for several effects of one list (`indices`): `f` gets each target's list and /// the positions of `indices` there, ascending; with `aligned`, a position a target doesn't share -/// is left out of it, and a target sharing none of them is left out. +/// is left out of it, and a target sharing none of them is left out. A position no target has is +/// an error with `none`, and nothing changes. #[allow(clippy::too_many_arguments)] fn edit_effects_at( s: &mut Session, @@ -396,7 +397,12 @@ fn edit_effects_at( // Each target's list and the positions in it, in the order the targets first come up. let mut targets: Vec<(NodeId, Option, Vec)> = vec![]; for &index in indices { - for (id, at, i) in effect_targets(s, p, item, index, cmd)? { + let found = effect_targets(s, p, item, index, cmd)?; + // An aligned effect of a design's art that no other object has is refused, as it is given alone. + if found.is_empty() { + return Err(EngineError::Other(none.into())); + } + for (id, at, i) in found { match targets.iter_mut().find(|t| t.0 == id && t.1 == at) { Some(t) => t.2.push(i), None => targets.push((id, at, vec![i])), diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index ca1f1d2c45..c533cb5e4e 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -1109,6 +1109,42 @@ fn aligned_effect_indices_past_the_end_of_a_graph_designs_art_are_refused() { assert!(rows(&s, mark).effects.is_empty()); } +/// With a graph design's art given first and `aligned: true`, `effect.remove` and `effect.duplicate` with `indices` are an +/// error and change nothing when one of the art's effects is one no other object has, as with that index given alone. +#[test] +fn aligned_effect_indices_of_a_graph_designs_art_that_no_object_has_are_refused() { + let rows = |s: &Session, id: NodeId| (*s.doc().unwrap().doc.node(id).unwrap().appearance).clone(); + let (mut s, _, art, mark) = aligned_design_art(); + // The art has a shadow and a roughen, the mark the shadow only. + s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "ids": [mark.0], "item": null})).unwrap(); + s.execute("effect.apply", &json!({"effect": "distort.roughen", "ids": [mark.0], "item": null})).unwrap(); + s.edit("Effects", |d, _| { + let effects = d.node(mark).unwrap().appearance.effects.clone(); + d.node_mut(art).unwrap().appearance.effects = effects; + d.node_mut(mark).unwrap().appearance.effects.pop(); + Ok(()) + }) + .unwrap(); + let (art_was, mark_was) = (rows(&s, art), rows(&s, mark)); + let steps = s.doc().unwrap().history.undo.len(); + for cmd in ["effect.remove", "effect.duplicate"] { + assert!(s.execute(cmd, &json!({"ids": [art.0, mark.0], "item": null, "index": 1, "aligned": true})).is_err(), "{cmd}"); + let e = s.execute(cmd, &json!({"ids": [art.0, mark.0], "item": null, "indices": [0, 1], "aligned": true})).unwrap_err(); + assert!(e.to_string().contains("no effects at indices 0, 1"), "{cmd}: {e}"); + assert_eq!((rows(&s, art), rows(&s, mark)), (art_was.clone(), mark_was.clone()), "{cmd}"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{cmd}"); + } + // With the roughen on the mark too, both of its effects are removed. + s.edit("Roughen", |d, _| { + let roughen = d.node(art).unwrap().appearance.effects[1].clone(); + d.node_mut(mark).unwrap().appearance.effects.push(roughen); + Ok(()) + }) + .unwrap(); + s.execute("effect.remove", &json!({"ids": [art.0, mark.0], "item": null, "indices": [0, 1], "aligned": true})).unwrap(); + assert!(rows(&s, mark).effects.is_empty()); +} + /// A blur on a series group makes the whole group an image, which draws the design's art with the series' other art: /// Expand Appearance does not put the art back beside the image. #[test] From cdd40789079669cf102a030ef441f7b90f1538d7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 08:42:15 -0800 Subject: [PATCH 30/31] Paste: Paste without Formatting sets pie legend label contrast from merged swatch colors Paste without Formatting sets each pie legend label in a wedge to white or black from the wedge colors before it pastes, but a wedge linked to a global swatch that the document gives another color takes the document's color only during the paste (swatchConflict "merge", the default). A light wedge merged into a dark swatch kept a black label, and a later redraw turned it white. The copied colors linked to merged swatches now take the document's color before the labels are set, so the labels match what a redraw sets. Graphic style links are left for the paste to relink. --- crates/engine/src/cmd/clipboard/resources.rs | 30 +++++++++- crates/engine/src/cmd/typemenu.rs | 7 +++ crates/engine/src/tests/clipboard.rs | 62 ++++++++++++++++++++ docs/mcp.md | 4 +- 4 files changed, 101 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index f457712415..fa69f1f820 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -595,6 +595,8 @@ struct Relink { styles: BTreeMap, /// Swatch (its name in the document) → the colour linked colours show at 100 %. colors: BTreeMap, + /// Leave graphic style links as they are ([`Clipboard::show_merged_colors`]). + keep_styles: bool, } impl Relink { @@ -674,7 +676,9 @@ impl Relink { /// Relink a node tree (the mirror of [`node_refs`]). fn node(&self, n: &mut Node) { self.appearance(&mut n.appearance); - n.extras_mut().graphic_style = n.extras().graphic_style.and_then(|id| self.styles.get(&id).copied()); + if !self.keep_styles { + n.extras_mut().graphic_style = n.extras().graphic_style.and_then(|id| self.styles.get(&id).copied()); + } if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) { self.node(Arc::make_mut(&mut m.art)); } @@ -1109,6 +1113,30 @@ impl Clipboard { self.import_used(d, &self.used(), choices, same_doc) } + /// Give the objects' colors linked to a global or spot swatch whose conflict with `d` + /// `choices` merge the color that swatch has in `d`, as pasting into `d` gives them (Paste + /// without Formatting sets its pie legend labels' contrast from the wedge colors before it + /// pastes). Nothing changes for the document the objects came from (`same_doc`). + pub(crate) fn show_merged_colors(&mut self, d: &Document, choices: &SwatchChoices, same_doc: bool) { + if same_doc { + return; + } + let used = self.used(); + let colors: BTreeMap = self + .conflicts(d, &used) + .into_iter() + .filter(|(w, _)| choices.of(&w.name) == SwatchChoice::Merge) + .filter_map(|(w, _)| d.global_color(&w.name).map(|c| (w.name.clone(), c))) + .collect(); + if colors.is_empty() { + return; + } + let relink = Relink { colors, keep_styles: true, ..Default::default() }; + for n in &mut self.nodes { + relink.node(n); + } + } + /// [`Self::import_into`] for the resources `used` names. Each style, symbol, pattern and brush /// comes after the styles, symbols, patterns and brushes it uses ([`use_order`]), so that it is /// compared and relinked with their names here, and each loop of definitions that use each diff --git a/crates/engine/src/cmd/typemenu.rs b/crates/engine/src/cmd/typemenu.rs index 0701f6eeca..da930d7e59 100644 --- a/crates/engine/src/cmd/typemenu.rs +++ b/crates/engine/src/cmd/typemenu.rs @@ -1783,6 +1783,13 @@ fn strip_formatting(n: &mut vectorcraft_doc::Node) { fn paste_plain(s: &mut Session, p: &Value) -> Result { let saved = s.clipboard.nodes.clone(); + // Pasted colors linked to a swatch merged with the document's show its color, so a pasted pie's legend labels take + // the contrast of the wedges as pasted. A `swatchConflict` the paste refuses is left to its error. + if let (Ok(choices), Ok(st)) = (super::clipboard::SwatchChoices::parse("edit.pasteWithoutFormatting", p), s.doc()) { + let same_doc = s.clipboard.source_doc == Some(st.uid); + let d = std::sync::Arc::clone(&st.doc); + s.clipboard.show_merged_colors(&d, &choices, same_doc); + } for n in &mut s.clipboard.nodes { strip_formatting(n); } diff --git a/crates/engine/src/tests/clipboard.rs b/crates/engine/src/tests/clipboard.rs index 368bc6de10..519974f33d 100644 --- a/crates/engine/src/tests/clipboard.rs +++ b/crates/engine/src/tests/clipboard.rs @@ -1034,6 +1034,68 @@ fn a_repainted_wedge_sets_its_label_color_when_pasted_without_formatting() { assert_eq!(pasted, labels(&s, p), "copied as {before:?}"); } +/// Wedges linked to a global swatch that the destination document gives a dark color, merged on Paste without +/// Formatting, give their legend labels white characters, as a redraw does; added under a new name, they keep the +/// copied light color and black labels. +#[test] +fn wedges_merged_into_a_dark_swatch_give_white_labels_when_pasted_without_formatting() { + let csv = ",North,South\nP,1,1"; + fn labels(s: &Session, id: NodeId) -> Vec<(String, Paint)> { + let mut out = vec![]; + node(s, id).walk(&mut |n| { + if let NodeKind::Text(t) = &n.kind + && ["North", "South"].contains(&t.plain_text().as_str()) + { + out.push((t.plain_text(), t.first_style().fill.clone())); + } + }); + out + } + let both = |c: Color| vec![("North".to_string(), Paint::solid(c)), ("South".to_string(), Paint::solid(c))]; + for (conflict, expected) in [("merge", Color::WHITE), ("add", Color::BLACK)] { + let mut s = session(); + let g = id_of(&s.execute("graph.create", &json!({"type": "pie", "x": 50, "y": 50, "width": 200, "height": 200, "csv": csv})).unwrap()); + s.execute("graph.setType", &json!({"id": g.0, "pieLegend": "wedges"})).unwrap(); + s.execute("swatch.new", &json!({"name": "Ink", "color": "#ffffff", "global": true})).unwrap(); + let mut wedges = vec![]; + node(&s, g).walk(&mut |m| { + if let NodeKind::Path { .. } = m.kind { + wedges.push(m.id.0); + } + }); + s.execute("paint.setFill", &json!({"ids": wedges, "swatch": "Ink"})).unwrap(); + s.execute("graph.setData", &json!({"id": g.0, "csv": csv})).unwrap(); + assert_eq!(labels(&s, g), both(Color::BLACK), "light wedges have black labels"); + copy(&mut s, &[g]); + new_doc(&mut s); + s.execute("swatch.new", &json!({"name": "Ink", "color": "#000000", "global": true})).unwrap(); + let p = ids_of(&s.execute("edit.pasteWithoutFormatting", &json!({"swatchConflict": conflict})).unwrap())[0]; + let pasted = labels(&s, p); + assert_eq!(pasted, both(expected), "{conflict}"); + s.execute("graph.setData", &json!({"id": p.0, "csv": csv})).unwrap(); + assert_eq!(pasted, labels(&s, p), "{conflict}: as a redraw sets them"); + } +} + +/// An object linked to a graphic style and to a swatch merged with the document's keeps its graphic style link when +/// pasted without formatting, and its color shows the document's swatch. +#[test] +fn a_merged_swatch_keeps_graphic_style_links_when_pasted_without_formatting() { + let mut s = session(); + let r = swatched_rect(&mut s, "Ink", "#ffffff"); + sel(&mut s, &[r]); + s.execute("graphicStyle.new", &json!({"name": "Sun"})).unwrap(); + copy(&mut s, &[r]); + new_doc(&mut s); + s.execute("swatch.new", &json!({"name": "Ink", "color": "#000000", "global": true})).unwrap(); + let v = s.execute("edit.pasteWithoutFormatting", &json!({})).unwrap(); + assert_eq!(v["merged"], 1); + let p = ids_of(&v)[0]; + let style = node(&s, p).extras().graphic_style.and_then(|id| doc(&s).graphic_style_by_id(id)).map(|g| g.name.clone()); + assert_eq!(style.as_deref(), Some("Sun")); + assert_eq!(fill(&s, p), linked(hex("#000000"), "Ink", 1.0)); +} + /// When one pie's wedge of a series is repainted and another pie's wedge of that series is not, each pasted legend label /// takes the contrast of the wedge it is in. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index ac0a768306..eed031a2b1 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7228,7 +7228,9 @@ to}]}`. `edit.pasteWithoutFormatting` sets the labels of a pasted graph in a new graph's label character style and paragraph attributes, keeping each label's alignment and where it starts. The pasted graph no longer keeps its labels' character and paragraph formats, so a later `graph.setData` or `graph.setType` sets the labels the same way. The rest of the -graph's art is pasted as it was copied. +graph's art is pasted as it was copied. A pie's legend labels in its wedges are white on a dark wedge and black on a +light one, by the wedge colors as pasted: a wedge linked to a swatch merged with the document's takes that swatch's +color first. A global or spot swatch whose name the document gives another colour is a conflict: `clipboard.conflicts` lists them, and `swatchConflict` answers: `"merge"` (the default: the objects take the document's swatch), `"add"` (the From dc8054fb3929005d8a8dda2e80883bc48ea55989 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 08:45:10 -0800 Subject: [PATCH 31/31] PSD: a slices resource cut short warns that the slices were left out When image resource 1050 declared more bytes than the image resources hold, the lookup stopped as if the file stored no slices, and Open and Place brought the artwork in without the warning that the slices were left out. The new psdread::resource tells a cut-short resource 1050 apart from one that is absent or that follows another block cut short, and the slices reader passes that error on, so the warning names it. Other resource readers keep their behavior. --- crates/engine/src/cmd/fileio/psdread.rs | 55 ++++++++++++++----- crates/engine/src/cmd/fileio/psdslices.rs | 8 +-- .../engine/src/cmd/fileio/tests_psdslices.rs | 23 ++++++++ 3 files changed, 67 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/cmd/fileio/psdread.rs b/crates/engine/src/cmd/fileio/psdread.rs index ed9f08a731..8571a19e4e 100644 --- a/crates/engine/src/cmd/fileio/psdread.rs +++ b/crates/engine/src/cmd/fileio/psdread.rs @@ -174,23 +174,48 @@ pub fn resolution(bytes: &[u8]) -> Option<(f64, f64)> { /// blocks whose signature is `8BIM` are given. pub(super) fn resources(resources: &[u8], signed: bool) -> impl Iterator { let mut r = Reader::new(resources); - std::iter::from_fn(move || { - if r.rest().is_empty() { - return None; + std::iter::from_fn(move || if r.rest().is_empty() { None } else { block(&mut r).ok() }) + .filter(move |(ours, ..)| *ours || !signed) + .map(|(_, id, name, data)| (id, name, data)) +} + +/// The data of the first `8BIM` image resource block `id` of `resources`. `None` when there is +/// none before the blocks end or before a block that is cut short ahead of it. An error when +/// that block itself is cut short. +pub(super) fn resource(resources: &[u8], id: u16) -> Result, String> { + let mut r = Reader::new(resources); + while !r.rest().is_empty() { + match block(&mut r) { + Ok((true, i, _, data)) if i == id => return Ok(Some(data)), + Ok(_) => {} + Err(Some((true, i))) if i == id => return Err(TRUNCATED.into()), + Err(_) => return Ok(None), } - let ours = r.take(4).ok()? == b"8BIM"; - let id = r.u16().ok()?; + } + Ok(None) +} + +/// An image resource block: whether its signature is `8BIM`, its id, its name (the bytes of its +/// Pascal string) and its data. +type Block<'a> = (bool, u16, &'a [u8], &'a [u8]); + +/// The image resource block that `r` starts with. When it is cut short, the error gives whether +/// its signature is `8BIM` and its id, when those were read. +fn block<'a>(r: &mut Reader<'a>) -> Result, Option<(bool, u16)>> { + let ours = r.take(4).map_err(|_| None)? == b"8BIM"; + let id = r.u16().map_err(|_| None)?; + let mut rest = || -> Result<(&'a [u8], &'a [u8]), String> { // A Pascal string padded to an even size, length byte included. - let len = usize::from(r.u8().ok()?); - let name = r.take(len).ok()?; - r.take((len + 1) % 2).ok()?; - let size = usize::try_from(r.u32().ok()?).ok()?; - let data = r.take(size).ok()?; - r.take(size % 2).ok()?; - Some((ours, id, name, data)) - }) - .filter(move |(ours, ..)| *ours || !signed) - .map(|(_, id, name, data)| (id, name, data)) + let len = usize::from(r.u8()?); + let name = r.take(len)?; + r.take((len + 1) % 2)?; + let size = usize::try_from(r.u32()?).map_err(|_| TRUNCATED.to_string())?; + let data = r.take(size)?; + r.take(size % 2)?; + Ok((name, data)) + }; + let (name, data) = rest().map_err(|_| Some((ours, id)))?; + Ok((ours, id, name, data)) } /// The resource naming the document's clipping path. diff --git a/crates/engine/src/cmd/fileio/psdslices.rs b/crates/engine/src/cmd/fileio/psdslices.rs index ea87f70797..9f76de9b15 100644 --- a/crates/engine/src/cmd/fileio/psdslices.rs +++ b/crates/engine/src/cmd/fileio/psdslices.rs @@ -18,7 +18,7 @@ use vectorcraft_doc::{SliceKind, SliceOptions}; use vectorcraft_geom::Rect; -use super::psdread::{Reader, TRUNCATED, header, resources}; +use super::psdread::{Reader, TRUNCATED, header, resource}; /// The image resource that holds the slices. const SLICES: u16 = 1050; @@ -51,12 +51,12 @@ struct Stored { } /// The slices PSD or PSB file `bytes` stores. `None` when it stores none (no `8BIM` resource 1050 -/// before the image resources end or are cut short). An error when the file isn't a PSD or PSB -/// file, or its slices can't be read. +/// before the image resources end, or before a block that is cut short ahead of it). An error when +/// the file isn't a PSD or PSB file, resource 1050 is cut short, or its slices can't be read. fn read(bytes: &[u8]) -> Result, String> { let mut r = Reader::new(bytes); let h = header(&mut r)?; - let Some((_, _, data)) = resources(h.resources, true).find(|(id, _, _)| *id == SLICES) else { return Ok(None) }; + let Some(data) = resource(h.resources, SLICES)? else { return Ok(None) }; Ok(Some(Stored { slices: decode(data)?, size: (h.width, h.height) })) } diff --git a/crates/engine/src/cmd/fileio/tests_psdslices.rs b/crates/engine/src/cmd/fileio/tests_psdslices.rs index 42dc33c600..9748502de2 100644 --- a/crates/engine/src/cmd/fileio/tests_psdslices.rs +++ b/crates/engine/src/cmd/fileio/tests_psdslices.rs @@ -371,6 +371,29 @@ fn slices_that_cant_be_read_warn_and_the_file_still_opens() { assert!(warnings(&r).is_empty() && slices(&s).is_empty(), "{r}"); } +#[test] +fn a_slices_resource_cut_short_warns_and_the_file_still_opens() { + let good = v6(&[user("a", [0, 0, 5, 5])], &[]); + // Image resource `id`, the last of the image resources, declares 10 bytes more than they hold. + let cut = |layers: bool, id: u16, data: &[u8]| { + let mut f = with_resource(&psd(layers), id, data); + let sig = [&b"8BIM"[..], &id.to_be_bytes()].concat(); + let at = f.windows(6).rposition(|w| w == sig.as_slice()).unwrap() + 8; + f[at..at + 4].copy_from_slice(&(data.len() as u32 + 10).to_be_bytes()); + f + }; + for layers in [true, false] { + let (s, r) = open(&cut(layers, 1050, &good), json!({})); + let w = warnings(&r); + assert!(w.iter().any(|w| w.starts_with("the slices can't be read (") && w.contains("cut short")), "{w:?}"); + assert!(slices(&s).is_empty()); + assert!(s.doc().unwrap().doc.art_bounds().is_some()); + // Another resource cut short says nothing about slices. + let (s, r) = open(&cut(layers, 1051, &[0, 1]), json!({})); + assert!(warnings(&r).is_empty() && slices(&s).is_empty(), "{r}"); + } +} + #[test] fn slices_are_clipped_to_the_canvas_and_those_outside_it_are_left_out() { let data = v6(&[user("over", [-5, -5, 5, 30]), user("out", [25, 0, 30, 5]), user("empty", [4, 4, 4, 9]), user("in", [1, 1, 2, 2])], &[]);